text:
package com.cidic.equipment.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.cidic.equipment.exception.EquipmentException;
import com.cidic.equipment.model.ListResultModel;
import com.cidic.equipment.model.ResultModel;
import com.cidic.equipment.model.Texture;
import com.cidic.equipment.model.VehicleInfo;
import com.cidic.equipment.model.VehicleInfoTableModel;
import com.cidic.equipment.service.VehicleInfoService;
import com.cidic.equipment.util.ResponseCodeUtil;
import com.cidic.equipment.util.WebRequestUtil;

@Controller
@RequestMapping("/vehicleInfo")
public class VehicleInfoController {

	@Autowired
	@Qualifier(value = "vehicleInfoServiceImpl")
	private VehicleInfoService vehicleInfoServiceImpl;

	private ResultModel resultModel = null;

	@ExceptionHandler(EquipmentException.class)
	public @ResponseBody ResultModel handleCustomException(EquipmentException ex) {
		ResultModel resultModel = new ResultModel();
		resultModel.setResultCode(ex.getErrCode());
		resultModel.setMessage(ex.getErrMsg());
		resultModel.setSuccess(false);
		return resultModel;
	}

	@RequestMapping(value = "/infoMgr", method = RequestMethod.GET)
	public String infoMgr(Locale locale, Model model) {
		return "infoMgr";
	}

	@RequestMapping(value = "/infoCOU", method = RequestMethod.GET)
	public ModelAndView guideCOU(Locale locale, Model model) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("infoCOU");
		return modelAndView;
	}

	@RequestMapping(value = "/infoCOU/{id}", method = RequestMethod.GET)
    public ModelAndView updateInfoCOU(HttpServletRequest request, @PathVariable int id) {

		VehicleInfo vehicleInfo = null;
        if (id > 0) {
        	vehicleInfo = vehicleInfoServiceImpl.getDataByVehicleInfoId(id).get();
        }
        ModelAndView view = new ModelAndView();
        view.setViewName("infoCOU");
        view.addObject("info", vehicleInfo);
        return view;
    }

	@RequestMapping(value = "/createVehicleInfo", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel createVehicleInfo(HttpServletRequest request, HttpServletResponse response,
			@RequestBody VehicleInfo vehicleInfo) {
		WebRequestUtil.AccrossAreaRequestSet(request, response);
		resultModel = new ResultModel();
		vehicleInfo.setCreateTime(new Date());
		int result = vehicleInfoServiceImpl.createVehicleInfo(vehicleInfo);
		if (result == ResponseCodeUtil.DB_OPERATION_SUCCESS) {
			resultModel.setResultCode(200);
			resultModel.setSuccess(true);
			return resultModel;
		} else {
			throw new EquipmentException(500, "操作失败!");
		}
	}

	@RequestMapping(value = "/updateVehicleInfo", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel updateVehicleInfo(HttpServletRequest request, HttpServletResponse response,@RequestBody VehicleInfo vehicleInfo) {
		WebRequestUtil.AccrossAreaRequestSet(request, response);
		resultModel = new ResultModel();
		vehicleInfo.setCreateTime(new Date());
		int result = vehicleInfoServiceImpl.updateVehicleInfo(vehicleInfo);
		if (result == ResponseCodeUtil.DB_OPERATION_SUCCESS) {
			resultModel.setResultCode(200);
			resultModel.setSuccess(true);
			return resultModel;
		} else {
			throw new EquipmentException(500, "操作失败!");
		}
	}

	@RequestMapping(value = "/deleteVehicleInfo", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel deleteVehicleInfo(HttpServletRequest request, HttpServletResponse response, @RequestParam int id) {
		WebRequestUtil.AccrossAreaRequestSet(request, response);
		resultModel = new ResultModel();
		int result = vehicleInfoServiceImpl.deleteVehicleInfo(id);
		if (result == ResponseCodeUtil.DB_OPERATION_SUCCESS) {
			resultModel.setResultCode(200);
			resultModel.setSuccess(true);
			return resultModel;
		} else {
			throw new EquipmentException(500, "操作失败!");
		}
	}

	@RequestMapping(value = "/getDataByCondition", method = RequestMethod.GET)
	@ResponseBody
	public ListResultModel getDataByCondition(HttpServletRequest request, HttpServletResponse response,
			@RequestParam int iDisplayLength, @RequestParam int iDisplayStart, @RequestParam String sEcho) {

		WebRequestUtil.AccrossAreaRequestSet(request, response);
		ListResultModel listResultModel = new ListResultModel();
		try {

			VehicleInfoTableModel vehicleInfoTableModel = vehicleInfoServiceImpl.getVehicleInfoByPage(iDisplayStart, iDisplayLength);
			listResultModel.setAaData(vehicleInfoTableModel.getList());
			listResultModel.setsEcho(sEcho);
			listResultModel.setiTotalRecords((int) vehicleInfoTableModel.getCount());
			listResultModel.setiTotalDisplayRecords((int) vehicleInfoTableModel.getCount());
			listResultModel.setSuccess(true);
		} catch (Exception e) {
			listResultModel.setSuccess(false);
		}
		return listResultModel;
	}

	@RequestMapping(value = "/searchDataByCondition", method = RequestMethod.GET)
	@ResponseBody
	public ListResultModel searchDataByCondition(HttpServletRequest request, HttpServletResponse response, @RequestParam(required=false) String brand,
			@RequestParam int iDisplayLength, @RequestParam int iDisplayStart, @RequestParam(required=false) String startDate,
			@RequestParam(required=false) String endDate, @RequestParam(required=false) String marketType, @RequestParam String sEcho) {

		WebRequestUtil.AccrossAreaRequestSet(request, response);
		ListResultModel listResultModel = new ListResultModel();
		try {
			List<Integer> list = new ArrayList<>();
			if (brand.length() > 1){
				int[] brandsArray = Arrays.stream(brand.split(",")).mapToInt(s -> Integer.parseInt(s)).toArray();
		        list = Arrays.stream(brandsArray).boxed().collect(Collectors.toList());
			}

			List<Integer> marketTypeList = new ArrayList<>();
	        if (marketType.length() > 1){
	        	int[] marketTypesArray = Arrays.stream(marketType.split(",")).mapToInt(s -> Integer.parseInt(s)).toArray();
		        marketTypeList = Arrays.stream(marketTypesArray).boxed().collect(Collectors.toList());
	        }

	        Map<String,String> timeQuantumMap = new HashMap<String,String>();
	        if (startDate != null && !startDate.equals("")){
	        	timeQuantumMap.put("startYear", startDate);
	        }
	        if (endDate != null && !endDate.equals("")){
	        	timeQuantumMap.put("endYear", endDate);
	        }

			VehicleInfoTableModel vehicleInfoTableModel = vehicleInfoServiceImpl.getVehicleInfoBySearchCondition(list,timeQuantumMap,marketTypeList,iDisplayStart, iDisplayLength);
			listResultModel.setAaData(vehicleInfoTableModel.getList());
			listResultModel.setsEcho(sEcho);
			listResultModel.setiTotalRecords((int) vehicleInfoTableModel.getCount());
			listResultModel.setiTotalDisplayRecords((int) vehicleInfoTableModel.getCount());
			listResultModel.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			listResultModel.setSuccess(false);
		}
		return listResultModel;
	}

	@RequestMapping(value = "/getVehicleInfoById", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel getVehicleInfoById(HttpServletRequest request, HttpServletResponse response,@RequestParam int id) {
		WebRequestUtil.AccrossAreaRequestSet(request, response);
		resultModel = new ResultModel();
		try {
			VehicleInfo vehicleInfo = vehicleInfoServiceImpl.getDataByVehicleInfoId(id).get();
			resultModel.setResultCode(200);
			resultModel.setSuccess(true);
			resultModel.setObject(vehicleInfo);
			return resultModel;
		}catch (Exception e) {
			throw new EquipmentException(500, "操作失败!");
		}
	}
}


text:
"""
dyn_pages/feeds.py

Author: Kord Campbell
Date Added: 1/1/07

Builds RSS and ATOM feeds for the various pages on the site - cool, isn't it?
"""

## STD LIBS
from time import mktime
from xml.dom import minidom
from pprint import pformat
import datetime, xml

## OUR LIBS
from decorators import stack
import utils

## 3RD PARTY LIBS
from twisted.internet.defer import Deferred
from nevow import rend, inevow

class feeds(rend.Page):
	addSlash = True
	def __init__(self, username, app, log):
		self.username = username
		self.segments = []
		self.app = app
		self.log = log
		self.domain =  self.app.servers.httpserver._cfg_site_domain

	def locateChild(self, ctx, segments):
		self.segments = segments
		return self, []

	# called by twisted, this function parses the URL to figure out what type of feed to deliver, and what the globber should return
	def renderHTTP(self, ctx):
		self.request = inevow.IRequest(ctx)
		self.title_append_item = ""
		self.search_segment = ""

		# prep the glob with default info
		glob = {'include_comment_total': 1, 'order_by': 'date_uploaded', 'order_dir': 'desc', 'tag_list': True}
		self.search_items = []
		self.user_info = {}

		# ensure we have the correct feed types passed
		if self.segments[0] == "rss" or self.segments[0] == "atom" or self.segments[0] == "kml":
			if len(self.segments) > 1 and self.segments[1]:
				# parse out the search terms
				self.search_items = self.segments[1].split(".")

				if len(self.search_items) != 2:
					# ummm, no - we have no idea what you are doing
					return '<meta http-equiv="refresh" content="0;url=http://www.%s/not_found/">' % self.domain
				else:
					if self.search_items[0] == "SSQ":
						# search query
						glob['simple_search_query'] = self.search_items[1]
						self.title_append_item = " - searching on '%s'" % self.search_items[1]
						self.search_segment = self.segments[1]
					elif self.search_items[0] == "TUN":
						# tag query - we'll need to update this when we get advanced search (intersections/unions on tags)
						glob['tag_union'] = [self.search_items[1]]
						self.title_append_item = " - tagged with '%s'" % self.search_items[1]
						self.search_segment = self.segments[1]
					elif self.search_items[0] == "ALB":
						# album query - we need to update this to support album names - but whatever - it's release time!!!
						glob['album_id'] = int(self.search_items[1])
						self.title_append_item = ""
						self.search_segment = self.segments[1]
					else:
						# again, we have no idea what you are doing
						return '<meta http-equiv="refresh" content="0;url=http://www.%s/not_found/">' % self.domain
		else:
			# unsupported feed type
			return '<meta http-equiv="refresh" content="0;url=http://www.%s/not_found/">' % self.domain

		def act(globber_result):
			# grab some user info
			d2 = self.app.api.users.get_user_id(self.username)
			d2.addCallback(handle_user_id, globber_result)
			return d2

		def handle_user_id(result):
			if result[0] != 0:
				return "Bad username"
			self.userid = result[1]
			if self.userid:
				d3 = self.app.api.users.get_info(self.userid, None)
			else:
				d3 = Deferred()
				d3.callback((0, {}))
			d3.addCallback(handle_user_info)
			return d3

		@stack
		def handle_user_info(result):
			if result[0] != 0:
				return "NO USER INFO"
			self.user_info = result[1]

			limit = 20 # flickr does 20, so we do 20
			offset = 0 # shouldn't ever be anything else
			d4 = self.app.api.globber.get_images(self.userid, None, glob, limit, offset)
			d4.addCallback(handle_globber_result)
			return d4

		@stack
		def handle_globber_result(result):
			if result[0] != 0:
				return "NO PHOTOS"

			self.photo_list = result[1]

			if self.userid:
				if len(self.search_items) and self.search_items[0] == "ALB":
					self.log.warning("we have an album search item: %s" % self.search_items[1])
					d5 = self.app.api.albums.get_info(None, int(self.search_items[1]))
				else:
					self.log.warning("no album search item")
					d5 = Deferred()
					d5.callback((0, None))
			else:
				d5 = Deferred()
				d5.callback((0, None))
			d5.addCallback(handle_album_info)
			return d5

		@stack
		def handle_album_info(result):
			if result[0] != 0:
				return "NO ALBUMS"
			self.album_info = result[1]

			if not self.userid:
				self.user_info['last_login'] = datetime.datetime.now()
				self.user_info['date_created'] = datetime.datetime.now()

			globber_arg = (0, self.photo_list)
			album_arg = (0, self.album_info)

			if self.segments[0] == "rss":
				return self._build_rss2_feed(self.user_info, globber_arg, album_arg)
			elif self.segments[0] == "atom":
				return self._build_atom_feed(self.user_info, globber_arg, album_arg)
			elif self.segments[0] == "kml":
				return self._build_kml_feed(self.user_info, globber_arg, album_arg)

		if self.username == "*ALL*":
			d = Deferred()
			d.callback((0, None))
		else:
			d = self.app.api.users.get_user_id(self.username)
		d.addCallback(handle_user_id)
		return d

	def _format_date(self, dt):
		return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
			["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"][dt.weekday()],
			dt.day,
			["Jan", "Feb", "Mar", "Apr", "May", "Jun",
			"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][dt.month-1],
			dt.year, dt.hour, dt.minute, dt.second)

	# function that josh had to write twice
	@stack
	def create_node(self, doc, label, attributes, children):
		node = doc.createElement(label)
		for key, value in attributes.items():
			node.setAttribute(key, value)

		if children:
			for child in children:
				node.appendChild(child)

		return node

	# call for building a rss feed
	def _build_rss2_feed(self, user_result, globber_result, album_result):
		if album_result[0] == 0 and album_result[1]:
			album_info = album_result[1]
		else:
			album_info = {}

		MEDIA_NS = 'http://search.yahoo.com/mrss/'
		DUBLIN_NS = 'http://purl.org/dc/elements/1.1/'
		if album_info:
			## you have an album
			self.title_append_item = " - %s" % album_info['title']
		else:
			self.title_append_item = ""

		# Create an atom feed
		doc = xml.dom.minidom.getDOMImplementation().createDocument('', 'rss', None)
		doc.documentElement.setAttribute('version', "2.0")
		doc.documentElement.setAttribute('xmlns:media', MEDIA_NS)
		doc.documentElement.setAttribute('xmlns:dc', DUBLIN_NS)

		# create channel entry
		channel_node = self.create_node(doc, 'channel', {}, [])
		channel_node.appendChild(doc.createTextNode("\n"))

		if self.username != "*ALL*":
			# define possessive username
			pos_user = utils.possesive_username(self.username)

			# Title
			feed_title = "%s photos%s" % (pos_user, self.title_append_item)
		else:
			feed_title = "Everyone's photos on Zoto%s" % (self.title_append_item)

		title_node = self.create_node(doc, 'title', {}, [doc.createTextNode(feed_title)])
		channel_node.appendChild(title_node)

		# feed links
		if self.username != "*ALL*":
			feed_link = "http://www.%s/site/#USR.%s::PAG.lightbox" % (self.domain, self.username)
		else:
			feed_link = "http://www.%s/#PAG.explore" % self.domain

		link_node = self.create_node(doc, 'link', {}, [doc.createTextNode(feed_link)])
		channel_node.appendChild(link_node)

		# description
		if self.username != "*ALL*":
			feed_sub_title = "A feed of %s photos" % (pos_user)
		else:
			feed_sub_title = "A feed of everyone's photos on Zoto%s." % (self.title_append_item)

		sub_title_node = self.create_node(doc, 'description', {}, [doc.createTextNode(feed_sub_title)])
		channel_node.appendChild(sub_title_node)

		# pubdate and lastbuilddate
		if globber_result[0]:
			feed_pubDate =  self._format_date(datetime.datetime.now())
			feed_lastBuildDate = self._format_date(datetime.datetime.now())
		else:
			feed_pubDate =  self._format_date(datetime.datetime.now())
			feed_lastBuildDate = self._format_date(datetime.datetime.now())
			#feed_pubDate = self._format_date(globber_result[1]['date_uploaded'])
			#feed_lastBuildDate = self._format_date(globber_result[1]['date_uploaded'])

		# TODO - fix this to use GMT converted times
		pub_date_node = self.create_node(doc, 'pubDate', {}, [doc.createTextNode(feed_pubDate)])
		last_build_node = self.create_node(doc, 'lastBuildDate', {}, [doc.createTextNode(feed_lastBuildDate)])
		channel_node.appendChild(pub_date_node)
		channel_node.appendChild(last_build_node)

		# Generator
		PROGRAM_URI = "http://www.%s/" % self.domain
		generator_node = self.create_node(doc, 'generator', {}, [doc.createTextNode(PROGRAM_URI)])
		channel_node.appendChild(generator_node)

		# image
		if self.username != "*ALL*":
			image = "http://www.%s/%s/avatar-small.jpg" % (self.domain, self.username)
		else:
			image = "http://www.%s/image/avatar-11.jpg" % (self.domain)

		image_node = self.create_node(doc, 'image', {}, [])
		image_url_node = self.create_node(doc, 'url', {}, [doc.createTextNode(image)])
		image_title_node = self.create_node(doc, 'title', {}, [doc.createTextNode(feed_title)])
		image_link_node = self.create_node(doc, 'link', {}, [doc.createTextNode(feed_link)])
		image_node.appendChild(image_url_node)
		image_node.appendChild(image_title_node)
		image_node.appendChild(image_link_node)
		channel_node.appendChild(image_node)

		if not globber_result[0]:

			# photos
			for i in globber_result[1]:
				item_node = doc.createElement('item')

				# Title
				item_title = i['title']
				title_node = self.create_node(doc, 'title', {}, [doc.createTextNode(item_title)])
				item_node.appendChild(title_node)

				# feed links - alternate
				item_link = "http://www.%s/site/#USR.%s::PAG.detail::%s" % (self.domain, i['owner_username'], i['media_id'])
				link_node = self.create_node(doc, 'link', {}, [doc.createTextNode(item_link)])
				item_node.appendChild(link_node)

				# do the math for the rendered width or height (using a 240x240 render - size 28)
				height_width_constraint = 240 # change this if you change the size we use (which we won't)
				image_size_used = 28
				if i['current_width'] and i['current_height']:
					original_width = i['current_width']
					original_height = i['current_height']
				else:
					original_width = i['original_width']
					original_height = i['original_height']

				if original_width > original_height:
					# landscape
					item_width = height_width_constraint
					item_height = (height_width_constraint * (original_height*100/original_width))/100
				elif original_width < original_height:
					# portrait
					item_height = height_width_constraint
					item_width = (height_width_constraint * (original_width*100/original_height))/100
				else:
					# square
					item_height = height_width_constraint
					item_width = height_width_constraint

				# description
				image_link = "http://www.%s/%s/img/%s/%s.jpg" % (self.domain, i['owner_username'], image_size_used, i['media_id'])
				description = '
%s posted a photo

' % (self.domain, i['owner_username'], i['owner_username'], item_link, item_title, image_link, item_width, item_height, item_title)
				description_node = self.create_node(doc, 'description', {}, [doc.createTextNode(description)])
				item_node.appendChild(description_node)

				# pubDate entry
				pubDate = self._format_date(i['date_uploaded'])
				pubdate_node = self.create_node(doc, 'pubDate', {}, [doc.createTextNode(pubDate)])
				item_node.appendChild(pubdate_node)

				# dc:date.Taken entry
				if i['date']:
					taken = datetime.datetime.utcfromtimestamp(mktime(i['date'].timetuple()))
				else:
					taken = datetime.datetime.utcfromtimestamp(mktime(i['date_uploaded'].timetuple()))

				year = taken.year
				month = taken.month
				day = taken.day
				hour = taken.hour
				minute = taken.minute
				second = taken.second
				date_taken = "%s-%2.2d-%2.2dT%2.2d:%2.2d:%2.2dZ" % (year, int(month), day, hour, minute, second)
				date_node = self.create_node(doc, 'dc:date.Taken', {}, [doc.createTextNode(date_taken)])
				item_node.appendChild(date_node)

				# author entry
				author_entry = "noreply@zoto.com (%s)" % (i['owner_username'])
				date_node = self.create_node(doc, 'author', {}, [doc.createTextNode(author_entry)])

				# guid entry
				item_guid = "tag:%s,%s:/site/#USR.%s::PAG.detail::%s" % (self.domain, i['date_uploaded'].year, i['owner_username'], i['media_id'])
				guid_node = self.create_node(doc, 'guid', {'isPermaLink': "false"}, [doc.createTextNode(item_guid)])
				item_node.appendChild(guid_node)

				# media:content entry
				item_media_content_url = "http://www.%s/img/35/%s.jpg" % (self.domain, i['media_id'])
				item_media_content_type = "image/jpeg"
				item_media_content_height = str(item_height)
				item_media_content_width = str(item_width)
				media_content_node = self.create_node(doc, 'media:content', {'url': item_media_content_url, 'type': item_media_content_type, 'height': item_media_content_height, 'width': item_media_content_width}, [])
				item_node.appendChild(media_content_node)

				# media:title entry
				item_media_title = i['title']
				media_title_node = self.create_node(doc, 'media:title', {}, [doc.createTextNode(item_media_title)])
				item_node.appendChild(media_title_node)

				# media:text entry
				media_text_node = self.create_node(doc, 'media:text', {'type': "html"}, [doc.createTextNode(description)])
				item_node.appendChild(media_text_node)

				# again, we are using a predefined size, 16, which is 75x75 (minimal view size)
				item_media_thumbnail_height = 75
				item_media_thumbnail_width = 75
				item_media_image_size_used = 16

				# build the thumbnail for media:thumbnail (convert height and width to strings so the library can handle it)
				item_media_thumbnail_url = "http://www.%s/%s/img/%s/%s.jpg" % (self.domain, i['owner_username'], item_media_image_size_used, i['media_id'])
				height = str(item_media_thumbnail_height)
				width = str(item_media_thumbnail_width)
				media_thumbnail_node = self.create_node(doc, 'media:thumbnail', {'url': item_media_thumbnail_url, 'height': height, 'width': width}, [])
				item_node.appendChild(media_thumbnail_node)

				# media:credit entry
				item_media_credit = i['owner_username']
				item_media_role = "photographer"
				media_credit_node = self.create_node(doc, 'media:credit', {'role': item_media_role}, [doc.createTextNode(item_media_credit)])
				item_node.appendChild(media_credit_node)

				# loop through the tags on the photo and build a category entry - how do we do this with multi-word tags?  dunno.
				tag_nodes = []
				for j in i['tag_list']:
					tag_nodes.append(doc.createTextNode(unicode(j, "utf-8")))

				media_category_node = self.create_node(doc, 'media:category', {'scheme': "urn:zoto:tags"}, tag_nodes)
				item_node.appendChild(media_category_node)

				# attach item node - last thing in loop
				channel_node.appendChild(item_node)

		doc.documentElement.appendChild(channel_node)

		# build the page and set the type
		data = doc.toxml('utf-8')

		self.request.setHeader('content-type', 'text/xml')
		self.request.setHeader('content-length', str(len(data)))

		return data

	# call for building an atom feed
	@stack
	def _build_atom_feed(self, user_result, globber_result, album_result):
		if album_result[0] == 0 and album_result[1]:
			album_info = album_result[1]
		else:
			album_info = {}

		ATOM_NS = 'http://www.w3.org/2005/Atom'
		DUBLIN_NS = 'http://purl.org/dc/elements/1.1/'

		# Create an atom feed
		doc = xml.dom.minidom.getDOMImplementation().createDocument('', 'feed', None)
		doc.documentElement.setAttribute('xmlns',ATOM_NS)
		doc.documentElement.setAttribute('xmlns:dc',DUBLIN_NS)

		if self.username != "*ALL*":
			# define possessive username
			pos_user = utils.possesive_username(self.username)

			# Title
			feed_title = "%s photos%s" % (pos_user, self.title_append_item)
		else:
			feed_title = "Everyone's photos on Zoto%s" % (self.title_append_item)

		title_node = self.create_node(doc, 'title', {}, [doc.createTextNode(feed_title)])
		doc.documentElement.appendChild(title_node)

		# feed links - self
		if self.username != "*ALL*":
			feed_link = "http://www.%s/%s/feeds/atom/%s" % (self.domain, self.username, self.search_segment)
		else:
			feed_link = "http://www.%s/%s/feeds/atom/%s" % (self.domain, "community", self.search_segment)

		link_node = self.create_node(doc, 'link', {'rel': 'self', 'href': feed_link}, [])
		doc.documentElement.appendChild(link_node)

		# feed links - alternate
		if self.username != "*ALL*":
			feed_link = "http://www.%s/%s/" % (self.domain, self.username)
		else:
			feed_link = "http://www.%s/%s/" % (self.domain, "community")

		link_node = self.create_node(doc, 'link', {'rel': "alternate", 'type': "text/html", 'href': feed_link}, [])
		doc.documentElement.appendChild(link_node)

		# ID
		if self.username != "*ALL*":
			id_text = "tag:%s,%s:/%s/photos#%s" % (self.domain, user_result['date_created'].year, self.username, self.search_segment)
		else:
			id_text = "tag:%s,%s:/%s/photos#%s" % (self.domain, user_result['date_created'].year, "community", self.search_segment)

		id_node = self.create_node(doc, 'id', {}, [doc.createTextNode(id_text)])
		doc.documentElement.appendChild(id_node)

		# user icon
		if self.username != "*ALL*":
			feed_icon = "http://www.%s/%s/avatar-small.jpg" % (self.domain, self.username)
		else:
			feed_icon = "http://www.%s/image/avatar-11.jpg" % (self.domain)

		icon_node = self.create_node(doc, 'icon', {}, [doc.createTextNode(feed_icon)])
		doc.documentElement.appendChild(icon_node)

		# sub Title
		if self.username != "*ALL*":
			feed_sub_title = "A feed of %s photos" % (pos_user)
		else:
			feed_sub_title = "A feed of everyone's photos on Zoto%s." % (self.title_append_item)

		sub_title_node = self.create_node(doc, 'subtitle', {}, [doc.createTextNode(feed_sub_title)])
		doc.documentElement.appendChild(sub_title_node)

		# updated
		updated = datetime.datetime.utcfromtimestamp(mktime(user_result['last_login'].timetuple()))
		year = updated.year
		month = updated.month
		day = updated.day
		hour = updated.hour
		minute = updated.minute
		second = updated.second
		feed_updated = "%s-%2.2d-%2.2dT%2.2d:%2.2d:%2.2dZ" % (year, int(month), day, hour, minute, second)
		updated_node = self.create_node(doc, 'updated', {}, [doc.createTextNode(feed_updated)])
		doc.documentElement.appendChild(updated_node)

		# Generator
		PROGRAM_NAME = "Zoto"
		PROGRAM_URI = "http://www.%s/" % self.domain
		VERSION = "3.0"
		generator_node = self.create_node(doc, 'generator', {'version': VERSION, 'uri': PROGRAM_URI}, [doc.createTextNode(PROGRAM_NAME)])
		doc.documentElement.appendChild(generator_node)

		if not globber_result[0]:

			# photos
			for i in globber_result[1]:
				entry_node = doc.createElement('entry')

				# Title
				item_title = i['title']
				title_node = self.create_node(doc, 'title', {}, [doc.createTextNode(item_title)])
				entry_node.appendChild(title_node)

				# feed links - alternate
				item_link = "http://www.%s/%s/detail/#%s" % (self.domain, i['owner_username'], i['media_id'])
				link_node = self.create_node(doc, 'link', {'rel': "alternate", 'type': "text/html", 'href': item_link}, [])
				entry_node.appendChild(link_node)

				# id entry
				item_id = "tag:%s,%s:/%s/detail/#%s" % (self.domain, i['date_uploaded'].year, i['owner_username'], i['media_id'])
				id_node = self.create_node(doc, 'id', {}, [doc.createTextNode(item_id)])
				entry_node.appendChild(id_node)

				# published
				published = datetime.datetime.utcfromtimestamp(mktime(i['date_uploaded'].timetuple()))
				year = published.year
				month = published.month
				day = published.day
				hour = published.hour
				minute = published.minute
				second = published.second
				item_pub = "%s-%2.2d-%2.2dT%2.2d:%2.2d:%2.2dZ" % (year, int(month), day, hour, minute, second)
				pub_node = self.create_node(doc, 'published', {}, [doc.createTextNode(item_pub)])
				entry_node.appendChild(pub_node)

				# updated (borrowing item_pub from published)
				updated_node = self.create_node(doc, 'updated', {}, [doc.createTextNode(item_pub)])
				entry_node.appendChild(updated_node)

				# dc:date.Taken
				if not i['date']:
					i['date'] = i['date_uploaded']
				taken = datetime.datetime.utcfromtimestamp(mktime(i['date'].timetuple()))
				year = taken.year
				month = taken.month
				day = taken.day
				hour = taken.hour
				minute = taken.minute
				second = taken.second
				item_taken = "%s-%2.2d-%2.2dT%2.2d:%2.2d:%2.2dZ" % (year, int(month), day, hour, minute, second)
				dc_taken_node = self.create_node(doc, 'dc:date.Taken', {}, [doc.createTextNode(item_taken)])
				entry_node.appendChild(dc_taken_node)

				# do the math for the rendered width or height (using a 240x240 render - size 28)
				height_width_constraint = 240 # change this if you change the size we use (which we won't)
				image_size_used = 28
				if i['current_width'] and i['current_height']:
					original_width = i['current_width']
					original_height = i['current_height']
				else:
					original_width = i['original_width']
					original_height = i['original_height']

				if original_width > original_height:
					# landscape
					item_width = height_width_constraint
					item_height = (height_width_constraint * (original_height*100/original_width))/100
				elif original_width < original_height:
					# portrait
					item_height = height_width_constraint
					item_width = (height_width_constraint * (original_width*100/original_height))/100
				else:
					# square
					item_height = height_width_constraint
					item_width = height_width_constraint

				# content
				image_link = "http://www.%s/%s/img/%s/%s.jpg" % (self.domain, i['owner_username'], image_size_used, i['media_id'])
				content = '
%s posted a photo

' % (self.domain, i['owner_username'], i['owner_username'], item_link, item_title, image_link, item_width, item_height, item_title)
				content_node = self.create_node(doc, 'content', {'type': "html"}, [doc.createTextNode(content)])
				entry_node.appendChild(content_node)

				# author
				author_node = self.create_node(doc, 'author', {}, [])
				name_node = self.create_node(doc, 'name', {}, [doc.createTextNode(i['owner_username'])])
				author_node.appendChild(name_node)
				uri_link = "http://www.%s/%s/" % (self.domain, i['owner_username'])
				uri_node = self.create_node(doc, 'uri', {}, [doc.createTextNode(uri_link)])
				author_node.appendChild(uri_node)
				entry_node.appendChild(author_node)

				# link enclosure
				enclosure_node = self.create_node(doc, 'link', {'type': "image/jpeg", 'rel': "enclosure", 'href': image_link}, [])
				entry_node.appendChild(enclosure_node)

				# loop through the tags on the photo
				for j in i['tag_list']:
					tag_name = j
					scheme = "http://www.%s/%s/tags/" % (self.domain, i['owner_username'])
					tag_node = self.create_node(doc, 'category', {'term': unicode(tag_name, "utf-8"), 'scheme': scheme}, [])
					entry_node.appendChild(tag_node)

				# tack on the entry_node to the main document
				doc.documentElement.appendChild(entry_node)

		# build the page and set the type
		#data = doc.toprettyxml()
		data = doc.toxml('utf-8')

		self.request.setHeader('content-type', 'text/xml')
		self.request.setHeader('content-length', str(len(data)))

		return data

	# to be done, kml feeds for google earth exports
	def _build_kml_feed(self, user_result, globber_result, album_info):
		return "kml feed"

redpajama_set_name: RedPajamaGithub


text:
/*************************************************************************/
/*  emws_peer.cpp                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifdef JAVASCRIPT_ENABLED

#include "emws_peer.h"
#include "core/io/ip.h"

void EMWSPeer::set_sock(int p_sock, unsigned int p_in_buf_size, unsigned int p_in_pkt_size) {
	peer_sock = p_sock;
	_in_buffer.resize(p_in_pkt_size, p_in_buf_size);
	_packet_buffer.resize((1 << p_in_buf_size));
}

void EMWSPeer::set_write_mode(WriteMode p_mode) {
	write_mode = p_mode;
}

EMWSPeer::WriteMode EMWSPeer::get_write_mode() const {
	return write_mode;
}

Error EMWSPeer::read_msg(uint8_t *p_data, uint32_t p_size, bool p_is_string) {
	uint8_t is_string = p_is_string ? 1 : 0;
	return _in_buffer.write_packet(p_data, p_size, &is_string);
}

Error EMWSPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
	int is_bin = write_mode == WebSocketPeer::WRITE_MODE_BINARY ? 1 : 0;

	/* clang-format off */
	EM_ASM({
		var sock = Module.IDHandler.get($0);
		var bytes_array = new Uint8Array($2);
		var i = 0;

		for(i=0; i<$2; i++) {
			bytes_array[i] = getValue($1+i, 'i8');
		}

		try {
			if ($3) {
				sock.send(bytes_array.buffer);
			} else {
				var string = new TextDecoder("utf-8").decode(bytes_array);
				sock.send(string);
			}
		} catch (e) {
			return 1;
		}
		return 0;
	}, peer_sock, p_buffer, p_buffer_size, is_bin);
	/* clang-format on */

	return OK;
};

Error EMWSPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
	if (_in_buffer.packets_left() == 0)
		return ERR_UNAVAILABLE;

	int read = 0;
	Error err = _in_buffer.read_packet(_packet_buffer.ptrw(), _packet_buffer.size(), &_is_string, read);
	ERR_FAIL_COND_V(err != OK, err);

	*r_buffer = _packet_buffer.ptr();
	r_buffer_size = read;

	return OK;
};

int EMWSPeer::get_available_packet_count() const {
	return _in_buffer.packets_left();
};

bool EMWSPeer::was_string_packet() const {
	return _is_string;
};

bool EMWSPeer::is_connected_to_host() const {
	return peer_sock != -1;
};

void EMWSPeer::close(int p_code, String p_reason) {
	if (peer_sock != -1) {
		/* clang-format off */
		EM_ASM({
			var sock = Module.IDHandler.get($0);
			var code = $1;
			var reason = UTF8ToString($2);
			sock.close(code, reason);
			Module.IDHandler.remove($0);
		}, peer_sock, p_code, p_reason.utf8().get_data());
		/* clang-format on */
	}
	_is_string = 0;
	_in_buffer.clear();
	peer_sock = -1;
};

IP_Address EMWSPeer::get_connected_host() const {
	ERR_FAIL_V_MSG(IP_Address(), "Not supported in HTML5 export.");
};

uint16_t EMWSPeer::get_connected_port() const {
	ERR_FAIL_V_MSG(0, "Not supported in HTML5 export.");
};

void EMWSPeer::set_no_delay(bool p_enabled) {
	ERR_FAIL_MSG("'set_no_delay' is not supported in HTML5 export.");
}

EMWSPeer::EMWSPeer() {
	peer_sock = -1;
	write_mode = WRITE_MODE_BINARY;
	close();
};

EMWSPeer::~EMWSPeer() {
	close();
};

#endif // JAVASCRIPT_ENABLED


text:
// Code generated by protoc-gen-go.
// source: sink.proto
// DO NOT EDIT!

/*
Package proto is a generated protocol buffer package.

It is generated from these files:
	sink.proto

It has these top-level messages:
	UploadRequest
	Blob
	UploadResponse
*/
package proto

import proto1 "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"

import (
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto1.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto1.ProtoPackageIsVersion2 // please upgrade the proto package

type UploadRequest struct {
	Blob []*Blob `protobuf:"bytes,1,rep,name=blob" json:"blob,omitempty"`
}

func (m *UploadRequest) Reset()                    { *m = UploadRequest{} }
func (m *UploadRequest) String() string            { return proto1.CompactTextString(m) }
func (*UploadRequest) ProtoMessage()               {}
func (*UploadRequest) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }

func (m *UploadRequest) GetBlob() []*Blob {
	if m != nil {
		return m.Blob
	}
	return nil
}

type Blob struct {
	Data []byte `protobuf:"bytes,1,opt,name=data,proto3" json:"data,omitempty"`
}

func (m *Blob) Reset()                    { *m = Blob{} }
func (m *Blob) String() string            { return proto1.CompactTextString(m) }
func (*Blob) ProtoMessage()               {}
func (*Blob) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }

type UploadResponse struct {
}

func (m *UploadResponse) Reset()                    { *m = UploadResponse{} }
func (m *UploadResponse) String() string            { return proto1.CompactTextString(m) }
func (*UploadResponse) ProtoMessage()               {}
func (*UploadResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }

func init() {
	proto1.RegisterType((*UploadRequest)(nil), "proto.UploadRequest")
	proto1.RegisterType((*Blob)(nil), "proto.Blob")
	proto1.RegisterType((*UploadResponse)(nil), "proto.UploadResponse")
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion3

// Client API for Sink service

type SinkClient interface {
	Upload(ctx context.Context, in *UploadRequest, opts ...grpc.CallOption) (*UploadResponse, error)
}

type sinkClient struct {
	cc *grpc.ClientConn
}

func NewSinkClient(cc *grpc.ClientConn) SinkClient {
	return &sinkClient{cc}
}

func (c *sinkClient) Upload(ctx context.Context, in *UploadRequest, opts ...grpc.CallOption) (*UploadResponse, error) {
	out := new(UploadResponse)
	err := grpc.Invoke(ctx, "/proto.Sink/Upload", in, out, c.cc, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// Server API for Sink service

type SinkServer interface {
	Upload(context.Context, *UploadRequest) (*UploadResponse, error)
}

func RegisterSinkServer(s *grpc.Server, srv SinkServer) {
	s.RegisterService(&_Sink_serviceDesc, srv)
}

func _Sink_Upload_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(UploadRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(SinkServer).Upload(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/proto.Sink/Upload",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(SinkServer).Upload(ctx, req.(*UploadRequest))
	}
	return interceptor(ctx, in, info, handler)
}

var _Sink_serviceDesc = grpc.ServiceDesc{
	ServiceName: "proto.Sink",
	HandlerType: (*SinkServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "Upload",
			Handler:    _Sink_Upload_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: fileDescriptor0,
}

func init() { proto1.RegisterFile("sink.proto", fileDescriptor0) }

var fileDescriptor0 = []byte{
	// 150 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x2a, 0xce, 0xcc, 0xcb,
	0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x05, 0x53, 0x4a, 0x06, 0x5c, 0xbc, 0xa1, 0x05,
	0x39, 0xf9, 0x89, 0x29, 0x41, 0xa9, 0x85, 0xa5, 0xa9, 0xc5, 0x25, 0x42, 0xf2, 0x5c, 0x2c, 0x49,
	0x39, 0xf9, 0x49, 0x12, 0x8c, 0x0a, 0xcc, 0x1a, 0xdc, 0x46, 0xdc, 0x10, 0xd5, 0x7a, 0x4e, 0x39,
	0xf9, 0x49, 0x41, 0x60, 0x09, 0x25, 0x29, 0x2e, 0x16, 0x10, 0x4f, 0x48, 0x88, 0x8b, 0x25, 0x25,
	0xb1, 0x24, 0x51, 0x82, 0x51, 0x81, 0x51, 0x83, 0x27, 0x08, 0xcc, 0x56, 0x12, 0xe0, 0xe2, 0x83,
	0x99, 0x56, 0x5c, 0x90, 0x9f, 0x57, 0x9c, 0x6a, 0x64, 0xcf, 0xc5, 0x12, 0x9c, 0x99, 0x97, 0x2d,
	0x64, 0xce, 0xc5, 0x06, 0x91, 0x11, 0x12, 0x81, 0x1a, 0x89, 0x62, 0xad, 0x94, 0x28, 0x9a, 0x28,
	0x44, 0xbb, 0x12, 0x43, 0x12, 0x1b, 0x58, 0xdc, 0x18, 0x10, 0x00, 0x00, 0xff, 0xff, 0xa3, 0x2d,
	0xd2, 0xf2, 0xbc, 0x00, 0x00, 0x00,
}


text:
/**
 *
 */
package com.perforce.p4java.exception;

/**
 * A P4Java extension used to signal to participating
 * users that an error occurred in Options object processing.
 */

public class OptionsException extends P4JavaException {

	private static final long serialVersionUID = 1L;

	public OptionsException() {
		super();
	}

	public OptionsException(String message, Throwable cause) {
		super(message, cause);
	}

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

	public OptionsException(Throwable cause) {
		super(cause);
	}
}


text:
/**
 * Standard Postmark error on which all sub-errors are based.
 */
export class PostmarkError extends Error {
    public code: number;
    public statusCode: number;

    constructor(message: string, code: number = 0, statusCode: number = 0) {
        super(message);
        this.statusCode = statusCode;
        this.code = code;

        // this is mandatory due:
        // https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
        Object.setPrototypeOf(this, PostmarkError.prototype);
        this.setUpStackTrace();
    }

    protected setUpStackTrace() {
        this.name = this.constructor.name;
        Error.captureStackTrace(this, this.constructor);
    }
}

export class HttpError extends PostmarkError {
    constructor(message: string, code: number, statusCode: number) {
        super(message, code, statusCode);
        Object.setPrototypeOf(this, HttpError.prototype);
        this.setUpStackTrace();
    }
}

export class InvalidAPIKeyError extends HttpError {
    constructor(message: string, code: number, statusCode: number) {
        super(message, code, statusCode);
        Object.setPrototypeOf(this, InvalidAPIKeyError.prototype);
        this.setUpStackTrace();
    }
}

export class InternalServerError extends HttpError {
    constructor(message: string, code: number, statusCode: number) {
        super(message, code, statusCode);
        Object.setPrototypeOf(this, InternalServerError.prototype);
        this.setUpStackTrace();
    }
}

export class ServiceUnavailablerError extends HttpError {
    constructor(message: string, code: number, statusCode: number) {
        super(message, code, statusCode);
        Object.setPrototypeOf(this, ServiceUnavailablerError.prototype);
        this.setUpStackTrace();
    }
}

export class RateLimitExceededError extends HttpError {
    constructor(message: string, code: number, statusCode: number) {
        super(message, code, statusCode);
        Object.setPrototypeOf(this, RateLimitExceededError.prototype);
        this.setUpStackTrace();
    }
}

export class UnknownError extends HttpError {
    constructor(message: string, code: number, statusCode: number) {
        super(message, code, statusCode);
        Object.setPrototypeOf(this, UnknownError.prototype);
        this.setUpStackTrace();
    }
}

export class ApiInputError extends HttpError {
    public static ERROR_CODES = {
        inactiveRecipient: 406,
        invalidEmailRequest: 300
    };

    constructor(message: string, code: number, statusCode: number) {
        super(message, code, statusCode);
        Object.setPrototypeOf(this, ApiInputError.prototype);
        this.setUpStackTrace();
    }

    public static buildSpecificError(message: string, code: number, statusCode: number): ApiInputError {
        switch (code) {
            case this.ERROR_CODES.inactiveRecipient:
                return new InactiveRecipientsError(message, code, statusCode);
            case this.ERROR_CODES.invalidEmailRequest:
                return new InvalidEmailRequestError(message, code, statusCode);
            default:
                return new ApiInputError(message, code, statusCode);
        }
    }
}

export class InactiveRecipientsError extends ApiInputError {
    public static inactiveRecipientsPatterns = [
        /Found inactive addresses: (.+?)\.?$/m,
        /these inactive addresses: (.+?)\. Inactive/,
        /these inactive addresses: (.+?)\.?$/
    ]

    public recipients: string[];

    constructor(message: string, code: number, statusCode: number) {
        super(message, code, statusCode);
        Object.setPrototypeOf(this, InactiveRecipientsError.prototype);
        this.setUpStackTrace();
        this.recipients = InactiveRecipientsError.parseInactiveRecipients(message);
    }

    public static parseInactiveRecipients(message: string): string[] {
        let result: string[] = [];

        this.inactiveRecipientsPatterns.some(pattern => {
            const regexResult = message.match(pattern)
            if (regexResult !== null) {
                result = regexResult[1].split(', ')
                return result;
            }
            else {
                result = []
            }
        })

        return result;
    }
}

export class InvalidEmailRequestError extends ApiInputError {
    constructor(message: string, code: number, statusCode: number) {
        super(message, code, statusCode);
        Object.setPrototypeOf(this, InvalidEmailRequestError.prototype);
        this.setUpStackTrace();
    }
}


text:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import app from '../reducers/app';
import AppContainer from "../containers/AppContainer";
import '../../css/global.css';

let store = createStore(
  app,
  applyMiddleware(thunk)
);

ReactDOM.render(
  <Provider store={store}>
    <AppContainer />
  </Provider>,
  document.getElementById('app')
);


text:
'use strict';

const remote = require('remote');
const app = remote.require('app');
const crypto = require('crypto');
const Datastore = require('nedb');

let accountsDB = new Datastore({
  filename: app.getPath('userData')+'/db/accounts',
  autoload: true
});
let postsDB = new Datastore({
  filename: app.getPath('userData')+'/db/posts',
  autoload: true
});
let companiesDB = new Datastore({
  filename: app.getPath('userData')+'/db/companies',
  autoload: true
});

angular.module('mirCtrls', [])

.controller('overviewCtrl', function($scope, $q, $uibModal) {
  let getData = () => {
    return $q((resolve, reject) => {
      accountsDB.find({}, (error, docs) => {
        resolve(docs);
      });
    });
  };

  getData().then((docs) => {
    $scope.accounts = docs;
  });

  $scope.newAccount = {
    name: undefined,
    init: undefined
  };

  $scope.currencies = ['EUR', 'GBP', 'USD', 'CHF'];

  $scope.valid = () => {
    return (
      !$scope.newAccount.name ||
      !$scope.newAccount.init ||
      !$scope.newAccount.currency ||
      !(!isNaN(parseFloat($scope.newAccount.init)) && isFinite($scope.newAccount.init))
    );
  };

  $scope.insert = () => {
    let acc = {
      name: $scope.newAccount.name,
      init: parseFloat($scope.newAccount.init),
      balance: parseFloat($scope.newAccount.init),
      currency: $scope.newAccount.currency,
      created_on: new Date(),
      thresholds: {
        critical: 0,
        warning: 500,
        ok: 1000
      },
      moves: []
    };
    accountsDB.insert(acc, (err, inserted) => {
      $scope.new = false;
      $scope.newAccount = {
        name: undefined,
        init: undefined,
        currency: undefined
      };
      getData().then((docs) => {
        $scope.accounts = docs;
      }, (err) => {
        throw err;
      });
    });
  };

  $scope.edit = (id) => {
    event.preventDefault();
    var modalInstance = $uibModal.open({
      animation: true,
      templateUrl: 'editModal.html',
      controller: 'editModalCtrl'
    });
    modalInstance.result.then((obj) => {
      accountsDB.update({_id: id}, {$set: {name: obj.newName}}, {}, (err, numReplaced) => {
        getData().then((docs) => {
          $scope.accounts = docs;
        }, (err) => {
          throw err;
        });
      });
    });
  };

  $scope.remove = (id) => {
    event.preventDefault();
    var modalInstance = $uibModal.open({
      animation: true,
      templateUrl: 'deleteModal.html',
      controller: 'deleteModalCtrl'
    });
    modalInstance.result.then(() => {
      accountsDB.remove({_id: id}, {multi: true} ,(err) => {
        getData().then((docs) => {
          $scope.accounts = docs;
        }, (err) => {
          throw err;
        });
      });
    });
  };
})

.controller('accountCtrl', function($scope, $q, $routeParams) {
  $scope.show = 'history';

  $scope.getData = () => {
    return $q((resolve, reject) => {
      let data = {};
      let proceed = _.after(3, () => {
        resolve(data);
      });

      accountsDB.findOne({_id: $routeParams.id}, (err, acc) => {
        data.acc = acc;
        proceed();
      });
      postsDB.find({}, (err, posts) => {
        data.posts = posts;
        proceed();
      });
      companiesDB.find({}, (err, comps) => {
        data.comps = comps;
        proceed();
      });
    });
  };

  $scope.getData().then((data) => {
    $scope.account   = data.acc;
    $scope.posts     = data.posts;
    $scope.companies = data.comps;
  }, (err) => {
    console.warn(err);
    throw err;
  });
})

.controller('accountHistoryCtrl', function($scope, $uibModal) {
  $scope.predicate = 'date';
  $scope.reverse = true;

  $scope.order = (predicate) => {
    $scope.predicate = predicate;
    $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : true;
  };

  $scope.results = [];
  $scope.refiner = false;
  var oldRefine = $scope.refine = {
    post: [],
    company: []
  };

  $scope.toggleRefiner = () => {
    $scope.refiner = !$scope.refiner;
    if($scope.refiner)
      $scope.refine = oldRefine;
    else {
      oldRefine = $scope.refine;
      $scope.refine = {
        post: [],
        company: []
      };
    }
  };
  $scope.refinePost = (name) => {
    let index;
    if((index = $scope.refine.post.indexOf(name)) > -1)
      $scope.refine.post.splice(index, 1);
    else
      $scope.refine.post.push(name);
  };
  $scope.refineComp = (name) => {
    let index;
    if((index = $scope.refine.company.indexOf(name)) > -1)
      $scope.refine.company.splice(index, 1);
    else
      $scope.refine.company.push(name);
  };

  $scope.sum = (items) => {
    let sum = 0;
    items.forEach((item) => {
      sum += item.amount;
    });
    return sum;
  };
  $scope.avg = (items) => {
    return (items.length === 0) ? 0 : Math.round(($scope.sum(items)/items.length) *100)/100;
  };
  $scope.min = (items) => {
    let min = 0;
    items.forEach((item) => {
      min = (!min || min > item.amount) ? item.amount : min;
    });
    return min;
  };
  $scope.max = (items) => {
    let max = 0;
    items.forEach((item) => {
      max = (!max || max < item.amount) ? item.amount : max;
    });
    return max;
  };

  $scope.newMove = {
    date  : undefined,
    amount: undefined
  };

  $scope.valid = () => {
    return (
      !$scope.newMove.date ||
      !$scope.newMove.amount ||
      !(!isNaN(parseFloat($scope.newMove.amount)) && isFinite($scope.newMove.amount))
    );
  };
  $scope.insert = () => {
    $scope.newMove.amount = parseFloat($scope.newMove.amount);
    $scope.newMove._id = crypto.randomBytes(8).toString('hex');
    let proceed = _.after(3, () => {
      $scope.$parent.getData().then((data) => {
        $scope.$parent.account   = data.acc;
        $scope.$parent.posts     = data.posts;
        $scope.$parent.companies = data.comps;
        $scope.newMove = {
          date  : undefined,
          amount: undefined
        };
      }, (err) => {
        console.warn(err);
        throw err;
      });
    });

    accountsDB.update({_id: $scope.$parent.account._id}, {$push: {moves: $scope.newMove}, $inc: {balance: $scope.newMove.amount}}, {}, () => {
      proceed();
    });

    if($scope.newMove.post) {
      postsDB.insert({_id: $scope.newMove.post}, () => {
        proceed();
      });
    } else {
      proceed();
    }

    if($scope.newMove.post) {
      companiesDB.insert({_id: $scope.newMove.company}, () => {
        proceed();
      });
    } else {
      proceed();
    }
  };
  $scope.remove = (id) => {
    var modalInstance = $uibModal.open({
      animation: true,
      templateUrl: 'deleteModal.html',
      controller: 'deleteModalCtrl'
    });
    modalInstance.result.then(() => {
      delete id.$$hashKey;
      accountsDB.update({_id: $scope.$parent.account._id}, {$inc: {balance: -id.amount}, $pull: {moves: id}}, {returnUpdatedDocs: true}, (err, num, up) => {
        $scope.$parent.account = up;
        $scope.$apply();
      });
    });
  };
})
.controller('accountConfigCtrl', function($scope) {
  $scope.updateTS = (valid) => {
    if(valid) {
      accountsDB.update({_id: $scope.$parent.account._id}, {$set: {thresholds: $scope.$parent.account.thresholds}});
    }
  };
})

.controller('editModalCtrl', function($scope, $uibModalInstance) {
  $scope.ok = () => {
    $uibModalInstance.close($scope.obj);
  };
  $scope.cancel = () => {
    $uibModalInstance.dismiss();
  };
})

.controller('deleteModalCtrl', function($scope, $uibModalInstance) {
  $scope.ok = () => {
    $uibModalInstance.close();
  };
  $scope.cancel = () => {
    $uibModalInstance.dismiss();
  };
})

.controller('topBarCtrl', function($scope, $route, $translate) {
  $scope.route = $route;
  $translate.onReady(() => {
    $scope.currentLocale = $translate.proposedLanguage();
  });
  $scope.selectLocale = (locale) => {
    $translate.use(locale);
    $scope.currentLocale = locale;
  };
})

.filter('refineFilter', function() {
  return function(items, refiner) {
    var filtered = [];
    angular.forEach(items, function(item) {
      if((refiner.post.length === 0 || refiner.post.indexOf(item.post) > -1) &&
         (refiner.company.length === 0 || refiner.company.indexOf(item.company) > -1) &&
         (!refiner.from || item.date >= refiner.from) &&
         (!refiner.to || item.date <= refiner.to)) {
        filtered.push(item);
      }
    });
    return filtered;
  };
});


text:
NS_ASSUME_NONNULL_BEGIN

@interface COSLayout : NSObject

- (instancetype)initWithView:(COSView *)view;
+ (instancetype)layoutWithView:(COSView *)view;

- (void)addRule:(NSString *)format, ...;
- (void)addRule:(NSString *)format args:(va_list)args;
- (void)addRule:(NSString *)format arguments:(nullable NSArray *)arguments;

@end

@interface COSView (COSLayout)

@property (nonatomic, strong, readonly) COSLayout *cosLayout;

@end

@protocol COSCGFloatProtocol

- (CGFloat)cosCGFloatValue;

@end

NS_ASSUME_NONNULL_END


text:
module EmberValidationsRailsJa
  VERSION = "0.0.2"
end


text:
#ifndef DEBUG_H
#define DEBUG_H

#include <stdarg.h>
#include <app/Message.h>
#include <support/List.h>
#include <support/String.h>
#include <storage/File.h>
#include <interface/Rect.h>
#include <support/Locker.h>
#include <stdio.h>

/*
	%d %i 	    Decimal signed integer.
    %o			Octal integer.
    %x %X		Hex integer.
    %u			Unsigned integer.
    %c			Character.
    %s			String. See below.
    %f			double
    %p			pointer.
    %b			bool
    %r			*Rect
*/

/**
 * @class Debug
 * @brief  Provide a tool for effective Debbunging ;-)
 */
enum debug_kind{D_INFO,D_DEBUG,D_ERROR};

class Debugger
{

public:
						Debugger(char *newGlobalName);
						~Debugger(void);
			void		Info(const char* group,const char *format, ...) const;
			void		Debug(const char* group,const char *format, ...) const;
			void		Error(const char* group,const char *format, ...) const;
			BList*		GetGroupList(void);
			void		EnableAllGroups(void){disabledGroups->MakeEmpty();allDisabled=false;};
			void		EnableGroup(char *group);
			void		DisableGroup(char *group);
			void		DisableAllGroups(void){allDisabled=true;};
			BMessage*	GetErrors(char *group);
			BMessage* 	GetDebugs(char *group);
			BMessage*	GetInfos(char *group);
			BMessage*	GetMessages(char *group);
			void		SetTerminalOutput(bool on){terminalOutput=on;};
			void		SetFile(BFile *output){file=output;};

protected:
private:
			BList*		disabledGroups;
			BMessage*	allMessages;
			bool		terminalOutput;
			bool		allDisabled;
			BFile		*file;
			char		*globalName;
			BLocker		*locker;
};
#endif


text:
module.exports = function(grunt) {

  // configure the tasks
  grunt.initConfig({
//  Copy
    copy: {
      dist: { cwd: 'font', src: [ '**' ], dest: 'dist/font', expand: true },
    },

//  Sass
    sass: {                              // Task
      expanded: {                            // Target
        options: {                       // Target options
          outputStyle: 'expanded',
          sourcemap: false,
        },
        files: {
          'dist/css/materialize.css': 'sass/materialize.scss',
        }
      },

      min: {
        options: {
          outputStyle: 'compressed',
          sourcemap: false
        },
        files: {
          'dist/css/materialize.min.css': 'sass/materialize.scss',
        }
      },

      // Compile ghpages css
      gh: {
        options: {
          style: 'compressed',
          sourcemap: false
        },
        files: {
          'css/ghpages-materialize.css': 'sass/ghpages-materialize.scss',
        }
      },

      // Compile ghpages css
      bin: {
        options: {
          style: 'expanded',
          sourcemap: false
        },
        files: {
          'bin/materialize.css': 'sass/materialize.scss',
        }
      }
    },

//  Concat
    concat: {
      options: {
        separator: ';'
      },
      dist: {
        // the files to concatenate
        src: [
              "js/jquery.easing.1.3.js",
              "js/animation.js",
              "js/velocity.min.js",
              "js/hammer.min.js",
              "js/jquery.hammer.js",
              "js/global.js",
              "js/collapsible.js",
              "js/dropdown.js",
              "js/leanModal.js",
              "js/materialbox.js",
              "js/parallax.js",
              "js/tabs.js",
              "js/tooltip.js",
              "js/waves.js",
              "js/toasts.js",
              "js/sideNav.js",
              "js/scrollspy.js",
              "js/forms.js",
              "js/slider.js",
              "js/cards.js",
              "js/pushpin.js",
              "js/buttons.js",
              "js/transitions.js",
              "js/scrollFire.js",
              "js/date_picker/picker.js",
              "js/date_picker/picker.date.js",
              "js/character_counter.js",
             ],
        // the location of the resulting JS file
        dest: 'dist/js/materialize.js'
      },
      temp: {
        // the files to concatenate
        src: [
              "js/jquery.easing.1.3.js",
              "js/animation.js",
              "js/velocity.min.js",
              "js/hammer.min.js",
              "js/jquery.hammer.js",
              "js/global.js",
              "js/collapsible.js",
              "js/dropdown.js",
              "js/leanModal.js",
              "js/materialbox.js",
              "js/parallax.js",
              "js/tabs.js",
              "js/tooltip.js",
              "js/waves.js",
              "js/toasts.js",
              "js/sideNav.js",
              "js/scrollspy.js",
              "js/forms.js",
              "js/slider.js",
              "js/cards.js",
              "js/pushpin.js",
              "js/buttons.js",
              "js/transitions.js",
              "js/scrollFire.js",
              "js/date_picker/picker.js",
              "js/date_picker/picker.date.js",
              "js/character_counter.js",
             ],
        // the location of the resulting JS file
        dest: 'temp/js/materialize.js'
      },
    },

//  Uglify
    uglify: {
      options: {
        // Use these options when debugging
        // mangle: false,
        // compress: false,
        // beautify: true

      },
      dist: {
        files: {
          'dist/js/materialize.min.js': ['dist/js/materialize.js']
        }
      },
      bin: {
        files: {
          'bin/materialize.js': ['temp/js/materialize.js']
        }
      }
    },

//  Compress
    compress: {
      main: {
        options: {
          archive: 'bin/materialize.zip',
          level: 6
        },
        files:[
          { expand: true, cwd: 'dist/', src: ['**/*'], dest: 'materialize/'},
          { expand: true, cwd: './', src: ['LICENSE', 'README.md'], dest: 'materialize/'},
        ]
      },

      src: {
        options: {
          archive: 'bin/materialize-src.zip',
          level: 6
        },
        files:[
          {expand: true, cwd: 'font/', src: ['**/*'], dest: 'materialize-src/font/'},
          {expand: true, cwd: 'sass/', src: ['materialize.scss'], dest: 'materialize-src/sass/'},
          {expand: true, cwd: 'sass/', src: ['components/**/*'], dest: 'materialize-src/sass/'},
          {expand: true, cwd: 'js/', src: [
              "jquery.easing.1.3.js",
              "animation.js",
              "velocity.min.js",
              "hammer.min.js",
              "jquery.hammer.js",
              "global.js",
              "collapsible.js",
              "dropdown.js",
              "leanModal.js",
              "materialbox.js",
              "parallax.js",
              "tabs.js",
              "tooltip.js",
              "waves.js",
              "toasts.js",
              "sideNav.js",
              "scrollspy.js",
              "forms.js",
              "slider.js",
              "cards.js",
              "pushpin.js",
              "buttons.js",
              "transitions.js",
              "scrollFire.js",
              "date_picker/picker.js",
              "date_picker/picker.date.js",
              "character_counter.js",
             ], dest: 'materialize-src/js/'},
        {expand: true, cwd: 'dist/js/', src: ['**/*'], dest: 'materialize-src/js/bin/'},
        {expand: true, cwd: './', src: ['LICENSE', 'README.md'], dest: 'materialize-src/'}

        ]
      },

      starter_template: {
        options: {
          archive: 'templates/starter-template.zip',
          level: 6
        },
        files:[
          { expand: true, cwd: 'dist/', src: ['**/*'], dest: 'starter-template/'},
          { expand: true, cwd: 'templates/starter-template/', src: ['index.html', 'LICENSE'], dest: 'starter-template/'},
          { expand: true, cwd: 'templates/starter-template/css', src: ['style.css'], dest: 'starter-template/css'},
          { expand: true, cwd: 'templates/starter-template/js', src: ['init.js'], dest: 'starter-template/js'}

        ]
      },

      parallax_template: {
        options: {
          archive: 'templates/parallax-template.zip',
          level: 6
        },
        files:[
          { expand: true, cwd: 'dist/', src: ['**/*'], dest: 'parallax-template/'},
          { expand: true, cwd: 'templates/parallax-template/', src: ['index.html', 'LICENSE', 'background1.jpg', 'background2.jpg', 'background3.jpg'], dest: 'parallax-template/'},
          { expand: true, cwd: 'templates/parallax-template/css', src: ['style.css'], dest: 'parallax-template/css'},
          { expand: true, cwd: 'templates/parallax-template/js', src: ['init.js'], dest: 'parallax-template/js'}

        ]
      }

    },

//  Clean
   clean: {
     temp: {
       src: [ 'temp/' ]
     },
   },

//  Jade
    jade: {
      compile: {
        options: {
          pretty: true,
          data: {
            debug: false
          }
        },
        files: {
          "index.html": "jade/index.jade",
          "icons.html": "jade/icons.jade",
          "about.html": "jade/about.jade",
          "sass.html": "jade/sass.jade",
          "getting-started.html": "jade/getting-started.jade",
          "mobile.html": "jade/mobile.jade",
          "showcase.html": "jade/showcase.jade",
          "parallax.html": "jade/parallax.jade",
          "parallax-demo.html": "jade/parallax-demo.jade",
          "typography.html": "jade/typography.jade",
          "color.html": "jade/color.jade",
          "shadow.html": "jade/shadow.jade",
          "grid.html": "jade/grid.jade",
          "media-css.html": "jade/media-css.jade",
          "table.html": "jade/table.jade",
          "helpers.html": "jade/helpers.jade",
          "forms.html": "jade/forms.jade",
          "buttons.html": "jade/buttons.jade",
          "navbar.html": "jade/navbar.jade",
          "cards.html": "jade/cards.jade",
          "preloader.html": "jade/preloader.jade",
          "collections.html": "jade/collections.jade",
          "badges.html": "jade/badges.jade",
          "footer.html": "jade/footer.jade",
          "dialogs.html": "jade/dialogs.jade",
          "modals.html": "jade/modals.jade",
          "dropdown.html": "jade/dropdown.jade",
          "tabs.html": "jade/tabs.jade",
          "side-nav.html": "jade/sideNav.jade",
          "pushpin.html": "jade/pushpin.jade",
          "waves.html": "jade/waves.jade",
          "media.html": "jade/media.jade",
          "collapsible.html": "jade/collapsible.jade",
          "scrollfire.html": "jade/scrollFire.jade",
          "scrollspy.html": "jade/scrollspy.jade",
          "transitions.html": "jade/transitions.jade",
          "fullscreen-slider-demo.html": "jade/fullscreen-slider-demo.jade",
          "pagination.html": "jade/pagination.jade"

        }
      }
    },

//  Watch Files
    watch: {
      jade: {
        files: ['jade/**/*'],
        tasks: ['jade_compile'],
        options: {
          interrupt: false,
          spawn: false,
        },
      },

      js: {
        files: [ "js/**/*", "!js/init.js"],
        tasks: ['js_compile'],
        options: {
          interrupt: false,
          spawn: false,
        },
      },

      sass: {
        files: ['sass/**/*'],
        tasks: ['sass_compile'],
        options: {
          interrupt: false,
          spawn: false,
        },
      }
    },

//  Concurrent
    concurrent: {
      options: {
        logConcurrentOutput: true
      },
      monitor: {
        tasks: ["watch:jade", "watch:js", "watch:sass", "notify:watching", 'connect:server', 'notify:server']
      },
    },

//  Notifications
    notify: {
      watching: {
        options: {
          enabled: true,
          message: 'Watching Files!',
          title: "Materialize", // defaults to the name in package.json, or will use project directory's name
          success: true, // whether successful grunt executions should be notified automatically
          duration: 1 // the duration of notification in seconds, for `notify-send only
        }
      },

      sass_compile: {
        options: {
          enabled: true,
          message: 'Sass Compiled!',
          title: "Materialize",
          success: true,
          duration: 1
        }
      },

      js_compile: {
        options: {
          enabled: true,
          message: 'JS Compiled!',
          title: "Materialize",
          success: true,
          duration: 1
        }
      },

      jade_compile: {
        options: {
          enabled: true,
          message: 'Jade Compiled!',
          title: "Materialize",
          success: true,
          duration: 1
        }
      },

      server: {
        options: {
          enabled: true,
          message: 'Server Running!',
          title: "Materialize",
          success: true,
          duration: 1
        }
      }
    },

//  Server
    connect: {
      server: {
        options: {
          port: 8000,
          useAvailablePort: true,
          hostname: '*',
          keepalive: true
        }
      }
    },

    // Text Replace
    replace: {
      version: { // Does not edit README.md
        src: [
          'bower.json',
          'package.json',
          'package.js',
          'jade/**/*.html'
        ],
        overwrite: true,
        replacements: [{
          from: grunt.option( "oldver" ),
          to: grunt.option( "newver" )
        }]
      },
      readme: { // Changes README.md
        src: [
          'README.md'
        ],
        overwrite: true,
        replacements: [{
          from: 'Current Version : v'+grunt.option( "oldver" ),
          to: 'Current Version : v'+grunt.option( "newver" )
        }]
      },
    },

    // Create Version Header for files
    usebanner: {
        release: {
          options: {
            position: 'top',
            banner: "/*!\n * Materialize v"+ grunt.option( "newver" ) +" (http://materializecss.com)\n * Copyright 2014-2015 Materialize\n * MIT License (https://raw.githubusercontent.com/Dogfalo/materialize/master/LICENSE)\n */",
            linebreak: true
          },
          files: {
            src: [ 'dist/css/*.css', 'dist/js/*.js']
          }
        }
      },

      // Rename files
      rename: {
          rename_src: {
              src: 'bin/materialize-src'+'.zip',
              dest: 'bin/materialize-src-v'+grunt.option( "newver" )+'.zip',
              options: {
                ignore: true
              }
          },
          rename_compiled: {
              src: 'bin/materialize'+'.zip',
              dest: 'bin/materialize-v'+grunt.option( "newver" )+'.zip',
              options: {
                ignore: true
              }
          },
      },

      // Removes console logs
      removelogging: {
          source: {
            src: ["js/**/*.js", "!js/velocity.min.js"],
            options: {
              // see below for options. this is optional.
            }
          }
        }

  });

  // load the tasks
//  grunt.loadNpmTasks('grunt-gitinfo');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-sass');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-compress');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jade');
  grunt.loadNpmTasks('grunt-concurrent');
  grunt.loadNpmTasks('grunt-notify');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-text-replace');
  grunt.loadNpmTasks('grunt-banner');
  grunt.loadNpmTasks('grunt-rename');
  grunt.loadNpmTasks("grunt-remove-logging");
  // define the tasks
  grunt.registerTask(
    'release',[
      'lint',
      'copy',
      'sass:expanded',
      'sass:min',
      'concat:dist',
      'uglify:dist',
      'usebanner:release',
      'compress:main',
      'compress:src',
      'compress:starter_template',
      'compress:parallax_template',
      'replace:version',
      'replace:readme',
      'rename:rename_src',
      'rename:rename_compiled'
    ]
  );

  grunt.registerTask('jade_compile', ['jade', 'notify:jade_compile']);
  grunt.registerTask('js_compile', ['concat:temp', 'uglify:bin', 'notify:js_compile', 'clean:temp']);
  grunt.registerTask('sass_compile', ['sass:gh', 'sass:bin', 'notify:sass_compile']);
  grunt.registerTask('start_server', ['connect:server', 'notify:server']);
  grunt.registerTask('lint', ['removelogging:source']);
  grunt.registerTask("monitor", ["concurrent:monitor"]);
};


text:
"use strict";

describe("inherit", function () {

  var foo;

  var TestBed = inherit(oak.Statable, function () {

    this.started = false;

    this.states = {
      onFart: function () {
      },
      offStartup: function () {
      },
      onStartup: function () {
        this.started = true;
      }
    };

  });

  beforeEach(function () {
    foo = new TestBed();
  });

  it("Statable exists", function () {
    expect(oak.Statable).toBeDefined();
  });

  describe("inherit evented", function () {
    it("calls init", function () {
      expect(foo instanceof oak.Evented).toBe(true);
    });
  });

  describe("statable calls", function () {
    it("sets states", function () {
      foo.setState("startup");
      expect(foo.currentState).toBe("startup");
      foo.setState("fart");
    });

    it("calls states", function () {
      foo.setState("startup");
      expect(foo.started).toBe(true);
    });

  });

});


text:
BEGIN;
DELETE FROM t5;
INSERT INTO t8 VALUES('hello world');


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
F. W. H. A. von Humboldt et al. , Nov. gen. sp. 4:154[folio]. 1818; 4:197[quarto]. 1820

#### Original name
null

### Remarks
null


text:
<?php

use Phalcon\Di;
use Phalcon\Logger\Adapter\Stream;

require '/../app/bootstrap_cli.php';

function clear_cache() {
    $log = new Stream('php://stdout');
    $log->info('Start');
    $iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator(BASE_DIR.'/app/cache/'), RecursiveIteratorIterator::CHILD_FIRST
    );
    $excludeDirsNames = [];
    $excludeFileNames = ['.gitignore'];
    foreach($iterator as $entry) {
        if ($entry->isDir()) {
            if (!in_array($entry->getBasename(), $excludeDirsNames)) {
                //echo 'DIR:'.$entry->getPathname().PHP_EOL;
            }
        } elseif (!in_array($entry->getFileName(), $excludeFileNames)) {
            $log->info('Delete:'.$entry->getFileName());
            unlink($entry->getPathname());
        }
    }
    $log->info('End');
}

clear_cache();


text:
title: I've Built a Digital Organ and This Is What I Learned
date: '2022-03-15T10:55:16.599Z'
author: Ionică Bizău
image: https://i.imgur.com/Ssl3H0c.jpg
language: en
tags:
  - music
  - organ
  - building
---

For quite a bit of time, I have been looking for a solution to practice the organ at home. A digital piano may simulate a real piano quite well, but for an organ, the pedalboard is a real need. :musical_keyboard:

![Organ](https://i.imgur.com/zPUEEer.jpeg)

I concluded that _**building**_ a digital organ with a pedalboard would be way more exciting than _buying_ one (which would be very expensive too!).

So, here's the story! :hammer_and_wrench:

## Building the Pedalboard, Together With My Dad

My dad is a carpenter. Lucky me! When I was a kid, building my stuff in my dad's workshop was a lot of fun!

I was expecting that for building a pedalboard, we would have to join our forces together: my father would take care of the mechanical part (the pedalboard wooden structure, pedals, and so on), and me of the digital part (sensors, cables, connections, etc). And that's what we did!

However, connecting the mechanical part with the computer was something I was not sure about. Initially, I was thinking to use a Raspberry Pi, then thought that maybe an Arduino would do the job too. But I was expecting something like this would exist already.

When traveling in Brazil I met [Leandro Cardoso](https://www.instagram.com/orgaosleandroharcardoso/) — an amazing organ builder and organist who suggested I could build a MIDI pedalboard using electrical components built by [MIDIHardware.com](https://midi-hardware.com) — a Polish company building such electronic modules for musical instruments. That was the missing piece in the puzzle! :four_leaf_clover:

I impatiently waited for the package from Poland and eventually received it! I carefully unpacked and studied the instructions. :page_with_curl:

![](https://i.imgur.com/bcDT55p.png)

Each wooden pedal would have a sensor and a magnet, which — when in the proximity of the sensor (pedal pressed) — would trigger the signal to the main chip, and from there it would be converted into a MIDI signal, which goes to the computer via a USB cable. After lots of measurements Dad and I have done together, my dad built the pedals and the case where they would be placed.

![](https://i.imgur.com/LYTRJYo.jpg)

We went together to a small local hardware store to buy 32 springs — one for each pedal. They were quite astonished when realizing we really wanted to buy so many springs (that was kinda their entire stock of springs): _But Mr. Bizău, what are you doing with so many springs?!_ — asked one of the sellers. He was amazed.

Back home, we attached the spring to a test pedal, calibrated it, and then repeated the steps for all the pedals. I attached a magnet to each of the pedals.

Mounting the pedals in place was the most tedious part of the process and when it was done we were both tired. While my dad took a break outside, I took the electronics I got from Poland, placed them in the right place, connected the wires, brought my computer, and set up a _Cathedral Organ_ in Logic Pro X (with a lot of reverb!), and pressed one of the pedals! A majestical sound came from my MacBook's speakers. **It was working! The pedalboard was working!** That feeling of joy and accomplishment could not be explained! I called my dad and mom to see it! They were so happy! We did it! :tada:

![](https://i.imgur.com/eyapNdQ.jpg)

We arranged the pedalboard together with my digital piano and did a quick test! It was feeling like an organ indeed!

I could not wait to share this with my teacher and a couple of my friends! :heart:

Then, of course, it was time to **paint and polish it**! :art:

![](https://i.imgur.com/M0fZcDs.jpg)

### Prototyping the Organ Case

First I prototyped the organ case on paper, following the measurements I have taken of the two-manual organ from the University, but then realized it would be better to create a SketchUp project and do a 3D simulation to make sure everything is going to fit. :triangular_ruler:

![](https://i.imgur.com/JhzJf4Z.jpg)

### Ordering the Wooden Pieces

My parents went on holiday, and I thought: _well, I should be able to do this alone now!_ The pedalboard was the most complex part.

I went to a local furniture store and presented them with my project with all my measurements. They did a great job delivering the particle board pieces I indicated. :page_facing_up:

In the meantime, I got the tools and machines necessary for this: a driller, a vertical cutting tool, and a smoother machine. I brought all the components and tools I needed to my home's garage. :construction_worker_man:

### Assembling the Organ and the Bench

I was calling my dad to tell me what are the best practices when working with melamine as this was my first project of this kind. He was like: _maybe it would be better to wait until I come back so we can do that together, but if you want to do it by yourself this is how you can do it_. :rocket:

For the manuals (keyboards) I used two [Nektar MIDI Impact GX61](https://kytary.ro/nektar-technology-impact-gx61/HN210449/) controllers which turned out to be quite good and give that organ feeling.

Technically, I ended with three MIDI controllers (the MIDI pedalboard + two Nektar keyboards). :musical_keyboard:

Finally, I built a platform with wheels on which I placed the organ so that I could move it in front of the [office desk](https://birou-reglabil.ro/birouri-reglabile-pe-inaltime/) (where the speakers are) during the recording sessions.

![](https://i.imgur.com/SQIm6M2.jpg)

## GrandOrgue vs Logic Pro X

For creating the sound on the computer, I first experimented with Haupwerk which turned out to be quite buggy for some reason. However, I had a good experience with GrandOrgue which is also open-source. There are quite a few organ sets for GrandOrgue with which we can simulate the sound of a particular church/cathedral in the world. :speaker:

Using the MIDI connections I experimented with Omnisphere 2 on Logic Pro X which turned out to be amazing. :sparkles:

## Inscriptions

![](https://i.imgur.com/R4YRQEE.jpeg)

Finally, it came the moment to add the inscriptions on the organ.

On the top side, I chose the very known quote of Jesus from Luke 13: _**SI POTES CREDERE, OMNIA POSSIBILIA SUNT CREDENTI**_ (_Everything is possible for one who believes_) along with the _**SOLI DEO GLORIA**_ seal which I use in several places. It is a reminder that the music played on this organ should glorify God — He who watches over us and hears our prayers (cf. Psalm 34:15, Proverbs 15:3). :pray:

![](https://i.imgur.com/flOp8Kx.jpeg)

### Wrapping Up

It was such a great experience to build this musical instrument! I learned how to measure, cut, and assemble melamine boards. Also, I learned how to build simple 3D projects in SketchUp. :hammer:

What's next? Improving the way I change the registers, adding expression and crescendo pedals... and, who knows, in the future maybe adding real organ pipes! :notes:

<iframe width="100%" height="315" src="https://www.youtube.com/embed/YJbO9qliMaQ" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

![](https://i.imgur.com/Ssl3H0c.jpg)

<script>
    window.BloggifyPage.available_languages = { en: 43, ro: 44 }
    window.checkLanguage()
</script>


text:
import java.io.*;
import java.util.*;

class PartitionLabels
{
    public static void main(String[] args)
    {
        System.out.println("=== Partition Labels ===");
        Solution solution = new Solution();
        String S = "ababcbacadefegdehijhklij";
        System.out.println("S = "+S);
        System.out.println("output = "+solution.partitionLabels(S));
    }
}

class Solution
{
    public List<Integer> partitionLabels(String S) {
        List<Integer> list = new ArrayList<>();
        Map<Character, Integer> leftMap = new HashMap<>();
        Map<Character, Integer> rightMap = new HashMap<>();
        for (int i = 0; i < S.length(); i++) {
            char ch = S.charAt(i);
            if (!leftMap.containsKey(ch)) {
                leftMap.put(ch, i);
            }
        }
        for (int i = S.length()-1; i >= 0; i--) {
            char ch = S.charAt(i);
            if (!rightMap.containsKey(ch)) {
                rightMap.put(ch, i);
            }
        }

        int prevRight = -1;
        int count = 0;
        for (int i = 0; i < S.length(); i++) {
            char ch = S.charAt(i);
            int currLeft = leftMap.get(ch);
            int currRight = rightMap.get(ch);

            if (currLeft == i && prevRight < i) {
                if (count > 0) { list.add(count); }
                count = 1;
            } else {
                count++;
            }

            prevRight = (prevRight>=currRight)?prevRight:currRight;
        }

        if (count > 0) { list.add(count); }

        return list;
    }
}


text:
drest-client
============

Client tool to allow quick / simple consumption of a [drest](https://github.com/leedavis81/drest) API service.

| Tests | Releases | Downloads |
| ----- | -------- | ------- |
[![Build Status](https://travis-ci.org/leedavis81/drest-client.png?branch=master)](https://travis-ci.org/leedavis81/drest-client) [![Coverage Status](https://coveralls.io/repos/leedavis81/drest-client/badge.png?branch=master)](https://coveralls.io/r/leedavis81/drest-client?branch=master) | [![Latest Stable Version](https://poser.pugx.org/leedavis81/drest-client/v/stable.png)](https://packagist.org/packages/leedavis81/drest-client) [![Latest Unstable Version](https://poser.pugx.org/leedavis81/drest-client/v/unstable.png)](https://packagist.org/packages/leedavis81/drest-client) | [![Total Downloads](https://poser.pugx.org/leedavis81/drest-client/downloads.png)](https://packagist.org/packages/leedavis81/drest-client)|

####Installation

```
composer require leedavis81/drest-client

// or add the following directly to your composer.json file
require: {
    "leedavis81/drest-client": "dev-master"
}
```


text:
package com.yunikov.algorithms;

@FunctionalInterface
public interface AlgorithmAssert {
    void assertAlgorithm();
}


text:
/**
 * Soap12AddTestRpcBindingImpl.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis WSDL2Java emitter.
 */

package test.wsdl.soap12.additional;

public class Soap12AddTestRpcBindingImpl implements test.wsdl.soap12.additional.Soap12AddTestPortTypeRpc{
    public void echoVoid() throws java.rmi.RemoteException {
    }

    public test.wsdl.soap12.additional.xsd.SOAPStruct echoSimpleTypesAsStruct(java.lang.String inputString, int inputInteger, float inputFloat) throws java.rmi.RemoteException {
        return null;
    }

    // getTime is a notification style operation and is unsupported.

    public java.lang.String echoString(java.lang.String inputString) throws java.rmi.RemoteException {
        return inputString;
    }

    public test.wsdl.soap12.additional.xsd.SOAPStructTypes echoSimpleTypesAsStructOfSchemaTypes(java.lang.Object input1, java.lang.Object input2, java.lang.Object input3, java.lang.Object input4) throws java.rmi.RemoteException {
        return null;
    }

    public int echoInteger(int inputInteger) throws java.rmi.RemoteException {
        return -3;
    }

}


text:
local ansicolors = require 'ansicolors'
local s = require 'say'
local pretty = require 'pl.pretty'

return function(options, busted)
  local handler = require 'busted.outputHandlers.base'(busted)

  local successDot =  ansicolors('%{green}●')
  local failureDot =  ansicolors('%{red}●')
  local errorDot =  ansicolors('%{magenta}●')
  local pendingDot = ansicolors('%{yellow}●')

  local pendingDescription = function(pending)
    local name = handler.getFullName(pending)

    local string = ansicolors('%{yellow}' .. s('output.pending')) .. ' → ' ..
      ansicolors('%{cyan}' .. pending.trace.short_src) .. ' @ ' ..
      ansicolors('%{cyan}' .. pending.trace.currentline)  ..
      '\n' .. ansicolors('%{bright}' .. name)

    return string
  end

  local failureDescription = function(failure, isError)
    local string = ansicolors('%{red}' .. s('output.failure')) .. ' → '

    if isError then
      string = ansicolors('%{magenta}' .. s('output.error'))

      if failure.message then
        string = string .. ' → ' ..  ansicolors('%{cyan}' .. failure.message) .. '\n'
      end
    else
      string = string ..
        ansicolors('%{cyan}' .. failure.trace.short_src) .. ' @ ' ..
        ansicolors('%{cyan}' .. failure.trace.currentline) .. '\n' ..
        ansicolors('%{bright}' .. handler.getFullName(failure)) .. '\n'

      if type(failure.message) == 'string' then
        string = string .. failure.message
      elseif failure.message == nil then
        string = string .. 'Nil error'
      else
        string = string .. pretty.write(failure.message)
      end
    end

    if options.verbose then
      string = string .. '\n' .. failure.trace.traceback
    end

    return string
  end

  local statusString = function()
    local successString = s('output.success_plural')
    local failureString = s('output.failure_plural')
    local pendingString = s('output.pending_plural')
    local errorString = s('output.error_plural')

    local ms = handler.getDuration()
    local successes = handler.successesCount
    local pendings = handler.pendingsCount
    local failures = handler.failuresCount
    local errors = handler.errorsCount

    if successes == 0 then
      successString = s('output.success_zero')
    elseif successes == 1 then
      successString = s('output.success_single')
    end

    if failures == 0 then
      failureString = s('output.failure_zero')
    elseif failures == 1 then
      failureString = s('output.failure_single')
    end

    if pendings == 0 then
      pendingString = s('output.pending_zero')
    elseif pendings == 1 then
      pendingString = s('output.pending_single')
    end

    if errors == 0 then
      errorString = s('output.error_zero')
    elseif errors == 1 then
      errorString = s('output.error_single')
    end

    local formattedTime = ('%.6f'):format(ms):gsub('([0-9])0+$', '%1')

    return ansicolors('%{green}' .. successes) .. ' ' .. successString .. ' / ' ..
      ansicolors('%{red}' .. failures) .. ' ' .. failureString .. ' / ' ..
      ansicolors('%{magenta}' .. errors) .. ' ' .. errorString .. ' / ' ..
      ansicolors('%{yellow}' .. pendings) .. ' ' .. pendingString .. ' : ' ..
      ansicolors('%{bright}' .. formattedTime) .. ' ' .. s('output.seconds')
  end

  handler.testEnd = function(element, parent, status, debug)
    if not options.deferPrint then
      local string = successDot

      if status == 'pending' then
        string = pendingDot
      elseif status == 'failure' then
        string = failureDot
      end

      io.write(string)
      io.flush()
    end

    return nil, true
  end

  handler.suiteEnd = function(name, parent)
    print('')
    print(statusString())

    for i, pending in pairs(handler.pendings) do
      print('')
      print(pendingDescription(pending))
    end

    for i, err in pairs(handler.failures) do
      print('')
      print(failureDescription(err))
    end

    for i, err in pairs(handler.errors) do
      print('')
      print(failureDescription(err, true))
    end

    return nil, true
  end

  handler.error = function(element, parent, message, debug)
    io.write(errorDot)
    io.flush()

    return nil, true
  end

  local s = busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending })
  busted.subscribe({ 'suite', 'end' }, handler.suiteEnd)
  busted.subscribe({ 'error', 'file' }, handler.error)
  busted.subscribe({ 'error', 'describe' }, handler.error)

  return handler
end


text:
__Author__: Andrew Huynh

__License__: MIT

![example-planet gif](docs/example-planet.gif)

### a little history

Back when I was a wee lad, around the years of 2008-2009, I wanted to
experiment/play around with WebGL, which at the time was a relatively new
piece of technology. This code stemmed from the initial attempt and,
unfortunately, due to time constraints I could not pursue the project any
further than what I have here.

The planet generation code is based off of an even older school project
intended to build a complex 3D scene in OpenGL. For kicks, you can check
out the class project page here: [CSE167 Final Projects][cse169] and a
small write-up I did afterwards here:
[CSE167 Final Project Results][cse169results]

### about this repo

This repository contains WebGL & C++ code that setups and generates a
"planet" model. This is accomplished using the well known
[Particle Deposition][pdepo] technique. If you want to dive directly into
how the planet is generated, check the `generate` function in the file
`planet.js`.

If you're curious about how to interact with WebGL at a low level rather
than save time and use a nice library like [Three.js][3js], check out the
`gl*.js` files for a fun time.

All code is MIT licensed, so go ahead and use it in your next great game or
3D visualization tool!

[3js]: http://threejs.org/
[cse169]: http://graphics.ucsd.edu/twiki/bin/view.pl/Classes/CSE167F09-FinalProjects "CSE 167 Final Projects"
[cse169results]: https://a5huynh.github.io/posts/2009/cse-167-final-project-results/
[pdepo]: https://web.archive.org/web/20160307062357/http://www.lighthouse3d.com/opengl/terrain/index.php3?particle "Particle Deposition"

### typescript updates (2017)

In the year 2017, I decided to revisit portions of the planet generation code and
complete some updates I've been meaning to do for several years. You can check out
the code under the [`src/typescript`](src/typescript) directory and if you're interested in reading
a walkthrough of my thoughts and explanations feel free to check out the following:

- [Planet Rendering Pt. 1][blog-post-1]
- [Planet Rendering Pt. 2][blog-post-2]

[blog-post-1]: https://a5huynh.github.io/posts/2017/tbt-planet-rendering/ "TBT: Planet Rendering"
[blog-post-2]: https://a5huynh.github.io/posts/2017/planet-rendering-pt-2/ "Planet Rendering Pt. 2"


text:
package org.jsapar;

import org.jsapar.compose.bean.BeanComposeConfig;
import org.jsapar.compose.bean.BeanFactory;
import org.jsapar.model.Cell;
import org.jsapar.model.Line;
import org.jsapar.schema.CsvSchema;
import org.jsapar.schema.CsvSchemaLine;
import org.jsapar.text.TextParseConfig;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;

public class Text2BeanConverterTest {

    @Test
    public void convert() throws IOException {
        CsvSchema schema = makeTestCsvSchema();

        String input = "John;Doe";
        Text2BeanConverter<TstPerson> converter = new Text2BeanConverter<>(schema);
        try(Reader reader=new StringReader(input)){
            long count = converter.convertForEach(reader, b -> {
                assertEquals("John", b.getFirstName());
                assertEquals("Doe", b.getLastName());
            });
            assertEquals(1, count);
        }
    }

    protected CsvSchema makeTestCsvSchema() {
        return CsvSchema.builder()
                .withLine(CsvSchemaLine.builder("org.jsapar.TstPerson")
                        .withCells("firstName", "lastName")
                        .build())
                .build();
    }

    @Test
    public void convert_CustomBeanFactory() throws IOException {
        CsvSchema schema = makeTestCsvSchema();

        String input = "John;Doe";
        Text2BeanConverter<TstPerson> converter = new Text2BeanConverter<>(schema);
        converter.setBeanFactory(new BeanFactory<TstPerson>() {
            @Override
            public TstPerson createBean(Line line) {
                return new TstPerson();
            }

            @Override
            public void assignCellToBean(String lineType, TstPerson bean, Cell cell) {
                // Just convert to upper case and assign.
                switch(cell.getName()){
                    case "firstName":
                        bean.setFirstName(cell.getStringValue().toUpperCase());
                        break;
                    case "lastName":
                        bean.setLastName(cell.getStringValue().toUpperCase());
                        break;
                }
            }
        });
        try(Reader reader=new StringReader(input)){
            long count = converter.convertForEach(reader, bean -> {
                assertEquals("JOHN", bean.getFirstName());
                assertEquals("DOE", bean.getLastName());
            });
            assertEquals(1, count);
        }
    }

    @Test
    public void setGetComposeConfig() {
        CsvSchema schema = CsvSchema.builder().build();
        Text2BeanConverter<TstPerson> converter = new Text2BeanConverter<>(schema);
        BeanComposeConfig composeConfig = new BeanComposeConfig();
        converter.setComposeConfig(composeConfig);
        assertSame(composeConfig, converter.getComposeConfig());
    }

    @Test
    public void setGetParseConfig() {
        CsvSchema schema = CsvSchema.builder().build();
        Text2BeanConverter<TstPerson> converter = new Text2BeanConverter<>(schema);
        TextParseConfig config = new TextParseConfig();
        converter.setParseConfig(config);
        assertSame(config, converter.getParseConfig());
    }
}