text:
#if 0

#include <dvo/visualization/pcl_camera_trajectory_visualizer.h>

#include <memory>
#include <boost/thread.hpp>

#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/filters/approximate_voxel_grid.h>
#include <pcl/visualization/pcl_visualizer.h>

#include <dvo/visualization/async_point_cloud_builder.h>
#include <dvo/visualization/point_cloud_aggregator.h>

namespace dvo
{
namespace visualization
{
namespace internal
{

class PclTrajectoryVisualizer : public dvo::visualization::TrajectoryVisualizer
{
public:
  PclTrajectoryVisualizer(std::string& name)
  {
    name_ = name;
  }

  virtual TrajectoryVisualizer& add(const Eigen::Affine3d& pose)
  {
    PointPair latest;
    latest.second.x = pose.translation()(0);
    latest.second.y = pose.translation()(1);
    latest.second.z = pose.translation()(2);

    if(pairs_.empty())
    {
      ::std::mutex::scoped_lock lock(m_);

      pairs_.push_back(latest); // add to list - this copies the object
      pairs_.back().first = &(pairs_.back().second); // set pointer to second point in newly allocated object
      last_ = pairs_.begin();
    }

    latest.first = &(pairs_.back().second);

    {
      std::mutex::scoped_lock lock(m_);
      pairs_.push_back(latest);
    }

    return *this;
  }

  void updateVisualizer(pcl::visualization::PCLVisualizer& visualizer)
  {
    if(pairs_.empty()) return;

    pcl::PointCloud<pcl::PointXYZ>::Ptr cloud(new pcl::PointCloud<pcl::PointXYZ>);

    for(list::iterator it = pairs_.begin(); it != pairs_.end(); ++it)
    {
      cloud->points.push_back(it->second);
    }
    for(list::reverse_iterator it = pairs_.rbegin(); it != pairs_.rend(); ++it)
    {
      cloud->points.push_back(it->second);
    }

    visualizer.removeShape(name());
    visualizer.addPolygon<pcl::PointXYZ>(cloud, name());
    visualizer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR,  color().r, color().g, color().b, name());
    visualizer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 4, name());
  }
private:
  class PointPair
  {
  public:
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW;
    pcl::PointXYZ second;
    pcl::PointXYZ *first;
  };

  typedef std::list<PointPair, Eigen::aligned_allocator<PointPair> > list;

  list pairs_;
  list::iterator last_;

  std::mutex m_;
};

class PclCameraVisualizer : public dvo::visualization::CameraVisualizer
{
public:
  PclCameraVisualizer(std::string& name)
  {
    name_ = name;
  }

  virtual ~PclCameraVisualizer()
  {
  }

  virtual void show(Option option = ShowCameraAndCloud)
  {
    visibility_ = option;
  }

  virtual void hide()
  {
    visibility_ = ShowNothing;
  }

  virtual CameraVisualizer& update(const dvo::core::RgbdImage& img, const Eigen::Affine3d& pose)
  {
    ::std::mutex::scoped_lock lock(m_);

    cloud_.reset(new dvo::visualization::AsyncPointCloudBuilder::BuildJob(img, pose));
    return *this;
  }

  void updateVisualizer(pcl::visualization::PCLVisualizer& visualizer, PointCloudAggregator& aggregator)
  {
    std::mutex::scoped_lock lock(m_);

    std::string cube_id = name() + "_cube";

    visualizer.removeShape(cube_id);

    if(visibility_ != ShowCameraAndCloud)
    {
      //visualizer.removePointCloud(name());
      aggregator.remove(name());
    }

    if(visibility_ != ShowNothing && cloud_)
    {
      if(visibility_ == ShowCameraAndCloud)
      {
        aggregator.add(name(), cloud_->build());
        //if(!visualizer.updatePointCloud(cloud_->build(), name()))
        //{
        //  visualizer.addPointCloud(cloud_->build(), name());
        //}
        //visualizer.setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, name());
      }
      //visualizer.addCube(cloud_->pose.translation().cast<float>(), Eigen::Quaternionf(cloud_->pose.rotation().cast<float>()), 0.05, 0.05, 0.05, cube_id);
      //visualizer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_COLOR, color().r, color().g, color().b, cube_id);
      //visualizer.setShapeRenderingProperties(pcl::visualization::PCL_VISUALIZER_REPRESENTATION, pcl::visualization::PCL_VISUALIZER_REPRESENTATION_SURFACE, cube_id);
    }
  }
private:
  Option visibility_;
  std::shared_ptr<dvo::visualization::AsyncPointCloudBuilder::BuildJob> cloud_;
  std::mutex m_;
};

struct PclCameraTrajectoryVisualizerImpl
{
public:
  typedef std::shared_ptr<PclCameraVisualizer> PclCameraVisualizerPtr;
  typedef std::shared_ptr<PclTrajectoryVisualizer> PclTrajectoryVisualizerPtr;

  typedef std::map<std::string, PclCameraVisualizerPtr> CameraVisualizerMap;
  typedef std::map<std::string, PclTrajectoryVisualizerPtr> TrajectoryVisualizerMap;

  PclCameraTrajectoryVisualizerImpl(bool render_thread = true)
  {
    if(render_thread)
    {
      visualizer_thread_.reset(new std::thread(std::bind(&PclCameraTrajectoryVisualizerImpl::execVisualizerThread, this)));

      // wait for visualizer_ being created
      while(!visualizer_)
      {
        std::this_thread::yield();
      }
    }
    else
    {
      initVisualizer();
    }
  }

  ~PclCameraTrajectoryVisualizerImpl()
  {
    if(visualizer_ && !visualizer_->wasStopped())
    {
#if ((PCL_MAJOR_VERSION == 1) && (PCL_MINOR_VERSION > 5))
      // only available in PCL >= 1.6
      visualizer_->close();
#endif
    }
    visualizer_thread_->join();
  }

  void bindSwitchToKey(Switch& s, std::string& key)
  {
    visualizer_->registerKeyboardCallback(&PclCameraTrajectoryVisualizerImpl::onSwitchKeyPressed, new SwitchKeyBinding(s, key));
  }

  pcl::visualization::PCLVisualizer& visualizer()
  {
    return *visualizer_;
  }

  CameraVisualizer::Ptr camera(std::string name)
  {
    CameraVisualizerMap::iterator camera = camera_visualizers_.find(name);

    if(camera_visualizers_.end() == camera)
    {
      camera = camera_visualizers_.insert(
          std::make_pair(name, PclCameraVisualizerPtr(new PclCameraVisualizer(name)))
      ).first;
    }

    return camera->second;
  }

  TrajectoryVisualizer::Ptr trajectory(std::string name)
  {
    TrajectoryVisualizerMap::iterator trajectory = trajectory_visualizers_.find(name);

    if(trajectory_visualizers_.end() == trajectory)
    {
      trajectory = trajectory_visualizers_.insert(
          std::make_pair(name, PclTrajectoryVisualizerPtr(new PclTrajectoryVisualizer(name)))
      ).first;
    }

    return trajectory->second;
  }

  void reset()
  {
    camera_visualizers_.clear();
    trajectory_visualizers_.clear();
  }

  void initVisualizer()
  {
    visualizer_.reset(new pcl::visualization::PCLVisualizer("viewer"));
    visualizer_->setBackgroundColor(0.3, 0.3, 0.3);
    visualizer_->initCameraParameters();
  }

  void render(int milliseconds)
  {
    // safeguard against segfault when updating the visualizer from multiple threads
    if(visualizer_thread_ && visualizer_thread_->get_id() != std::this_thread::get_id())
    {
      static bool warned = false;

      if(!warned)
      {
        warned = true;
        std::cerr << "WARNING: called PclCameraTrajectoryVisualizer::render() from wrong thread!" << std::endl;
      }
      return;
    }

    CameraVisualizerMap local_cameras;
    TrajectoryVisualizerMap local_trajectories;

    {
      std::mutex::scoped_lock lock(m_);
      local_cameras = camera_visualizers_;
      local_trajectories = trajectory_visualizers_;
    }

    // sync visualizer
    std::mutex::scoped_lock lock(sync_);

    for(CameraVisualizerMap::iterator it = local_cameras.begin(); it != local_cameras.end(); ++it)
    {
      it->second->updateVisualizer(*visualizer_, cloud_aggregator_);
    }

    AsyncPointCloudBuilder::PointCloud::Ptr aggregated_cloud = cloud_aggregator_.build();

    if(!visualizer_->updatePointCloud(aggregated_cloud, "aggregated_cloud"))
    {
      visualizer_->addPointCloud(aggregated_cloud, "aggregated_cloud");
    }

    for(TrajectoryVisualizerMap::iterator it = local_trajectories.begin(); it != local_trajectories.end(); ++it)
    {
      it->second->updateVisualizer(*visualizer_);
    }

    visualizer_->spinOnce(milliseconds);
  }
  std::mutex sync_;
private:
  std::shared_ptr<pcl::visualization::PCLVisualizer> visualizer_;
  std::shared_ptr<std::thread> visualizer_thread_;
  std::mutex m_;

  CameraVisualizerMap camera_visualizers_;
  TrajectoryVisualizerMap trajectory_visualizers_;

  std::map<std::string, PclCameraVisualizer::Ptr> clouds_;
  PointCloudAggregator cloud_aggregator_;

  void execVisualizerThread()
  {
    initVisualizer();

    while(!visualizer_->wasStopped())
    {
      render(1);
    }
    visualizer_.reset();
  }

  struct SwitchKeyBinding
  {
    Switch& s;
    std::string key;
    SwitchKeyBinding(Switch& s, std::string& key)
      : s(s), key(key)
    {
    }
  };

  static void onSwitchKeyPressed(const pcl::visualization::KeyboardEvent& e, void* data)
  {
    SwitchKeyBinding* binding = (SwitchKeyBinding*) data;
    if(e.keyDown() && e.getKeySym() == binding->key)
    {
      binding->s.toggle();
    }
  }
};
} /* namespace internal */

PclCameraTrajectoryVisualizer::PclCameraTrajectoryVisualizer(bool async) :
    impl_(new internal::PclCameraTrajectoryVisualizerImpl(async))
{
}

PclCameraTrajectoryVisualizer::~PclCameraTrajectoryVisualizer()
{
  delete impl_;
}

dvo::visualization::CameraVisualizer::Ptr PclCameraTrajectoryVisualizer::camera(std::string name)
{
  return impl_->camera(name);
}

dvo::visualization::TrajectoryVisualizer::Ptr PclCameraTrajectoryVisualizer::trajectory(std::string name)
{
  return impl_->trajectory(name);
}

void PclCameraTrajectoryVisualizer::bindSwitchToKey(Switch& s, std::string key)
{
  impl_->bindSwitchToKey(s, key);
}

void PclCameraTrajectoryVisualizer::render(int milliseconds)
{
  impl_->render(milliseconds);
}

std::mutex& PclCameraTrajectoryVisualizer::sync()
{
  return impl_->sync_;
}

pcl::visualization::PCLVisualizer& PclCameraTrajectoryVisualizer::visualizer()
{
  return impl_->visualizer();
}

void PclCameraTrajectoryVisualizer::reset()
{
  impl_->reset();
}

} /* namespace visualization */
} /* namespace dvo */

#endif


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <link rel="shortcut icon" type="image/png" href="images/favicon.png"/>

    <title>Landolt</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/modern-business.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

Home

Kontakt

Wegbeschreibung

Wegbeschreibung

Kleinandelfingen liegt an der Schnellstrasse A4 zwischen Winterthur und Schaffhausen. In einer halben Stunde erreichen Sie uns von Zürich mit dem Auto.

Nach der Ausfahrt Kleinandelfingen folgen Sie der Schaffhauserstrasse Richtung Andelfingen. Unser Gebäude befindet sich auf der linken Strassenseite 100 m vor der Holzbrücke über die Thur.

.

Landolt + Co. AG

Totalunternehmung RDN
Schaffhauserstrasse 10
8451 Kleinandelfingen

  052 305 29 69

  052 317 27 94

 info@landolt-rdn.ch

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Symsite\Bundle\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symsite\Bundle\AdminBundle\Entity\BaseEntity;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Article
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Symsite\Bundle\BlogBundle\Entity\ArticleRepository")
 * @ORM\HasLifecycleCallbacks
 */
class Article extends BaseEntity
{
    public static $statuses = ['Published', 'Draft', 'Pending', 'Trash'];

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="title", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $title;

    /**
     * @var string
     *
     * @ORM\Column(name="body", type="text")
     * @Assert\NotBlank()
     */
    private $body;

    /**
     * @var string
     *
     * @ORM\Column(name="status", type="string", length=64)
     * @Assert\Choice(callback = {Article::class, "getStatuses"})
     */
    private $status;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="published_at", type="datetime")
     * @Assert\DateTime()
     */
    private $publishedAt;

    /**
     * @var Category
     *
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="articles")
     * @ORM\JoinColumn(onDelete="SET NULL")
     */
    protected $category;

    /**
     * @ORM\ManyToMany(targetEntity="Tag", inversedBy="articles")
     * @ORM\JoinColumn(onDelete="CASCADE")
     */
    protected $tags;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->tags = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Set title
     *
     * @param string $title
     *
     * @return Article
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set body
     *
     * @param string $body
     *
     * @return Article
     */
    public function setBody($body)
    {
        $this->body = $body;

        return $this;
    }

    /**
     * Get body
     *
     * @return string
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * Get summary
     *
     * @return mixed
     */
    public function getSummary()
    {
        return explode('<!--more-->', $this->body)[0];
    }

    /**
     * Set status
     *
     * @param string $status
     *
     * @return Article
     */
    public function setStatus($status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * Get status
     *
     * @return string
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Set publishedAt
     *
     * @param \DateTime $publishedAt
     *
     * @return Article
     */
    public function setPublishedAt($publishedAt)
    {
        $this->publishedAt = $publishedAt;

        return $this;
    }

    /**
     * Get publishedAt
     *
     * @return \DateTime
     */
    public function getPublishedAt()
    {
        return $this->publishedAt;
    }

    /**
     * Get statuses
     *
     * @return array
     */
    public static function getStatuses()
    {
        return self::$statuses;
    }

    /**
     * Set category
     *
     * @param \Symsite\Bundle\BlogBundle\Entity\Category $category
     *
     * @return Article
     */
    public function setCategory(\Symsite\Bundle\BlogBundle\Entity\Category $category = null)
    {
        $this->category = $category;

        return $this;
    }

    /**
     * Get category
     *
     * @return \Symsite\Bundle\BlogBundle\Entity\Category
     */
    public function getCategory()
    {
        return $this->category;
    }

    /**
     * Add tag
     *
     * @param \Symsite\Bundle\BlogBundle\Entity\Tag $tag
     *
     * @return Article
     */
    public function addTag(\Symsite\Bundle\BlogBundle\Entity\Tag $tag)
    {
        $this->tags[] = $tag;

        return $this;
    }

    /**
     * Remove tag
     *
     * @param \Symsite\Bundle\BlogBundle\Entity\Tag $tag
     */
    public function removeTag(\Symsite\Bundle\BlogBundle\Entity\Tag $tag)
    {
        $this->tags->removeElement($tag);
    }

    /**
     * Get tags
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTags()
    {
        return $this->tags;
    }
}


text:
package pricemap

import org.scalajs.dom
import org.scalajs.jquery._

import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global ⇒ g, literal ⇒ L, newInstance ⇒ jsNew}
import scalaz.State._
import scalaz._

object Controller {
  def initCanvas: State[ApplicationState, dom.html.Canvas] = for {
    _ ← modify((s: ApplicationState) ⇒ s.canvas match {
      case None ⇒ s
      case _ ⇒ s
    })
    s ← get
  } yield s.canvas.get

  def increaseLoadCount: State[ApplicationState, Int] = for {
    _ ← modify {
      (s: ApplicationState) ⇒ s.copy(loadCount = s.loadCount + 1)
    }
    _ ← modify {
      (s: ApplicationState) ⇒ if (s.loadCount == 1) {
        val timer = js.timers.setTimeout(Configuration.loadTimeout) {
          jQuery("#loading").removeClass("hidden")
        }
        s.copy(loadTimer = Some(timer))
      } else s
    }
    s ← get
  } yield s.loadCount

  def decreaseLoadCount: State[ApplicationState, Int] = for {
    _ ← modify {
      (s: ApplicationState) ⇒
        s.copy(loadCount = s.loadCount - 1)
    }
    _ ← modify {
      (s: ApplicationState) ⇒
        if (s.loadCount == 0) {
          jQuery("#loading").addClass("hidden")
          s.copy(loadTimer = s.loadTimer match {
            case Some(timer) ⇒
              js.timers.clearTimeout(timer)
              None
            case _ ⇒ None
          })
        } else s
    }
    s ← get
  } yield s.loadCount

  def drawCanvas: State[ApplicationState, Unit] = for {
    _ ← modify {
      (s: ApplicationState) ⇒
        val limit = 5.0
        val pixelRatio = g.window.devicePixelRatio

        s
    }
  } yield ()

  def loadData: State[ApplicationState, Unit] = for {
    url ← State[ApplicationState, String] {
      (s: ApplicationState) ⇒
        val url = s"/data/grid?location=${s.currentMap}&" +
          s"date=${s.currentDate.getFullYear()}-" +
          s"${s.currentDate.getMonth()}-" +
          s"${s.currentDate.getDay()}&" +
          s"type=${Util.objectTypeNumber(s.objectType)}"
        (s, url)
    }
  } yield ()

}


text:
#include "Main.h"
#include "cachemap.h"
#include <stdint.h>
#include <sstream>
#include <boost\filesystem.hpp>
#include <Windows.h>

#include <unordered_set>

#define DEBUG 0
#define ATTACH_DEBUGGER 0
#define GCONTEXT_DEBUG 0
#define CREATE_TEXTURE_DEBUG 0

#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
string gcontext_debug_file = "tonberry\\debug\\global_context.log";
#endif

#if DEBUG
double PCFreq = 0.0;
__int64 CounterStart = 0;
string debug_file = "tonberry\\tests\\timing.csv";
ofstream debug(debug_file, ofstream::out | ofstream::app);

void StartCounter()
{
    LARGE_INTEGER li;
    if(!QueryPerformanceFrequency(&li))
	cout << "QueryPerformanceFrequency failed!\n";

    PCFreq = double(li.QuadPart)/1000000.0;

    QueryPerformanceCounter(&li);
    CounterStart = li.QuadPart;
}

double GetCounter()
{
    LARGE_INTEGER li;
    QueryPerformanceCounter(&li);
    return double(li.QuadPart-CounterStart)/PCFreq;
}
#endif
/*********************************
*								 *
*$(SolutionDir)$(Configuration)\ *
*								 *
*********************************/
//-------------
/*#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>*/
//-------------

#ifndef ULTRA_FAST
bool g_ReportingEvents = false;
#endif

namespace fs = boost::filesystem;

GlobalContext *g_Context;

typedef enum {
	MATCH		= 0,
	NOMATCH		= 1,
	COLLISION	= 2
}Matchtype;

void GraphicsInfo::Init()
{
    _Device = NULL;
    _Overlay = NULL;
}

void GraphicsInfo::SetDevice(LPDIRECT3DDEVICE9 Device)
{
    Assert(Device != NULL, "Device == NULL");
    D3D9Base::IDirect3DSwapChain9* pSwapChain;
    HRESULT hr = Device->GetSwapChain(0, &pSwapChain);
    Assert(SUCCEEDED(hr), "GetSwapChain failed");
    hr = pSwapChain->GetPresentParameters(&_PresentParameters);
    Assert(SUCCEEDED(hr), "GetPresentParameters failed");
    pSwapChain->Release();
    hr = Device->GetCreationParameters(&_CreationParameters);
    Assert(SUCCEEDED(hr), "GetCreationParameters failed");
    _Device = Device;
}

template <typename T>
T ToNumber(const std::string& Str)	//convert string to unsigned long long -> uint64_t
{
    T Number;
    std::stringstream S(Str);
	S >> Number;
    return Number;
}

struct BigInteger_Hash
{
	size_t operator()(const BigInteger& b) const
	{
		return std::hash<string>()(b.getNumber());
	}
};

//Debug control variable
bool debugmode = false;

//Global Variables
//vector<int> pixval;
int pixval[64];
//vector<int> pixval2;
int pixval2[98];
//vector<int> objval;
int objval[64];
unordered_map<uint64_t, string> hashmap;	//Hashmap of unique hashvals
unordered_map<uint64_t, string> collmap;	//Hashmap of collision duplicates
unordered_map<BigInteger, uint64_t, BigInteger_Hash> hash2map;			//Map of hashval2 -> StringToUint64(hashval2)
unordered_map<string, string> coll2map;
unordered_map<uint64_t, string> objmap;
unordered_map<uint64_t, string>::iterator it;
unordered_map<string, string>::iterator it2;
unordered_set<uint64_t> persistent_hashes;	// holds hashes that should persist in the cache
unordered_set<uint64_t> sysfld_hashes;		// holds sysfld hashes
unordered_set<uint64_t> iconfl_hashes;		// holds iconfl hashes
uint64_t hashval; //current hashval of left half of memory
uint64_t objtop; //object in top left corner of memory
uint64_t objbot; //object in bottom left corner of memory
BigInteger hashval2; //hashval for algo 2

float resize_factor;
string texdir("");

//TextureCache
size_t cache_size = 250;
TextureCache * texcache;

void initCache(){
	texcache = new TextureCache(cache_size);
}

void loadprefs ()
{
	resize_factor = 4.0;
	ifstream prefsfile;
	prefsfile.open ("tonberry\\prefs.txt", ifstream::in);
	if (prefsfile.is_open()){
		string line;
		while ( getline(prefsfile, line) ){
			if (line.empty() || line[0] == '#') continue;
			size_t eq = line.find("=");
			if (eq != string::npos) {
				string param = line.substr(0, eq);
				if (param == "resize_factor")
					resize_factor = (float)atoi(line.substr(eq + 1, line.length()).c_str()); //make sure no spaces in prefs file
				else if (param == "debug_mode")
					debugmode = (line.substr(eq + 1, line.length()) == string("yes"));
				else if (param == "cache_size")
					cache_size = (unsigned)atoi(line.substr(eq + 1, line.length()).c_str());
				else if (param == "texture_dir") {
					texdir = line.substr(eq + 1, line.length());
					if (texdir.back() != '/') texdir += "/";
				}
			}
			//if (line.substr(0) == string("#"));
		}
		prefsfile.close();
	}

	//cache_size = max(cache_size, 100U);
	//cache_size = min(cache_size, 800U);

#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
	ofstream debug(gcontext_debug_file, fstream::out | fstream::app);
	debug << endl;
	debug << "Preferences:" << endl;
	debug << "  resize_factor = " << resize_factor << endl;
	debug << "  debugmode = " << ((debugmode) ? "yes" : "no") << endl;
	debug << "  cache_size = " << cache_size << endl;
	debug << "  texdir = " << texdir << endl;
	debug.close();
#endif
}

//Mod Jay
void loadhashfile ()	//Expects hash1map folder to be in ff8/tonberry directory
{
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
	ofstream debug(gcontext_debug_file, fstream::out | fstream::app);
	debug << endl;
	debug << "Hashmap:" << endl;
#endif

	fs::path hashpath("tonberry/hashmap");
	if (!fs::exists(hashpath)) {
		ofstream err;								//Error reporting file
		err.open("tonberry/error.txt", ofstream::out | ofstream::app);
		err << "Error: hashmap folder doesn't exist\n";
		err.close();
	} else {
		fs::directory_iterator end_it;				//get tonberry/hashmap folder iterator

		for (fs::directory_iterator it(hashpath); it != end_it; it++) {
			if (fs::is_regular_file(it->status())) {	//if we got a regular file
				if (it->path().extension() == ".csv") {	//we check its extension, if .csv file:
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
					debug << "  Reading " << it->path().filename().string() << "...";
					debug.flush();
					size_t size_before = hashmap.size();
#endif

					ifstream hashfile;
					hashfile.open(it->path().string(), ifstream::in);	//open it and dump into the map
					string line;
					if (hashfile.is_open()) {
						while (getline(hashfile, line)) //Omzy's original code
						{
							if (line.empty()) continue;
							if (line[0] == '*') continue;						// textures starting with * should be ignored

							bool persist = false;
							if (line[0] == '!') {								// textures starting with ! should be persistent
								persist = true;
								line = line.substr(1);
							}

							int comma = line.find(",");
							string field = line.substr(0, comma);
							string valuestr = line.substr(comma + 1, line.length()).c_str();
							uint64_t value = ToNumber<uint64_t>(valuestr);
							hashmap.insert(pair<uint64_t, string>(value, field)); //key, value for unique names, value, key for unique hashvals

							if (persist) persistent_hashes.insert(value);

							if (field.length() >= 6) {
								string chars = field.substr(0, 6);
								if (chars == "sysfld") { //Exception for sysfld00 and sysfld01
									sysfld_hashes.insert(value);
								} else if (chars == "iconfl") { //Exception for iconfl00, iconfl01, iconfl02, iconfl03, iconflmaster
									iconfl_hashes.insert(value);
								}
							}
						}
						hashfile.close();
					}

#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
					debug << " found " << (hashmap.size() - size_before) << " hashes." << endl;
#endif
				}
			}
		}
	}

#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
	debug << "  hashmap.size() = " << hashmap.size() << endl;
	debug << "  sysfld_hashes.size() = " << sysfld_hashes.size() << ":" << endl;
	for (uint64_t sysfld_hash : sysfld_hashes)
		debug << "    " << sysfld_hash << endl;
	debug << "  iconfl_hashes.size() = " << iconfl_hashes.size() << ":" << endl;
	for (uint64_t iconfl_hash : iconfl_hashes)
		debug << "    " << iconfl_hash << endl;
	debug.close();
#endif
}

void loadcollfile ()	//Expects collisions.csv to be in ff8/tonberry directory
{
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
	ofstream debug(gcontext_debug_file, fstream::out | fstream::app);
	debug << endl;
	debug << "Collisions:" << endl;
#endif

	ifstream collfile;
	collfile.open ("tonberry\\collisions.csv", ifstream::in);
	string line;
	if (collfile.is_open())
	{
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
		debug << "  Reading collisions.csv...";
		debug.flush();
#endif
		while ( getline(collfile, line) ) //~10000 total number of 128x256 texture blocks in ff8
		{
			int comma = line.find(",");
			string field = line.substr(0, comma);
			string valuestr = line.substr(comma + 1, line.length()).c_str();
			uint64_t value = ToNumber<uint64_t>(valuestr);
			collmap.insert(pair<uint64_t, string>(value, field)); //key, value for unique names, value, key for unique hashvals
		}
		collfile.close();
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
		debug << " found " << collmap.size() << " hashes." << endl;
#endif
	}

#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
	debug.close();
#endif
}

//-------------------------------------------------------------
// converts string to unsigned long long
uint64_t StringToUint64(string s)
{
	uint64_t sum = 0;

	for (int i = 0; i<s.length(); i++)
		sum = (sum * 10) + (s[i] - '0');

	return sum;
}

void loadcoll2file ()	//Expects hash2map.csv to be in ff8/tonberry directory
{
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
	ofstream debug(gcontext_debug_file, fstream::out | fstream::app);
	debug << endl;
	debug << "Hash2:" << endl;
#endif

	ifstream coll2file;
	coll2file.open ("tonberry\\hash2map.csv", ifstream::in);
	string line;
	if (coll2file.is_open())
	{
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
		debug << "  Reading hash2map.csv...";
		debug.flush();
#endif
		while ( getline(coll2file, line) ) //~10000 total number of 128x256 texture blocks in ff8
		{
			if (line.empty()) continue;
			if (line[0] == '*') continue;						// textures starting with * should be ignored

			bool persist = false;
			if (line[0] == '!') {								// textures starting with ! should be persistent
				persist = true;
				line = line.substr(1);
			}

			int comma = line.find(",");
			string field = line.substr(0, comma);
			string valuestr = line.substr(comma + 1, line.length()).c_str();
			//BigInteger value = BigInteger(valuestr);
			//value = ToNumber<BigInt>(valuestr);
			uint64_t value = StringToUint64(valuestr);
			hash2map.insert(pair<BigInteger, uint64_t>(valuestr, value));
			coll2map.insert(pair<string, string>(valuestr, field)); //key, value for unique names, value, key for unique hashvals

			if (persist) persistent_hashes.insert(value);
		}
		coll2file.close();
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
		debug << " found " << hash2map.size() << " hashes." << endl;
#endif
	}

#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
	debug.close();
#endif
}

//Mod Jay
void loadobjfile ()	//Expects objmap.csv to be in ff8/tonberry directory
{
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
	ofstream debug(gcontext_debug_file, fstream::out | fstream::app);
	debug << endl;
	debug << "Objects:" << endl;
#endif
	fs::path hashpath("tonberry/objmap");
	if (!fs::exists(hashpath)) {
		ofstream err;								//Error reporting file
		err.open("tonberry/error.txt", ofstream::out | ofstream::app);
		err << "Error: objmap folder doesn't exist\n";
		err.close();
	} else {
		fs::directory_iterator end_it;
		for (fs::directory_iterator it(hashpath); it != end_it; it++) {
			if (fs::is_regular_file(it->status())) {	//if we got a regular file
				if (it->path().extension() == ".csv") {	//we check its extension, if .csv file:
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
					debug << "  Reading " << it->path().filename().string() << "...";
					debug.flush();
					size_t size_before = objmap.size();
#endif

					ifstream objfile;
					objfile.open(it->path().string(), ifstream::in);
					string line;
					if (objfile.is_open()) {
						while (getline(objfile, line)) {
							if (line.empty()) continue;
							if (line[0] == '*') continue;						// textures starting with * should be ignored

							bool persist = false;
							if (line[0] == '!') {								// textures starting with ! should be persistent
								persist = true;
								line = line.substr(1);
							}

							int comma = line.find(",");
							string obj = line.substr(0, comma);
							string valuestr = line.substr(comma + 1, line.length()).c_str();
							uint64_t value = ToNumber<uint64_t>(valuestr);
							objmap.insert(pair<uint64_t, string>(value, obj)); //key, value for unique names, value, key for unique hashvals

							if (persist) persistent_hashes.insert(value);
						}
						objfile.close();
					}

#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
					debug << " found " << (objmap.size() - size_before) << " hashes." << endl;
#endif
				}
			}
		}
	}

#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
	debug << "  objmap.size() = " << objmap.size() << endl;
	debug.close();
#endif
}

int m;

void GlobalContext::Init ()
{
	//------------
	/*_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
	_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
	HANDLE hLogFile;
	hLogFile = CreateFile("c:\\log.txt", GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	_CrtSetReportFile( _CRT_ERROR, hLogFile );
	_RPT0(_CRT_ERROR,"file message\n");
	CloseHandle(hLogFile);*/
	//------------
#if ATTACH_DEBUGGER
	//DebugBreak();
	::MessageBox(NULL, "Attach debugger now", "ATTACH", MB_OK);
#endif

#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
	ofstream debug(gcontext_debug_file, fstream::out | fstream::trunc);
	debug << "Initialized" << endl;
	debug.close();
#endif

    Graphics.Init();
	loadprefs();
	loadhashfile();
	loadcollfile();
	loadcoll2file();
	loadobjfile();
	initCache();//has to be called after loadprefs() so we get the propper cache_size!

	m = 0; // debug
}

void Hash_Algorithm_1 (BYTE* pData, UINT pitch, int width, int height)	//hash algorithm that preferences top and left sides
{
	int blocksize = 16;
	UINT x, y;
	int pix = 0;
	int toppix = 0;
	int botpix = 0;
	for (x = 0; x < 8; x++) //pixvals 0->31
	{
		for (y = 0; y < 4; y++)
		{
			if (x*blocksize < width && y*blocksize < height) //respect texture sizes
			{
				RGBColor* CurRow = (RGBColor*)(pData + (y*blocksize) * pitch);
				RGBColor Color = CurRow[x*blocksize];
				pixval[pix] = (Color.r + Color.g + Color.b) / 3;
				if (y*blocksize < 128) { if (toppix < 32) { objval[toppix] = pixval[pix]; toppix++; } }
				else if (botpix < 32) { objval[botpix + 32] = pixval[pix]; botpix++; }
			} else { pixval[pix] = 0; } //out of bounds
			pix++;
		}
	}
	for (x = 0; x < 2; x++) //pixvals 32->55
	{
		for (y = 4; y < 16; y++)
		{
			if (x*blocksize < width && y*blocksize < height) //respect texture sizes
			{
				RGBColor* CurRow = (RGBColor*)(pData + (y*blocksize) * pitch);
				RGBColor Color = CurRow[x*blocksize];
				pixval[pix] = (Color.r + Color.g + Color.b) / 3;
				if (y*blocksize < 128) { if (toppix < 32) { objval[toppix] = pixval[pix]; toppix++; } }
				else if (botpix < 32) { objval[botpix + 32] = pixval[pix]; botpix++; }
			} else { pixval[pix] = 0; } //out of bounds
			pix++;
		}
	}
	for (x = 3; x < 7; x+=3) //pixvals 56->63, note +=3
	{
		for (y = 5; y < 15; y+=3)	//note +=3
		{
			if (x*blocksize < width && y*blocksize < height) //respect texture sizes
			{
				RGBColor* CurRow = (RGBColor*)(pData + (y*blocksize) * pitch);
				RGBColor Color = CurRow[x*blocksize];
				pixval[pix] = (Color.r + Color.g + Color.b) / 3;
				if (y*blocksize < 128) { if (toppix < 32) { objval[toppix] = pixval[pix]; toppix++; } }
				else if (botpix < 32) { objval[botpix + 32] = pixval[pix]; botpix++; }
			} else { pixval[pix] = 0; } //out of bounds
			pix++;
		}
	}
}

void Hash_Algorithm_2 (BYTE* pData, UINT pitch, int width, int height)	//hash algorithm that chooses unique pixels selected by hand
{
	int pix = 0;
	UINT x0, y0;
	UINT x[76] = {44, 0, 17, 25, 15, 111, 35, 25, 3, 46, 112, 34, 21, 1, 72, 80, 25, 32, 15, 4, 123, 16, 47, 14, 110, 78, 3, 66, 0, 86, 58, 27, 39, 4, 6, 49, 7, 71, 121, 17, 22, 16, 84, 115, 118, 119, 126, 59, 96, 88, 64, 1, 21, 31, 107, 92, 73, 116, 118, 58, 47, 18, 93, 78, 97, 106, 107, 77, 99, 13, 100, 125, 12, 33, 53, 61};
	UINT y[76] = {243, 0, 2, 19, 35, 24, 0, 12, 23, 7, 5, 0, 4, 0, 2, 218, 30, 2, 20, 23, 4, 4, 2, 8, 7, 7, 25, 0, 1, 0, 11, 15, 2, 0, 0, 1, 15, 15, 16, 7, 7, 0, 244, 245, 245, 245, 253, 203, 135, 184, 9, 15, 80, 81, 244, 245, 249, 255, 238, 237, 216, 218, 240, 216, 116, 164, 244, 247, 236, 245, 21, 59, 25, 8, 16, 108};
	for (int i = 0; i < 76; i++) //pixvals 0->75
	{
		if (x[i] < width && y[i] < height) //respect texture sizes
		{
			RGBColor* CurRow = (RGBColor*)(pData + (y[i]/*blocksize*/) * pitch); //blocksize already included
			RGBColor Color = CurRow[x[i]/*blocksize*/];
			pixval2[pix] = (Color.r + Color.g + Color.b) / 3;
		} else { pixval2[pix] = 0; } //out of bounds
		pix++;
	}

	for (x0 = 0; x0 < 44; x0+=4) //pixvals 76->97, note +=4
	{
		for (y0 = 7; y0 < 16; y0+=8) //note +=8
		{
			if (x0 < width && y0 < height) //respect texture sizes
			{
				RGBColor* CurRow = (RGBColor*)(pData + (y0/*blocksize*/) * pitch); //blocksize already included
				RGBColor Color = CurRow[x0/*blocksize*/];
				pixval2[pix] = (Color.r + Color.g + Color.b) / 3;
			} else { pixval2[pix] = 0; } //out of bounds
			pix++;
		}
	}
}

Matchtype getsysfld (BYTE* pData, UINT pitch, int width, int height, string & sysfld)	//Exception method for sysfld00 and sysfld01
{
	UINT x = 177;
	UINT y = 155;

	if (width <= x || height <= y) {
		return Matchtype::NOMATCH;
	}

	string tempstr = sysfld;
	RGBColor* CurRow = (RGBColor*)(pData + (y) * pitch);
	RGBColor Color = CurRow[x];
	int sysval = (Color.r + Color.g + Color.b) / 3;
	string syspage = "13";
	switch (sysval) {
		case 43: syspage = "13"; break;
		case 153: syspage = "14"; break;
		case 150: syspage = "15"; break;
		case 101: syspage = "16"; break;
		case 85: syspage = "17"; break;
		case 174: syspage = "18"; break;
		case 170: syspage = "19"; break;
		case 255: syspage = "20"; break;
		default: syspage = "13"; break;
	}
	sysfld = tempstr.substr(0, 9) + syspage;
	return Matchtype::MATCH;
}

Matchtype geticonfl (BYTE* pData, UINT pitch, int width, int height, string & iconfl)	//Exception method for iconfl00, iconfl01, iconfl02, iconfl03, iconflmaster
{
	UINT x = 0;
	UINT y = 0;
	string tempstr = iconfl;
	if (iconfl == "iconfl00_13") { x = 82; y = 150; }
	else if (iconfl == "iconfl01_13") { x = 175; y = 208; }
	else if (iconfl == "iconfl02_13") { x = 216; y = 108; }
	else if (iconfl == "iconfl03_13") { x = 58; y = 76; }
	else if (iconfl == "iconflmaster_13") { x = 215; y = 103; }

	if (width <= x || height <= y) {
		return Matchtype::NOMATCH;
	}

	RGBColor* CurRow = (RGBColor*)(pData + (y) * pitch);
	RGBColor Color = CurRow[x];
	int colR = Color.r;
	int colG = Color.g;
	int colB = Color.b;
	if (colR == 0) { colR++; }
	if (colG == 0) { colG++; }
	if (colB == 0) { colB++; }
	int icval = colR * colG * colB;

	string icpage = "13";
	switch (icval) {
		case 65025: icpage = "13"; break;
		case 605160: icpage = "14"; break;
		case 1191016: icpage = "15"; break;
		case 189: icpage = "16"; break;
		case 473304: icpage = "17"; break;
		case 20992: icpage = "18"; break;
		case 859625: icpage = "19"; break;
		case 551368: icpage = "20"; break;
		case 1393200: icpage = "21"; break;
		case 931500: icpage = "22"; break;
		case 1011240: icpage = "23"; break;
		case 1395640: icpage = "24"; break;
		case 1018024: icpage = "25"; break;
		case 411864: icpage = "26"; break;
		case 80064: icpage = "27"; break;
		case 4410944: icpage = "28"; break;
		default: icpage = "13"; break;
	}
	iconfl = tempstr.substr(0, iconfl.size()-2) + icpage;
	return Matchtype::MATCH;
}

Matchtype getobj (uint64_t & hash, string & texname) //if previously unmatched, searches through object map for objects in top left/bottom left memory quarters, finally NO_MATCH is returned
{
	objtop = 0;
	objbot = 0;
	int lastpixel = objval[63];
    for (int i = 0; i < 64; i++)
    {
		if (i < 32) { objtop *= 2; }
		else { objbot *= 2; }
		if ((objval[i] - lastpixel) >= 0)
		{
			if (i < 32) { objtop++; }
			else { objbot++; }
		}
		lastpixel = objval[i];
    }
	it = objmap.find(objtop);
	if (it != objmap.end()) {
		hash = objtop;
		texname = it->second;
		return Matchtype::MATCH ;
	}
	it = objmap.find(objbot);
	if (it != objmap.end()) {
		hash = objbot;
		texname = it->second;
		return Matchtype::MATCH;
	}
	hash = 0;
	return Matchtype::NOMATCH;
}

Matchtype getfield (uint64_t & hash, string & texname)	//simple sequential bit comparisons
{
	ofstream checkfile;
	//checkfile.open("tonberry/tests/hashcache_test.txt", ofstream::out| ofstream::app);
	hashval = 0;
	int lastpixel = pixval[63];
    for (int i = 0; i < 64; i++)
    {
        hashval *= 2;
		if ((pixval[i] - lastpixel) >= 0) {	hashval++; }
		lastpixel = pixval[i];
    }

	it = hashmap.find(hashval);
	if (it != hashmap.end()) {
		hash = hashval;
		texname = it->second;
		return Matchtype::MATCH;
	}
	else {
		it = collmap.find(hashval);
		if (it != collmap.end()) {
			hash = hashval;
			return Matchtype::COLLISION;
		}
	}

	return getobj(hash, texname);
}

Matchtype getfield2 (uint64_t & hash, string & texname)	//simple sequential bit comparisons, algorithm 2
{
	hashval2 = 0;
	int lastpixel = pixval2[97];
    for (int i = 0; i < 98; i++)
    {
        hashval2 *= 2;
		if ((pixval2[i] - lastpixel) >= 0) {	hashval2 += 1; }
		lastpixel = pixval2[i];
    }
	it2 = coll2map.find(hashval2.getNumber());
	if (it2 != coll2map.end()) {
		texname = it2->second;
		hash = hash2map[hashval2];
		return Matchtype::MATCH;
	}
	return Matchtype::NOMATCH;
}

uint64_t parseiconfl(const string & texname){
//that crappy quick-fix function will allow us to identify the ic textures until the new hashing is ready.
	uint64_t hash = 0;
	string token;
	ofstream check;

	token = texname.substr(6, 2);
	if (token == "ma") {//iconflmaster_XX
		hash += 11111111111111100000;
	} else if (token == "00") {
		hash += 2222222220000000000;
	} else if (token == "01") {
		hash += 3333333330000000000;
	} else if (token == "02") {
		hash += 4444444440000000000;
	} else if (token == "03") {
		hash += 5555555550000000000;
	}

	token = texname.substr(texname.find("_") + 1);
	int num;
	try {
		num = stoi(token);
	} catch (exception&) {
		return hash;
	}

	hash += (num != 15) ? num : 99;

	return hash;
}

uint64_t parsesysfld(const string & texname) {
	uint64_t hash = 0;
	string token;
	ofstream check;

	token = texname.substr(6, 2);
	if (token == "00") {
		hash += 6666666660000000000;
	} else if (token == "01") {
		hash += 7777777770000000000;
	}

	token = texname.substr(texname.find("_") + 1);
	int num;
	try {
		num = stoi(token);
	} catch (exception&) {
		return hash;
	}

	hash += num;

	return hash;
}

//Final unlockrect
void GlobalContext::UnlockRect (D3DSURFACE_DESC &Desc, Bitmap &BmpUseless, HANDLE Handle) //note BmpUseless
{
    IDirect3DTexture9* pTexture = (IDirect3DTexture9*)Handle;

    String debugtype = String("error");

#if GCONTEXT_DEBUG
	ofstream debug(gcontext_debug_file, fstream::out | fstream::app);
	debug << endl << m << " (" << Handle << "): " << endl;
#endif

    if (pTexture && Desc.Width < 640 && Desc.Height < 480 && Desc.Format == D3DFORMAT::D3DFMT_A8R8G8B8 && Desc.Pool == D3DPOOL::D3DPOOL_MANAGED)    // 640x480 are video
    {
        D3DLOCKED_RECT Rect;
        pTexture->LockRect(0, &Rect, NULL, 0);
        UINT pitch = (UINT)Rect.Pitch;
        BYTE* pData = (BYTE*)Rect.pBits;

        uint64_t hash;
		string texturename;
		Matchtype match;
		bool persist = false;
        Hash_Algorithm_1(pData, pitch, Desc.Width, Desc.Height);				// Run Hash_Algorithm_1
        match = getfield(hash, texturename);
		persist = persistent_hashes.count(hash);

#if GCONTEXT_DEBUG
		debug << "  getfield - ";
		debug.flush();
		switch (match) {
		case Matchtype::MATCH: debug << "MATCH:"; break;
		case Matchtype::NOMATCH: debug << "NOMATCH:"; break;
		case Matchtype::COLLISION: debug << "COLLISION:"; break;
		}
		debug << " " << hash << endl;
#endif

        if (sysfld_hashes.count(hash)) {										// Exception for sysfld00 and sysfld01
			if ((match = getsysfld(pData, pitch, Desc.Width, Desc.Height, texturename)) == Matchtype::MATCH)
				hash = parsesysfld(texturename);
#if GCONTEXT_DEBUG
			debug << "  getsysfld - ";
			debug.flush();
			switch (match) {
			case Matchtype::MATCH: debug << "MATCH:"; break;
			case Matchtype::NOMATCH: debug << "NOMATCH:"; break;
			case Matchtype::COLLISION: debug << "COLLISION?"; break;
			}
			debug << " " << hash << endl;
#endif
		} else if (iconfl_hashes.count(hash)) {									// Exception for iconfl00, iconfl01, iconfl02, iconfl03, iconflmaster
			if ((match = geticonfl(pData, pitch, Desc.Width, Desc.Height, texturename)) == Matchtype::MATCH)
				hash = parseiconfl(texturename);
#if GCONTEXT_DEBUG
			debug << "  geticonfl - ";
			debug.flush();
			switch (match) {
			case Matchtype::MATCH: debug << "MATCH:"; break;
			case Matchtype::NOMATCH: debug << "NOMATCH:"; break;
			case Matchtype::COLLISION: debug << "COLLISION?"; break;
			}
			debug << " " << hash << endl;
#endif
		}

		if (match == Matchtype::NOMATCH) {										// Handle inválido, lo borro, pero no su posible textura asociada.
			texcache->erase(Handle);
			debugtype = String("nomatch");
		} else {																// Texture FOUND in Hash_Algorithm_1 OR is a COLLISION
			if (match == Matchtype::COLLISION) {								// Run Hash_Algorithm_2
				Hash_Algorithm_2(pData, pitch, Desc.Width, Desc.Height);
				match = getfield2(hash, texturename);
				persist = persistent_hashes.count(hash);
				if (match == Matchtype::NOMATCH) {
					texcache->erase(Handle);
					debugtype = String("nomatch2");
				}

#if GCONTEXT_DEBUG
				debug << "  getfield2 - ";
				debug.flush();
				switch (match) {
				case Matchtype::MATCH: debug << "MATCH:"; break;
				case Matchtype::NOMATCH: debug << "NOMATCH:"; break;
				case Matchtype::COLLISION: debug << "COLLISION?"; break;
				}
				debug << " " << hash << endl;
#endif
			}

			if (match == Matchtype::MATCH) {
				debugtype = String("noreplace");
				if (!texcache->update(Handle, hash)) {							// directly updated if it succeeds we just end unlockrect cycle.
					if (!texcache->full()) {
						string filename = texdir + "textures\\" + texturename.substr(0, 2) + "\\" + texturename.substr(0, texturename.rfind("_")) + "\\" + texturename + ".png";

#if GCONTEXT_DEBUG
						debug << "  Reading " << filename << "...";
						debug.flush();
#endif

						ifstream ifile(filename);
						if (!ifile || ifile.fail()) {											// No file, allow normal SetTexture
							texcache->erase(Handle);
#if GCONTEXT_DEBUG
							debug << " failed." << endl;
#endif
						} else {																// Load texture into cache
#if GCONTEXT_DEBUG
							debug << " succeeded." << endl;
#endif
#if CREATE_TEXTURE_DEBUG && !GCONTEXT_DEBUG
							ofstream debug(gcontext_debug_file, fstream::out | fstream::app);
							debug << endl << m << " (" << Handle << "):" << endl;
#endif
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
							debug << "  Creating new texture...";
#if CREATE_TEXTURE_DEBUG
							debug << endl;
#endif
#endif

							Bitmap Bmp;
							Bmp.LoadPNG(String(filename.c_str()));

							size_t new_width = resize_factor * (float)Desc.Width;
							size_t new_height = resize_factor * (float)Desc.Height;
							if (new_width >= Bmp.Width() && new_height >= Bmp.Height()) {		// replaced HANDLE is large enough for the replacement
#if CREATE_TEXTURE_DEBUG
								debug << "    texture appropriate for replacement; " << Desc.Width << "x" << Desc.Height << " vs " << Bmp.Width() << "x" << Bmp.Height() << endl;
#endif
								LPDIRECT3DDEVICE9 Device = g_Context->Graphics.Device();
								IDirect3DTexture9* newtexture;
								HRESULT result = Device->CreateTexture(new_width, new_height, 0, D3DUSAGE_AUTOGENMIPMAP, D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, &newtexture, NULL);

								if (SUCCEEDED(result)) {										// newtexture successfully created
#if CREATE_TEXTURE_DEBUG
									debug << "    newtexture created; HRESULT = " << result << endl;
#endif

									D3DLOCKED_RECT newRect;
									result = newtexture->LockRect(0, &newRect, NULL, 0);

									if (SUCCEEDED(result)) {									// newtexture successfully locked
#if CREATE_TEXTURE_DEBUG
										debug << "    newtexture locked; HRESULT = " << result << endl;
#endif

										BYTE* newData = (BYTE *)newRect.pBits;

										for (UINT y = 0; y < Bmp.Height(); y++) {
											RGBColor* CurRow = (RGBColor *)(newData + y * newRect.Pitch);
											for (UINT x = 0; x < Bmp.Width(); x++) {			// works for textures of any size (e.g. 4-bit indexed)
												RGBColor Color = Bmp[Bmp.Height() - y - 1][x];  // must flip image
												CurRow[x] = RGBColor(Color.b, Color.g, Color.r, Color.a);
											}
										}
										result = newtexture->UnlockRect(0);						// Texture loaded

										if (SUCCEEDED(result)) {
#if CREATE_TEXTURE_DEBUG
											debug << "    newtexture loaded and unlocked; HRESULT = " << result << endl;
#endif

											HANDLE newhandle = (HANDLE)newtexture;
											texcache->insert(Handle, hash, newhandle, persist);
											debugtype = String("replaced");
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
											debug << "  succeeded. newhandle = " << newhandle << "." << endl;
#endif
										} else {
											texcache->erase(Handle);
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
											debug << "    ERROR: could not unlock newtexture; HRESULT = " << result << endl;
#endif
										}
									} else {
										texcache->erase(Handle);
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
										debug << "    ERROR: could not lock newtexture; HRESULT = " << result << endl;
#endif
									}
								} else {
									texcache->erase(Handle);
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
									debug << "    ERROR: could not create newtexture; HRESULT = " << result << endl;
#endif
								}
							} else {
								texcache->erase(Handle);
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
								debug << "    ERROR: texture too small for replacement; " << Desc.Width << "x" << Desc.Height << " vs " << Bmp.Width() << "x" << Bmp.Height() << endl;
#endif
							}
						}
					} else {													// if the cache is full, no new texture need be created
						texcache->erase(Handle);
#if GCONTEXT_DEBUG
						debug << "  Texture cache is full - abandoning newhandle creation." << endl;
#endif
					}
				}
#if GCONTEXT_DEBUG
				else {
					debug << "  Found existing newhandle." << endl;
				}
#endif
			}
		}
		pTexture->UnlockRect(0);												// Finished reading pTextures bits
	} else {																	// Video textures/improper format
		// this is the beauty of your solution; you replaced that whole O(n^2) loop bullshit with one line ;)
		texcache->erase(Handle);
		debugtype = String("unsupported");
#if GCONTEXT_DEBUG
		debug << "  Unsupported." << endl;
#endif
	}
	// debug
	if (debugmode) {
		String debugfile = String("tonberry\\debug\\") + debugtype + String("\\") + String::ZeroPad(String(m), 3) + String(".bmp");
#if GCONTEXT_DEBUG
		debug << "  Saving debugmode texture to " << debugfile << "... ";
		debug.flush();
#endif
		HRESULT result = D3DXSaveTextureToFile(debugfile.CString(), D3DXIFF_BMP, pTexture, NULL);
		m++; // debug
#if GCONTEXT_DEBUG
		debug << (SUCCEEDED(result) ? "succeeded." : "failed.") << endl;
#endif
	}
#if GCONTEXT_DEBUG || CREATE_TEXTURE_DEBUG
	else m++;
#endif
#if GCONTEXT_DEBUG
	debug.close();
#endif
}

//Final settex

bool GlobalContext::SetTexture(DWORD Stage, HANDLE* SurfaceHandles, UINT SurfaceHandleCount)
{
#if DEBUG
	StartCounter();
#endif
	for (int j = 0; j < SurfaceHandleCount; j++) {
		IDirect3DTexture9* newtexture;
        if (SurfaceHandles[j] && (newtexture = (IDirect3DTexture9*)texcache->at(SurfaceHandles[j]))) {
			HRESULT result = g_Context->Graphics.Device()->SetTexture(Stage, newtexture);
#if DEBUG
	debug << GetCounter() << endl;
#endif
            return true;
		} // Texture replaced!
	}
#if DEBUG
	debug << GetCounter() << endl;
#endif
	return false;
}

//Unused functions
void GlobalContext::UpdateSurface(D3DSURFACE_DESC &Desc, Bitmap &Bmp, HANDLE Handle) {}
void GlobalContext::Destroy(HANDLE Handle) {}
void GlobalContext::CreateTexture (D3DSURFACE_DESC &Desc, Bitmap &Bmp, HANDLE Handle, IDirect3DTexture9** ppTexture) {}
void GlobalContext::BeginScene () {}


text:
<?xml version="1.0"?>
<QuestsDefinitions
     level="sewers"
     pxsl_line="3">
    <!-- quest Firebees_Sewers -parent=Firebees  -glued=true   -difficulty=medium    -leading_portal=Firebees_Portal_OldTown_TO_Sewers -->
        <!-- ,goto <<Entering Sewers - START>> SensorGoTo WayToSomewhere_SewerEnter -distance=0  -obj=&WayToStadium_OBJ_Enter& -->
            <!-- ,debugpos   SpawnPoint SP_Sewers_Stadium_OldTown_Exit1 -->
        <!-- ,checkpoint _       SpawnPoint SP_Sewers_Stadium_OldTown_Exit1 -->
        <!-- ,enable _       SpawnPoint WayToSomewhere_Respawn_1 -->
        <!-- -= ,enable_time_freeze _ -->
        <!-- -= ,player-watch _ false -->
        <!-- -= ,set_day_time _ -day_time=10.00             -->
        <!-- ,BLOCK _        -obj=&WayToStadium_OBJ_Find_1& -->
            <!-- ,goto << Horde_Test >>     SensorGoTo WayToSomewhere_Marker_1      -distance=0         -->
                <!-- ,debugpos   SpawnPoint Horde_Test -->
            <!-- ,enable _       NightArea WayToSomewhere_NightArea -->
            <!-- ,enable _       SpawnPoint Horde_Test -->
            <!-- ,AND _ -->
                <!-- path -->
                    <!-- ,dialog _ voice2d Firebees_FindigWay -auto=true  -->
                <!-- path -->
                    <!-- ,OR _         -->
                        <!-- path -->
                            <!-- ,goto _     SensorGoTo WayToSomewhere_Marker_1A      -distance=0      -->
                        <!-- path -->
                            <!-- ,goto _     SensorGoTo WayToSomewhere_Marker_1B      -distance=0     -show=false -->
            <!-- ,goto << Entering Electric Room >>     SensorGoTo WayToSomewhere_Marker_ElectricRoom   -distance=0  -obj=&WayToStadium_OBJ_Find_2&       -->
                <!-- ,debugpos    SpawnPoint SP_Sewers_Stadium_Pipe -->
            <!-- ,enable _           SpawnPoint WayToSomewhere_ElectriRoom -->
            <!-- ,disable-multi _ -->
                <!-- ,o      SpawnPoint WayToSomewhere_Respawn_1 -->
                <!-- ,o      SpawnPoint Horde_Test -->
        <!-- ,BLOCK _    -obj=&WayToStadium_OBJ_Electricity& -->
            <!-- ,AND _ -->
                <!-- path -->
                    <!-- ,dialog _ voice2d Firebees_ElectricRoom_Enter -auto=true -->
            <!-- ,OR _ -->
                <!-- ,area      ZoneBox Electric_Zone_Marker -->
                <!-- path -->
                    <!-- ,use _      PhysicalSwitchDI Electric_Box       -state=on   -show=false -->
                    <!-- ,use _      PhysicalSwitchDI Electric_Lever     -state=on   -show=false -->
                    <!-- ,disable _  QuestEnableGroup Electric_Lever_Items -->
                    <!-- ,enable _  BlackoutArea Sewer_WayToSomewhere_BlackOut -->
                    <!-- ,enable _   QuestEnableGroup Electric_Room_Volletailes -->
                <!-- path -->
                    <!-- ,AND _ -->
                        <!-- path -->
                            <!-- ,use _  PhysicalSwitchDI Electric_Lever_Fake_1  -state=on   -show=false -->
                            <!-- ,dialog _ voice2d Firebees_Opening_FakeBox_1 -auto=true  -->
                        <!-- path -->
                            <!-- ,use _  PhysicalSwitchDI Electric_Lever_Fake_2  -state=on   -show=false -->
                            <!-- ,dialog _ voice2d Firebees_Opening_FakeBox_2 -auto=true  -->
                    <!-- ,semaphore _     -->
        <!-- ,BLOCK _    -obj=&WayToStadium_OBJ_Find_3& -->
            <!-- ,goto _     SensorGoTo WayToSome_Marker_ElectricRoom_Exit    -distance=0  -->
            <!-- ,enable _   QuestEnableGroup Air_Room_Zombies -->
            <!-- ,checkpoint _      SpawnPoint Check_Floded_Room -->
            <!-- ,goto << Entering Floded Room >>      SensorGoTo WayToSome_Marker_FloodRoom    -distance=0  -->
                <!-- ,debugpos    SpawnPoint Check_Floded_Room -->
            <!-- ,enable _   SpawnPoint WayToSomewhere_FlodedRoom -->
            <!-- ,disable _  SpawnPoint WayToSomewhere_ElectriRoom -->
            <!-- ,BLOCK _     -->
                <!-- ,goto _     SensorGoTo WayToSome_Marker_FloodRoom_Exit    -distance=0  -->
                <!-- ,enable _   SpawnPoint WayToSomewhere_FlodedRoom_Exit -->
                <!-- ,disable _   SpawnPoint WayToSomewhere_FlodedRoom -->
                <!-- ,enable _   QuestEnableGroup Air_Room_2_Zombies -->
            <!-- ,goto << Entering Bridge >>     SensorGoTo WayToSome_Marker_Bridge    -distance=0  -->
                <!-- ,debugpos    SpawnPoint Check_Bridge_Fall -->
            <!-- ,checkpoint _       SpawnPoint Check_Bridge_Fall -->
            <!-- ,goto _             SensorGoTo WayToSome_Marker_Slide           -distance=0      -->
            <!-- ,checkpoint _   SpawnPoint  Check_Slide -->
            <!-- ,disable _      SpawnPoint WayToSomewhere_FlodedRoom_Exit -->
            <!-- ,enable _       SpawnPoint WayToSomewhere_Slide_Respawn -->
            <!-- ,goto << Entering Slide >>             SensorGoTo WayToSome_Marker_Slide_2           -distance=0 -->
                <!-- ,debugpos   SpawnPoint Check_Slide -->
        <!-- ,AND _ -->
            <!-- path -->
                <!-- ,dialog _ voice2d Firebees_Sliding -auto=true  -->
            <!-- path -->
                <!-- ,OR _ -->
                    <!-- path -->
                        <!-- ,goto _            SensorGoTo WayToSome_Marker_TankRoom           -distance=0     -->
                        <!-- ,BLOCK _    -obj=&WayToStadium_OBJ_Water& -->
                            <!-- ,use _  PhysicalSwitchDI Sluice_Valve_3     -state=off -->
                            <!-- ,AND _ -->
                                <!-- path -->
                                    <!-- ,dialog _ voice2d Firebees_Closing_Sluices -auto=true  -->
                                <!-- path -->
                                    <!-- ,movie _    Movie_Sluice_Window_Close_3 -->
                                <!-- path -->
                                    <!-- ,use _  PhysicalSwitchDI Sluice_Valve_2     -state=off -->
                                    <!-- ,movie _    Movie_Sluice_Window_Close_2 -->
                                <!-- path -->
                                    <!-- ,use _  PhysicalSwitchDI Sluice_Valve_1     -state=off -->
                                    <!-- ,movie _    Movie_Sluice_Window_Close_1         -->
                            <!-- ,movie _        Movie_Water_Level_Up -->
                            <!-- ,checkpoint _   SpawnPoint Check_TankRoom                 -->
                    <!-- path -->
                        <!-- ,goto _     SensorGoTo WayToSomewhere_SewerExit      -distance=0       -show=false -->
        <!-- ,BLOCK _        -obj=&WayToStadium_OBJ_Find_4& -->
            <!-- ,checkpoint _   SpawnPoint  Check_SewerExit -->
            <!-- ,enable _       SpawnPoint WayToSomewhere_Sewer_Exit -->
            <!-- ,disable _      SpawnPoint WayToSomewhere_Slide_Respawn -->
            <!-- ,goto << End >>     MapPortal Portal_Sewers_Stadium_Exit      -distance=5     -show=false -->
                <!-- ,debugpos   SpawnPoint Check_SewerExit -->
            <!-- -= ,disable_time_freeze _ -->
            <!-- -= ,player-watch _ true           -->
    <!--  -->
    <!--  -->
        <!--  -->
    <!-- -=  -->
    <!--  -->
    <!--  -->
        <!--  -->
        <!--  -->
        <!--  -->
    <!--  -->
    <!-- quest __Firebees_Sewers_Bridge -parent=Firebees           -->
        <!-- ,goto << Bridge Destroy >>    SensorGoTo WayToSome_Marker_Bridge    -distance=0 -show=false -->
            <!-- ,debugpos    SpawnPoint Check_Bridge_Fall -->
        <!-- ,enable-multi _        -->
            <!-- ,o      FakeAITarget Bridge_Zombie_Attractor   -->
            <!-- ,o      DamageSwitchDI Bridge_Damage_Box_1 -->
            <!-- ,o      DamageSwitchDI Bridge_Damage_Box_2           -->
        <!-- ,OR _ -->
            <!-- path -->
                <!-- ,goto _     SensorGoTo WayToSome_Marker_Bridge_Fall     -distance=0     -show=false -->
            <!-- path -->
                <!-- ,OR _ -->
                    <!-- path -->
                        <!-- ,use _      DamageSwitchDI Bridge_Damage_Box_1        -state=on     -show=false -->
                    <!-- path -->
                        <!-- ,use _      DamageSwitchDI Bridge_Damage_Box_2        -state=on     -show=false -->
        <!-- ,disable _  FakeAITarget Bridge_Zombie_Attractor                   -->
        <!-- ,movie _    Movie_Bridge_Falls -->
        <!-- ,checkpoint _       SpawnPoint Check_Bridge_Fall -->
        <!--  -->
    <!-- quest __Firebees_Sewers_FallingZombies -parent=Firebees -->
        <!-- ,goto _          SensorGoTo WayToSome_Marker_TankRoom           -distance=0     -show=false     -->
        <!-- ,wait _         5 -->
        <!-- ,enable-multi _ -->
            <!-- ,o      FakeAITarget Fake_Zombie_BigRoom_Attractor -->
            <!-- ,o      AISpawnBoxNumber Falling_Zombies -->
        <!-- ,wait _         15 -->
        <!-- ,disable _      FakeAITarget Fake_Zombie_BigRoom_Attractor -->
        <!-- ,checkpoint _       SpawnPoint Check_TankRoom -->
        <!--  -->
    <!-- quest __Firebees_Sewers_Pipe_Grating -parent=Firebees -->
        <!-- ,goto _          SensorGoTo  Sewer_Pipe_Grating_Fall         -distance=0     -show=false   -->
        <!-- ,movie _        Movie_Pipe_Grating_Fall -->
        <!-- ,checkpoint _       SpawnPoint WayToSomewhere_FlodedRoom -->
        <!--  -->
    <!-- quest __Firebees_Sewers_Pipe_Grating_2 -parent=Firebees -->
        <!-- ,goto _          SensorGoTo  Sewer_Pipe_Grating_Fall_2         -distance=0     -show=false   -->
        <!-- ,movie _        Movie_Pipe_Grating_Fall_2 -->
        <!-- ,checkpoint _       SpawnPoint WayToSomewhere_FlodedRoom -->
        <!--  -->
    <!-- quest __Firebees_Sewers_Pipe_Grating_3 -parent=Firebees -->
        <!-- ,goto _          SensorGoTo  Sewer_Pipe_Grating_Fall_3         -distance=0     -show=false   -->
        <!-- ,movie _        Movie_Pipe_Grating_Fall_3 -->
        <!-- ,checkpoint _       SpawnPoint WayToSomewhere_ElectriRoom -->
        <!--  -->
    <!-- quest __Firebees_Sewers_Pipe_Grating_4 -parent=Firebees -->
        <!-- ,goto _          SensorGoTo  Sewer_Pipe_Grating_Fall_4         -distance=0     -show=false   -->
        <!-- ,movie _        Movie_Pipe_Grating_Fall_4 -->
        <!-- ,checkpoint _       SpawnPoint WayToSomewhere_ElectriRoom -->
    <!--  -->
        <!--  -->
    <!--  -->
</QuestsDefinitions>


text:
using namespace std;

BOOST_AUTO_TEST_SUITE( TestConstness )

BOOST_AUTO_TEST_CASE( TestConstReference )
{
	int a = 1234;
	const int &b = a;

	BOOST_CHECK_EQUAL( b, 1234 );
	BOOST_CHECK_EQUAL( &b, &a );

#if 0
	b = 3;		// of course compile error
#endif

	int &c = a;
	c = 4321;
	BOOST_CHECK_EQUAL( a, 4321 );
}

class Foo
{
public:
	Foo() : m_Counter(0) {}

	void Increase() { m_Counter++; }
	int Count() const { return m_Counter; }

private:
	int m_Counter;
};

BOOST_AUTO_TEST_CASE( TestConstFunctionsAndReturn )
{
	Foo f1;
	f1.Increase();
	BOOST_CHECK_EQUAL( f1.Count(), 1 );
}

class FooFactory
{
public:
	const Foo& GetConservative() const { return m_Conservative; }
	Foo& GetLiberal() { return m_Liberal; }

private:
	Foo m_Conservative;
	Foo m_Liberal;
};

BOOST_AUTO_TEST_CASE( TestConstReturn )
{
	FooFactory factory;
	const Foo& chanhi = factory.GetConservative();
#if 0
	chanhi.Increase();	// Compile error : Remember that dull is const !
#endif
	BOOST_CHECK_EQUAL( chanhi.Count(), 0 );

	Foo& sungwoo( factory.GetLiberal() );
	sungwoo.Increase();
	BOOST_CHECK_EQUAL( sungwoo.Count(), 1 );

	Foo& fakeSungwoo( factory.GetLiberal() );
	fakeSungwoo.Increase();
	BOOST_CHECK_EQUAL( sungwoo.Count(), 2 );
}

BOOST_AUTO_TEST_SUITE_END()


text:
import sourcemaps from 'rollup-plugin-sourcemaps';
import {readFileSync} from 'fs';
import path from 'path';
import commonjs from 'rollup-plugin-commonjs';
import nodeResolve from 'rollup-plugin-node-resolve';
import alias from '@rollup/plugin-alias';

const version = require(path.resolve(__dirname, '../../package.json')).version;

const ERRORS_TO_IGNORE = [
  "THIS_IS_UNDEFINED",
];

export default {
  input: 'tools/tmp/src/dexie-export-import.js',
  output: [{
    file: 'dist/dexie-export-import.js',
    format: 'umd',
    banner: readFileSync(path.resolve(__dirname, 'banner.txt'), "utf-8")
        .replace(/{version}/g, version)
        .replace(/{date}/g, new Date().toDateString()),
    globals: {dexie: "Dexie"},
    name: 'DexieExportImport',
    sourcemap: true,
    exports: 'named'
  },{
    file: 'dist/dexie-export-import.mjs',
    format: 'es',
    banner: readFileSync(path.resolve(__dirname, 'banner.txt'), "utf-8")
        .replace(/{version}/g, version)
        .replace(/{date}/g, new Date().toDateString()),
    sourcemap: true
  }],
  external: ['dexie'],
  plugins: [
    sourcemaps(),
    alias({entries: [{
      find: "stream", replacement: path.resolve(__dirname, './fake-stream')}
    ]}),
    nodeResolve({
      browser: true,
      preferBuiltins: false
    }),
    commonjs()
  ],
  onwarn ({loc, frame, code, message}) {
    if (ERRORS_TO_IGNORE.includes(code)) return;
    if ( loc ) {
      console.warn( `${loc.file} (${loc.line}:${loc.column}) ${message}` );
      if ( frame ) console.warn( frame );
    } else {
      console.warn(`${code} ${message}`);
    }
  }
};


text:
package com.zuoxiaolong.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import com.zuoxiaolong.dao.StatisticsDao;
import com.zuoxiaolong.orm.DaoFactory;
import org.apache.commons.lang.StringUtils;

import com.zuoxiaolong.dao.UserDao;
import com.zuoxiaolong.util.DirtyWordsUtil;

/**
 * @author 左潇龙
 * @since 2015年5月27日 下午7:55:28
 */
public class Login extends AbstractServlet {

	private static final String pattern = "[a-zA-Z0-9_\u4e00-\u9fa5]+";

	private static final Pattern chinesePattern = Pattern.compile("[\u4e00-\u9fa5]{1,1}");

	@Override
	protected void service() throws ServletException, IOException {
		Map<String, Object> result = new HashMap<>();
		HttpServletRequest request = getRequest();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		if (StringUtils.isBlank(username)) {
			writeText("用户名不能为空");
			return;
		}
		int chineseNumber = 0;
		Matcher matcher = chinesePattern.matcher(username);
		while (matcher.find()) {
			chineseNumber++;
		}
		int length = chineseNumber * 6 + (username.length() - chineseNumber);
		if (length < 6) {
			writeText("用户名长度不能小于6(汉字长度计为6)");
			return;
		}
		if (length > 30) {
			writeText("用户名长度不能超过30(汉字长度计为6)");
			return;
		}
		if (!Pattern.matches(pattern, username)) {
			writeText("用户名只能是字母,数字,汉字,下划线");
			return;
		}
		if (DirtyWordsUtil.isDirtyWords(username)) {
			writeText("用户名不合法");
			return;
		}
		if (StringUtils.isBlank(password)) {
			writeText("密码不能为空");
			return;
		}
		if (password.length() < 6) {
			writeText("密码长度不能小于6");
			return;
		}
		if (password.length() > 30) {
			writeText("密码长度不能超过30");
			return;
		}
		Map<String, String> user = DaoFactory.getDao(UserDao.class).login(username, password);
		if (user != null) {
			request.getSession().setAttribute("user", user);
			result.put("success", true);
			result.put("url", getDynamicUrl());
			writeJsonObject(result);
			return;
		}
		Map<String, String> userInDB = DaoFactory.getDao(UserDao.class).getUser(username);
		if (userInDB != null) {
			writeText("用户名已存在或密码错误");
			return;
		}
		if (DaoFactory.getDao(UserDao.class).saveCommonLogin(username, password)) {
			Map<String, String> newUser = DaoFactory.getDao(UserDao.class).getUser(username);
			request.getSession().setAttribute("user", newUser);
			result.put("success", true);
			result.put("url", getDynamicUrl());
			writeJsonObject(result);
			return;
		}
		writeText("服务器内部错误,请联系站长");
	}

}


text:
/**
 * UsuarioController
 *
 * @description :: Server-side logic for managing Usuarios
 * @help        :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
  crearUsuario: function (req, res) {
    var parametros = req.allParams();
    var nuevoUsuario = {
      nombre: parametros.nombre,
      apellido: parametros.apellido,
      password: parametros.password
    };
    Usuario.create(nuevoUsuario)
      .exec(function (error, usuarioCreado) {
        if (error) {
          return res.serverError(error);
        }
        else {
          return res.redirect("/");
        }
      });
  }
};


text:
#pragma once
#include <aws/codeartifact/CodeArtifact_EXPORTS.h>
#include <aws/codeartifact/CodeArtifactRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/codeartifact/model/PackageFormat.h>
#include <aws/codeartifact/model/PackageOriginRestrictions.h>
#include <utility>

namespace Aws
{
namespace Http
{
    class URI;
} //namespace Http
namespace CodeArtifact
{
namespace Model
{

  /**
   */
  class AWS_CODEARTIFACT_API PutPackageOriginConfigurationRequest : public CodeArtifactRequest
  {
  public:
    PutPackageOriginConfigurationRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "PutPackageOriginConfiguration"; }

    Aws::String SerializePayload() const override;

    void AddQueryStringParameters(Aws::Http::URI& uri) const override;

    /**
     *
The name of the domain that contains the repository that contains the
     * package.

     */
    inline const Aws::String& GetDomain() const{ return m_domain; }

    /**
     *
The name of the domain that contains the repository that contains the
     * package.

     */
    inline bool DomainHasBeenSet() const { return m_domainHasBeenSet; }

    /**
     *
The name of the domain that contains the repository that contains the
     * package.

     */
    inline void SetDomain(const Aws::String& value) { m_domainHasBeenSet = true; m_domain = value; }

    /**
     *
The name of the domain that contains the repository that contains the
     * package.

     */
    inline void SetDomain(Aws::String&& value) { m_domainHasBeenSet = true; m_domain = std::move(value); }

    /**
     *
The name of the domain that contains the repository that contains the
     * package.

     */
    inline void SetDomain(const char* value) { m_domainHasBeenSet = true; m_domain.assign(value); }

    /**
     *
The name of the domain that contains the repository that contains the
     * package.

     */
    inline PutPackageOriginConfigurationRequest& WithDomain(const Aws::String& value) { SetDomain(value); return *this;}

    /**
     *
The name of the domain that contains the repository that contains the
     * package.

     */
    inline PutPackageOriginConfigurationRequest& WithDomain(Aws::String&& value) { SetDomain(std::move(value)); return *this;}

    /**
     *
The name of the domain that contains the repository that contains the
     * package.

     */
    inline PutPackageOriginConfigurationRequest& WithDomain(const char* value) { SetDomain(value); return *this;}

    /**
     *
 The 12-digit account number of the Amazon Web Services account that owns the
     * domain. It does not include dashes or spaces.

     */
    inline const Aws::String& GetDomainOwner() const{ return m_domainOwner; }

    /**
     *
 The 12-digit account number of the Amazon Web Services account that owns the
     * domain. It does not include dashes or spaces.

     */
    inline bool DomainOwnerHasBeenSet() const { return m_domainOwnerHasBeenSet; }

    /**
     *
 The 12-digit account number of the Amazon Web Services account that owns the
     * domain. It does not include dashes or spaces.

     */
    inline void SetDomainOwner(const Aws::String& value) { m_domainOwnerHasBeenSet = true; m_domainOwner = value; }

    /**
     *
 The 12-digit account number of the Amazon Web Services account that owns the
     * domain. It does not include dashes or spaces.

     */
    inline void SetDomainOwner(Aws::String&& value) { m_domainOwnerHasBeenSet = true; m_domainOwner = std::move(value); }

    /**
     *
 The 12-digit account number of the Amazon Web Services account that owns the
     * domain. It does not include dashes or spaces.

     */
    inline void SetDomainOwner(const char* value) { m_domainOwnerHasBeenSet = true; m_domainOwner.assign(value); }

    /**
     *
 The 12-digit account number of the Amazon Web Services account that owns the
     * domain. It does not include dashes or spaces.

     */
    inline PutPackageOriginConfigurationRequest& WithDomainOwner(const Aws::String& value) { SetDomainOwner(value); return *this;}

    /**
     *
 The 12-digit account number of the Amazon Web Services account that owns the
     * domain. It does not include dashes or spaces.

     */
    inline PutPackageOriginConfigurationRequest& WithDomainOwner(Aws::String&& value) { SetDomainOwner(std::move(value)); return *this;}

    /**
     *
 The 12-digit account number of the Amazon Web Services account that owns the
     * domain. It does not include dashes or spaces.

     */
    inline PutPackageOriginConfigurationRequest& WithDomainOwner(const char* value) { SetDomainOwner(value); return *this;}

    /**
     *
The name of the repository that contains the package.

     */
    inline const Aws::String& GetRepository() const{ return m_repository; }

    /**
     *
The name of the repository that contains the package.

     */
    inline bool RepositoryHasBeenSet() const { return m_repositoryHasBeenSet; }

    /**
     *
The name of the repository that contains the package.

     */
    inline void SetRepository(const Aws::String& value) { m_repositoryHasBeenSet = true; m_repository = value; }

    /**
     *
The name of the repository that contains the package.

     */
    inline void SetRepository(Aws::String&& value) { m_repositoryHasBeenSet = true; m_repository = std::move(value); }

    /**
     *
The name of the repository that contains the package.

     */
    inline void SetRepository(const char* value) { m_repositoryHasBeenSet = true; m_repository.assign(value); }

    /**
     *
The name of the repository that contains the package.

     */
    inline PutPackageOriginConfigurationRequest& WithRepository(const Aws::String& value) { SetRepository(value); return *this;}

    /**
     *
The name of the repository that contains the package.

     */
    inline PutPackageOriginConfigurationRequest& WithRepository(Aws::String&& value) { SetRepository(std::move(value)); return *this;}

    /**
     *
The name of the repository that contains the package.

     */
    inline PutPackageOriginConfigurationRequest& WithRepository(const char* value) { SetRepository(value); return *this;}

    /**
     *
A format that specifies the type of the package to be updated.

     */
    inline const PackageFormat& GetFormat() const{ return m_format; }

    /**
     *
A format that specifies the type of the package to be updated.

     */
    inline bool FormatHasBeenSet() const { return m_formatHasBeenSet; }

    /**
     *
A format that specifies the type of the package to be updated.

     */
    inline void SetFormat(const PackageFormat& value) { m_formatHasBeenSet = true; m_format = value; }

    /**
     *
A format that specifies the type of the package to be updated.

     */
    inline void SetFormat(PackageFormat&& value) { m_formatHasBeenSet = true; m_format = std::move(value); }

    /**
     *
A format that specifies the type of the package to be updated.

     */
    inline PutPackageOriginConfigurationRequest& WithFormat(const PackageFormat& value) { SetFormat(value); return *this;}

    /**
     *
A format that specifies the type of the package to be updated.

     */
    inline PutPackageOriginConfigurationRequest& WithFormat(PackageFormat&& value) { SetFormat(std::move(value)); return *this;}

    /**
     *
The namespace of the package to be updated. The package component that
     * specifies its namespace depends on its type. For example:

 The
     * namespace of a Maven package is its groupId.

     * The namespace of an npm package is its scope.

     * Python and NuGet packages do not contain a corresponding component, packages of
     * those formats do not have a namespace.

     */
    inline const Aws::String& GetNamespace() const{ return m_namespace; }

    /**
     *
The namespace of the package to be updated. The package component that
     * specifies its namespace depends on its type. For example:

 The
     * namespace of a Maven package is its groupId.

     * The namespace of an npm package is its scope.

     * Python and NuGet packages do not contain a corresponding component, packages of
     * those formats do not have a namespace.

     */
    inline bool NamespaceHasBeenSet() const { return m_namespaceHasBeenSet; }

    /**
     *
The namespace of the package to be updated. The package component that
     * specifies its namespace depends on its type. For example:

 The
     * namespace of a Maven package is its groupId.

     * The namespace of an npm package is its scope.

     * Python and NuGet packages do not contain a corresponding component, packages of
     * those formats do not have a namespace.

     */
    inline void SetNamespace(const Aws::String& value) { m_namespaceHasBeenSet = true; m_namespace = value; }

    /**
     *
The namespace of the package to be updated. The package component that
     * specifies its namespace depends on its type. For example:

 The
     * namespace of a Maven package is its groupId.

     * The namespace of an npm package is its scope.

     * Python and NuGet packages do not contain a corresponding component, packages of
     * those formats do not have a namespace.

     */
    inline void SetNamespace(Aws::String&& value) { m_namespaceHasBeenSet = true; m_namespace = std::move(value); }

    /**
     *
The namespace of the package to be updated. The package component that
     * specifies its namespace depends on its type. For example:

 The
     * namespace of a Maven package is its groupId.

     * The namespace of an npm package is its scope.

     * Python and NuGet packages do not contain a corresponding component, packages of
     * those formats do not have a namespace.

     */
    inline void SetNamespace(const char* value) { m_namespaceHasBeenSet = true; m_namespace.assign(value); }

    /**
     *
The namespace of the package to be updated. The package component that
     * specifies its namespace depends on its type. For example:

 The
     * namespace of a Maven package is its groupId.

     * The namespace of an npm package is its scope.

     * Python and NuGet packages do not contain a corresponding component, packages of
     * those formats do not have a namespace.

     */
    inline PutPackageOriginConfigurationRequest& WithNamespace(const Aws::String& value) { SetNamespace(value); return *this;}

    /**
     *
The namespace of the package to be updated. The package component that
     * specifies its namespace depends on its type. For example:

 The
     * namespace of a Maven package is its groupId.

     * The namespace of an npm package is its scope.

     * Python and NuGet packages do not contain a corresponding component, packages of
     * those formats do not have a namespace.

     */
    inline PutPackageOriginConfigurationRequest& WithNamespace(Aws::String&& value) { SetNamespace(std::move(value)); return *this;}

    /**
     *
The namespace of the package to be updated. The package component that
     * specifies its namespace depends on its type. For example:

 The
     * namespace of a Maven package is its groupId.

     * The namespace of an npm package is its scope.

     * Python and NuGet packages do not contain a corresponding component, packages of
     * those formats do not have a namespace.

     */
    inline PutPackageOriginConfigurationRequest& WithNamespace(const char* value) { SetNamespace(value); return *this;}

    /**
     *
The name of the package to be updated.

     */
    inline const Aws::String& GetPackage() const{ return m_package; }

    /**
     *
The name of the package to be updated.

     */
    inline bool PackageHasBeenSet() const { return m_packageHasBeenSet; }

    /**
     *
The name of the package to be updated.

     */
    inline void SetPackage(const Aws::String& value) { m_packageHasBeenSet = true; m_package = value; }

    /**
     *
The name of the package to be updated.

     */
    inline void SetPackage(Aws::String&& value) { m_packageHasBeenSet = true; m_package = std::move(value); }

    /**
     *
The name of the package to be updated.

     */
    inline void SetPackage(const char* value) { m_packageHasBeenSet = true; m_package.assign(value); }

    /**
     *
The name of the package to be updated.

     */
    inline PutPackageOriginConfigurationRequest& WithPackage(const Aws::String& value) { SetPackage(value); return *this;}

    /**
     *
The name of the package to be updated.

     */
    inline PutPackageOriginConfigurationRequest& WithPackage(Aws::String&& value) { SetPackage(std::move(value)); return *this;}

    /**
     *
The name of the package to be updated.

     */
    inline PutPackageOriginConfigurationRequest& WithPackage(const char* value) { SetPackage(value); return *this;}

    /**
     *
A PackageOriginRestrictions
     * object that contains information about the upstream and
     * publish package origin restrictions. The upstream
     * restriction determines if new package versions can be ingested or retained from
     * external connections or upstream repositories. The publish
     * restriction determines if new package versions can be published directly to the
     * repository.

You must include both the desired upstream and
     * publish restrictions.

     */
    inline const PackageOriginRestrictions& GetRestrictions() const{ return m_restrictions; }

    /**
     *
A PackageOriginRestrictions
     * object that contains information about the upstream and
     * publish package origin restrictions. The upstream
     * restriction determines if new package versions can be ingested or retained from
     * external connections or upstream repositories. The publish
     * restriction determines if new package versions can be published directly to the
     * repository.

You must include both the desired upstream and
     * publish restrictions.

     */
    inline bool RestrictionsHasBeenSet() const { return m_restrictionsHasBeenSet; }

    /**
     *
A PackageOriginRestrictions
     * object that contains information about the upstream and
     * publish package origin restrictions. The upstream
     * restriction determines if new package versions can be ingested or retained from
     * external connections or upstream repositories. The publish
     * restriction determines if new package versions can be published directly to the
     * repository.

You must include both the desired upstream and
     * publish restrictions.

     */
    inline void SetRestrictions(const PackageOriginRestrictions& value) { m_restrictionsHasBeenSet = true; m_restrictions = value; }

    /**
     *
A PackageOriginRestrictions
     * object that contains information about the upstream and
     * publish package origin restrictions. The upstream
     * restriction determines if new package versions can be ingested or retained from
     * external connections or upstream repositories. The publish
     * restriction determines if new package versions can be published directly to the
     * repository.

You must include both the desired upstream and
     * publish restrictions.

     */
    inline void SetRestrictions(PackageOriginRestrictions&& value) { m_restrictionsHasBeenSet = true; m_restrictions = std::move(value); }

    /**
     *
A PackageOriginRestrictions
     * object that contains information about the upstream and
     * publish package origin restrictions. The upstream
     * restriction determines if new package versions can be ingested or retained from
     * external connections or upstream repositories. The publish
     * restriction determines if new package versions can be published directly to the
     * repository.

You must include both the desired upstream and
     * publish restrictions.

     */
    inline PutPackageOriginConfigurationRequest& WithRestrictions(const PackageOriginRestrictions& value) { SetRestrictions(value); return *this;}

    /**
     *
A PackageOriginRestrictions
     * object that contains information about the upstream and
     * publish package origin restrictions. The upstream
     * restriction determines if new package versions can be ingested or retained from
     * external connections or upstream repositories. The publish
     * restriction determines if new package versions can be published directly to the
     * repository.

You must include both the desired upstream and
     * publish restrictions.

     */
    inline PutPackageOriginConfigurationRequest& WithRestrictions(PackageOriginRestrictions&& value) { SetRestrictions(std::move(value)); return *this;}

  private:

    Aws::String m_domain;
    bool m_domainHasBeenSet = false;

    Aws::String m_domainOwner;
    bool m_domainOwnerHasBeenSet = false;

    Aws::String m_repository;
    bool m_repositoryHasBeenSet = false;

    PackageFormat m_format;
    bool m_formatHasBeenSet = false;

    Aws::String m_namespace;
    bool m_namespaceHasBeenSet = false;

    Aws::String m_package;
    bool m_packageHasBeenSet = false;

    PackageOriginRestrictions m_restrictions;
    bool m_restrictionsHasBeenSet = false;
  };

} // namespace Model
} // namespace CodeArtifact
} // namespace Aws


text:
Simple Ticketing System For Git Based Projects

## Quickstart
``` bash
sudo bash install.sh
```
Then run `ticket` from a git root to create a new ticket.

## Details
Tickets are stored as a file per ticket in the folder .tickets.


text:
update Chats
set StartDate =
(select min(m.SentOn) from Chats as c
inner join Messages as m
on c.Id = m.ChatId
where c.Id = Chats.Id
)
where Chats.Id in
(select c.Id from Chats as c
inner join Messages as m
on c.Id = m.ChatId
group by c.Id, c.StartDate
having c.StartDate > min(m.SentOn)
)


text:
layout: post
title: Good Comment
date: '2003-05-15 23:51:25 -0700'
mt_id: 209
blog_id: 1
post_id: 209
basename: good-comment
---

I just made a good comment about a post in the Signal vs. Noise blog. I'd repost it here, but you should really see in its original context.


text:
<?php

use backend\models\ConfigurationLogSearch;
use yii\web\View;
use yii\widgets\ActiveForm;
use yii\helpers\Html;

/* @var $this View */
/* @var $model ConfigurationLogSearch */
/* @var $form ActiveForm */
?>

<div class="operation-log-search">

    <?php $form = ActiveForm::begin(['action' => ['index'], 'method' => 'post']); ?>

    From date
    <?=
    yii\jui\DatePicker::widget([
        'model' => $model,
        'name' => $model->formName() . '[fromDate]',
        'dateFormat' => 'php:Y-m-d',
        'language' => 'en',
        'value' => \yii\helpers\Html::encode($model->fromDate)
    ])
    ?>
    To date
    <?=
    yii\jui\DatePicker::widget([
        'model' => $model,
        'name' => $model->formName() . '[toDate]',
        'dateFormat' => 'php:Y-m-d',
        'language' => 'en',
        'value' => \yii\helpers\Html::encode($model->toDate)
    ])
    ?>

    <input name="<?php echo $model->formName(); ?>[message]" value="<?php echo Html::encode($model->message); ?>" type="text" placeholder="message filter">

    <button type="submit" class="btn-reprt btn-primary">Report</button>

    <?php ActiveForm::end(); ?>

</div>


text:
#ifndef GW_GISREPORTSERVICE_H
#define GW_GISREPORTSERVICE_H

#include "sdk/include/sdk_export.h"

namespace LTE
{
    namespace TRUNK {
        namespace SDK {
            class SDK_IMPORT_EXPORT GISReportService
            {
            public:
                /**
                \brief Subscribe/Unsubscribe GPS reporting of a mobile terminal
                \param from_user : The Disptach Console ID who subscribes
                \param to: The mobile terminal ID
                \param gisInfo: a JSON string depicting the subscribed/unsubscribed mobile terminals, such as
                {
                "subtype":"sub", "uelist": [
                { "isdn":"1001" },
                { "isdn":"1002"}
                ]
                }
                \note "subtype" can be "sub" or "unsub"
                \return : please refer to dc_module_error.h in C:\Program Files\SDK\include\dc
                \since: TTR3.0
                */
                Op_Return_t GIS_SUB(const char*  from_user, const char*  to, const char*  gisInfo);

                /**
                \brief Customize GIS report configuration for a specific mobile terminal
                \param dcid : The Disptach Console ID which trigger the change
                \param mobileid: The mobile terminal ID
                \param gisCfg: a JSON string depicting the new GIS configuration, such as
                {
                "userid":"8001",
                "reportperiod":"10",
                "reportdistance":"1"
                }
                \note: "reportperiod" is in unit of second, shall be one vaule in {0,1,2,5,10,15,30,60}
                \note: "reportdistance" is in unit of meter, shall be a value between 0 and 10000
                \return : please refer to dc_module_error.h in C:\Program Files\SDK\include\dc
                \since: TTR4.0
                */
                Op_Return_t GIS_CFG(const char*  dcid, const char*  mobileid, const char*  gisCfg);
            };

            class SDK_IMPORT_EXPORT GISReportService_T
            {
            public:
                /**
                \brief Global access point to the GISReportService.
                \return : the singleton object for GISReportService
                */
                static GISReportService *instance (void);
            };
        }
    }
}

#endif // GW_GISREPORTSERVICE_H


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using Csla;

namespace MultipleBindingSources
{
  [Serializable]
  public class Child : BusinessBase<Child>
  {
    #region Business Methods

    private static readonly PropertyInfo<int> IdProperty = RegisterProperty<int>(p => p.Id);
    public int Id
    {
      get { return GetProperty<int>(IdProperty); }
      set { SetProperty<int>(IdProperty, value); }
    }

    private static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(p => p.Name);
    public string Name
    {
      get { return GetProperty<string>(NameProperty); }
      set { SetProperty<string>(NameProperty, value); }
    }

    private static int _lastId;

    public void DumpEditLevels(StringBuilder sb)
    {
      sb.AppendFormat("  {0} {1}: {2} {3}\r", this.GetType().Name, "n/a", this.EditLevel, this.BindingEdit);
    }

    protected override object GetIdValue()
    {
      return ReadProperty(IdProperty);
    }

    #endregion

    #region Business Rules

    protected override void AddBusinessRules()
    {
      // TODO: add validation rules
      //ValidationRules.AddRule(RuleMethod, "");
    }

    private static void AddObjectAuthorizationRules()
    {
      // TODO: add authorization rules
      //AuthorizationRules.AllowEdit(typeof(Child), "Role");
    }

    #endregion

    #region Factory Methods

    internal static Child NewEditableChild()
    {
      return DataPortal.CreateChild<Child>();
    }

    internal static Child GetEditableChild(object childData)
    {
      return DataPortal.FetchChild<Child>(childData);
    }

    private Child()
    { /* Require use of factory methods */ }

    #endregion

    #region Data Access

    protected override void Child_Create()
    {
      // TODO: load default values
      // omit this override if you have no defaults to set
      LoadProperty(IdProperty, System.Threading.Interlocked.Increment(ref _lastId));
      LoadProperty(NameProperty, string.Format("Child {0}", ReadProperty(IdProperty)));
      MarkAsChild();
    }

    private void Child_Fetch(object childData)
    {
      // TODO: load values
    }

    private void Child_Insert(object parent)
    {
      // TODO: insert values
    }

    private void Child_Update(object parent)
    {
      // TODO: update values
    }

    private void Child_DeleteSelf(object parent)
    {
      // TODO: delete values
    }

    #endregion
  }
}


text:
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInspection.java19modules;

import com.intellij.codeInsight.intention.QuickFixFactory;
import com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool;
import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * @author Pavel.Dolgov
 */
public class Java9ModuleExportsPackageToItselfInspection extends AbstractBaseJavaLocalInspectionTool {
  @NotNull
  @Override
  public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
    return PsiUtil.isModuleFile(holder.getFile()) ? new ExportedToSelfVisitor(holder) : PsiElementVisitor.EMPTY_VISITOR;
  }

  private static class ExportedToSelfVisitor extends JavaElementVisitor {
    private final ProblemsHolder myHolder;

    ExportedToSelfVisitor(ProblemsHolder holder) {
      myHolder = holder;
    }

    @Override
    public void visitPackageAccessibilityStatement(PsiPackageAccessibilityStatement statement) {
      super.visitPackageAccessibilityStatement(statement);
      PsiJavaModule javaModule = PsiTreeUtil.getParentOfType(statement, PsiJavaModule.class);
      if (javaModule != null) {
        String moduleName = javaModule.getName();
        List<PsiJavaModuleReferenceElement> references = ContainerUtil.newArrayList(statement.getModuleReferences());
        for (PsiJavaModuleReferenceElement referenceElement : references) {
          if (moduleName.equals(referenceElement.getReferenceText())) {
            String message = InspectionsBundle.message("inspection.module.exports.package.to.itself");
            if (references.size() == 1) {
              String fixText = InspectionsBundle.message("exports.to.itself.delete.statement.fix");
              myHolder.registerProblem(referenceElement, message, QuickFixFactory.getInstance().createDeleteFix(statement, fixText));
            }
            else {
              String fixText = InspectionsBundle.message("exports.to.itself.delete.module.ref.fix", moduleName);
              myHolder.registerProblem(referenceElement, message, QuickFixFactory.getInstance().createDeleteFix(referenceElement, fixText));
            }
          }
        }
      }
    }
  }
}


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = [
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
            new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(),
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
            new WhiteOctober\BreadcrumbsBundle\WhiteOctoberBreadcrumbsBundle(),
            new Sonata\CoreBundle\SonataCoreBundle(),
            new Sonata\BlockBundle\SonataBlockBundle(),
            new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
            new Sonata\AdminBundle\SonataAdminBundle(),
            new Sonata\TranslationBundle\SonataTranslationBundle(),
            new FOS\JsRoutingBundle\FOSJsRoutingBundle(),
            new Presta\SitemapBundle\PrestaSitemapBundle(),
            new Symfony\Cmf\Bundle\RoutingBundle\CmfRoutingBundle(),
            new Eko\FeedBundle\EkoFeedBundle(),
            new Liip\ImagineBundle\LiipImagineBundle(),
            new Hautelook\AliceBundle\HautelookAliceBundle(),

            new Harentius\BlogBundle\HarentiusBlogBundle(),
        ];

        if (in_array($this->getEnvironment(), ['dev', 'test'], true)) {
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();

            if ('dev' === $this->getEnvironment()) {
                $bundles[] = new Symfony\Bundle\WebServerBundle\WebServerBundle();
            }
        }

        return $bundles;
    }

    public function getRootDir()
    {
        return __DIR__;
    }

    public function getCacheDir()
    {
        return dirname(__DIR__).'/var/cache/'.$this->getEnvironment();
    }

    public function getLogDir()
    {
        return dirname(__DIR__).'/var/logs';
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
@implementation ZLPhotoAssets

- (UIImage *)thumbImage{
    return [UIImage imageWithCGImage:[self.asset thumbnail]];
}

- (UIImage *)originImage{
    return [UIImage imageWithCGImage:[[self.asset defaultRepresentation] fullScreenImage]];
}

@end
// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com


text:
#line 19 "admin_ops.cc" // ensures short filename in logs.

#include <errno.h>

#include <hbase/hbase.h>

#include "test_types.h"

namespace hbase {
namespace test {

#define COULD_NOT_CREATE_TABLE "Could not create HBase admin : errorCode = %d."
#define TABLE_EXISTS_DELETING "Table '%s' exists, deleting..."
#define COULD_NOT_DELETE_TABLE "Could not delete table %s[%d]."
#define TABLE_EXISTS "Table '%s' exists, will use it for test."
#define ERROR_WHILE_TABLE_EXISTS "Error while checking if the table exists: errorCode = %d."
#define CREATING_TABLE "Creating table '%s'..."
#define TABLE_IS_ENABLED_OR "Table '%s' is %senabled, result %d."
#define TABLE_CREATED_VERIFYING "Table '%s' created, verifying if enabled."

int32_t
ensureTable(
    hb_connection_t connection,
    bool createNew,
    const char* table_name,
    bytebuffer families[],
    size_t numFamilies) {
  int32_t retCode = 0;
  hb_admin_t admin = NULL;
  hb_columndesc *hcds = NULL;

  if ((retCode = hb_admin_create(connection, &admin)) != 0) {
    HBASE_LOG_ERROR(COULD_NOT_CREATE_TABLE, retCode);
    goto cleanup;
  }

  if ((retCode = hb_admin_table_exists(admin, NULL, table_name)) == 0) {
    if (createNew) {
      HBASE_LOG_INFO(TABLE_EXISTS_DELETING, table_name);
      if ((retCode = hb_admin_table_delete(admin, NULL, table_name)) != 0) {
        HBASE_LOG_ERROR(COULD_NOT_DELETE_TABLE, table_name, retCode);
        goto cleanup;
      }
    } else {
      HBASE_LOG_INFO(TABLE_EXISTS, table_name);
      goto cleanup;
    }
  } else if (retCode != ENOENT) {
    HBASE_LOG_ERROR(ERROR_WHILE_TABLE_EXISTS, retCode);
    goto cleanup;
  }

  hcds = new hb_columndesc[numFamilies];
  for (size_t i = 0; i < numFamilies; ++i) {
    hb_coldesc_create(families[i]->buffer, families[i]->length, &hcds[i]);
  }

  HBASE_LOG_INFO(CREATING_TABLE, table_name);
  if ((retCode = hb_admin_table_create(
      admin, NULL, table_name, hcds, numFamilies)) == 0) {
    HBASE_LOG_INFO(TABLE_CREATED_VERIFYING, table_name);
    retCode = hb_admin_table_enabled(admin, NULL, table_name);
    HBASE_LOG_MSG((retCode ? HBASE_LOG_LEVEL_ERROR : HBASE_LOG_LEVEL_INFO),
        TABLE_IS_ENABLED_OR, table_name, (retCode?"not ":""));
  }

  for (size_t i = 0; i < numFamilies; ++i) {
    hb_coldesc_destroy(hcds[i]);
  }

cleanup:
  if (hcds) {
    delete[] hcds;
  }
  if (admin) {
    hb_admin_destroy(admin, NULL, NULL);
  }
  return retCode;
}

} /* namespace test */
} /* namespace hbase */