text:
from django import forms
from django.utils.translation import ugettext as _
from django.core.validators import validate_email
from django.contrib.auth.forms import AuthenticationForm

GENDER_CHOICES = (
    ('Male', 'Male'),
    ('Female', 'Female'),
)
MONTH_CHOICES = (
    (1, 'January'),
    (2, 'February'),
    (3, 'March'),
    (4, 'April'),
    (5, 'May'),
    (6, 'June'),
    (7, 'July'),
    (8, 'August'),
    (9, 'September'),
    (10, 'October'),
    (11, 'November'),
    (12, 'December'),
)
class CommentForm(forms.Form):
    author = forms.CharField()
    comment = forms.CharField()
    parent_id = forms.CharField(widget=forms.HiddenInput())

class AuthenticationFormPlaceholder(AuthenticationForm):
    username = forms.CharField(
        max_length=30,
        widget=forms.TextInput(attrs={
            'id': 'id_username_auth',
            'placeholder': _('Username or Email'),
            'class': 'input-medium',
            'required': '',
        })
    )
    password = forms.CharField(
        widget=forms.PasswordInput(attrs={
            'id': 'id_password_auth',
            'placeholder': _('Password'),
            'class': 'input-medium required',
            'required': '',
        })
    )

class EditProfileForm(forms.Form):
    month = forms.ChoiceField(
        choices = MONTH_CHOICES
    )

    day = forms.CharField(
        label = _('Day'),
        min_length = 1,
        max_length = 2,
        widget = forms.TextInput(attrs={
            'placeholder':_('Day'),
            'class': 'span2',

        })
    )

    year = forms.CharField(
        label = _('Year'),
        min_length = 4,
        max_length = 4,
        widget = forms.TextInput(attrs={
            'placeholder':_('Year'),
            'class': 'span2',
        })
    )

    gender = forms.ChoiceField(
        choices = GENDER_CHOICES,
    )

    # gender = forms.CharField(label=_('Gender'))
    mobile = forms.CharField(
        label = _('Mobile'),
        min_length = 7,
        max_length = 20,
        widget = forms.TextInput(attrs={
            'placeholder':_('Mobile'),
        })
    )

    website = forms.CharField(
        label = _('Website'),
        min_length = 4,
        max_length = 100,
        widget = forms.TextInput(attrs={
            'placeholder':_('Website'),
        })
    )

class ChangePasswordForm(forms.Form):
    password = forms.CharField(
        label = _('Password'),
        min_length = 3,
        max_length = 30,
        widget = forms.PasswordInput(attrs={
            'placeholder':_('Password'),
        })
    )

    new_password = forms.CharField(
        label = _('New password'),
        min_length = 6,
        max_length = 30,
        widget = forms.PasswordInput(attrs={
            'placeholder':_('New password'),
        })
    )

    confirm_new_password = forms.CharField( # Why?!
        label = _('Re-type new password'),
        min_length = 6,
        max_length = 30,
        widget = forms.PasswordInput(attrs={
            'placeholder':_('Re-type new password'),
        })
    )

    def clean_confirm_new_password(self):
        confirm_new_password = self.cleaned_data['confirm_new_password']
        if confirm_new_password != self.cleaned_data['new_password']:
            raise forms.ValidationError(_('New password and Re-type does not match'))
        return confirm_new_password

class RegisterForm(forms.Form):
    error_messages = {
        'duplicate_username': _("A user with that username already exists."),
        'password_mismatch': _("The two password fields didn't match."),
    }
    # username = forms.RegexField(label=_("Username"), max_length=30,
    #     regex=r'^[\w.@+-]+$',
    #     help_text=_("Required. 30 characters or fewer. Letters, digits and "
    #                   "@/./+/-/_ only."),
    #     error_messages={
    #         'invalid': _("This value may contain only letters, numbers and "
    #                      "@/./+/-/_ characters.")},
    #     widget=forms.TextInput(attrs={
    #         'placeholder': _('Username'),
    #         'class': 'span12 required',
    #         'required': '',
    #     }))

    first_name = forms.CharField(
        label = _('First Name'),
        min_length = 2,
        max_length = 30,
        widget = forms.TextInput(attrs={
            'placeholder':_('First Name'),
            'class': 'span6 required',
            'required': '',
        })
    )

    last_name = forms.CharField(
        label = _('Last Name'),
        min_length = 2,
        max_length = 30,
        widget = forms.TextInput(attrs={
            'placeholder':_('Last Name'),
            'class': 'span6 required',
            'required': '',
        })
    )
    email = forms.EmailField(
        label = _('E-Mail'),
        min_length = 5,
        widget = forms.TextInput(attrs={
            'placeholder': _('Your email address'),
            'type': 'email',
            'class': 'span12 required',
            'required': '',
        })
    )
    password = forms.CharField(
        label = _('Password'),
        min_length = 6,
        max_length = 30,
        widget = forms.PasswordInput(attrs={
            'placeholder':_('Password'),
            'class': 'span6 required',
            'required': '',
        })
    )
    confirm_password = forms.CharField(
        label = _('Re-type password'),
        min_length = 6,
        max_length = 30,
        widget = forms.PasswordInput(attrs={
            'placeholder':_('Re-type password'),
            'class': 'span6',
            'required': '',
        })
    )

    gender = forms.ChoiceField(choices=GENDER_CHOICES)

    month = forms.ChoiceField(choices=MONTH_CHOICES,
        widget=forms.Select(attrs={
            'class': 'span4',
        })
    )

    day = forms.CharField(
        label = _('Day'),
        min_length = 1,
        max_length = 2,
        widget = forms.TextInput(attrs={
            'placeholder':_('Day'),
            'class': 'span4',
            'required': '',
        })
    )

    year = forms.CharField(
        label = _('Year'),
        min_length = 4,
        max_length = 4,
        widget = forms.TextInput(attrs={
            'placeholder':_('Year'),
            'class': 'span4',
            'required': '',
        })
    )

    def clean_day(self):
        day = int(self.cleaned_data['day'])
        if (day > 31 or day < 1):
            raise forms.ValidationError(_('Invalid date'))
        return day

    def clean_month(self):
        month = int(self.cleaned_data['month'])
        if (month > 12 or month < 1):
            raise forms.ValidationError(_('Invalid date'))
        return month

    def clean_year(self):
        year = int(self.cleaned_data['year'])
        if (year > 2012 or year < 1900):
            raise forms.ValidationError(_('Invalid date'))
        return year

    def clean_email(self):
        email = self.cleaned_data['email']
        from django.contrib.auth.models import User
        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        else:
            # E-mail is a uniqe field
            raise forms.ValidationError(_('You are member! Did you forget your password?'))

    def clean_password(self):
        password = self.cleaned_data['password']
        # Check strog password
        return password

    def clean_confirm_password(self):
        confirm_password = self.cleaned_data['confirm_password']
        if confirm_password != self.cleaned_data['password']:
            raise forms.ValidationError(_('Password and Re-type does not match'))
        return confirm_password

class NewPostForm(forms.Form):
    text = forms.CharField(
        label=_('Text'),
        widget=forms.Textarea(attrs={
            'placeholder': _('Say it!'),
            'rows': 3,
            'class': 'span12',
            'style': 'resize: none;',
        })
    )
    book = forms.CharField(
        label=_('Book'),
        widget=forms.TextInput(attrs={
            'placeholder': _('Book Name'),
            'autocomplete': 'off',
            'data-provide': 'typeahead',
            'class': 'span6 typeahead',
            'id': 'title-look',
        })
    )
    author = forms.CharField(
        label=_('Author'),
        widget=forms.TextInput(attrs={
            'placeholder': _('Author Name'),
            'autocomplete': 'off',
            'data-provide': 'typeahead',
            'class': 'span6 typeahead',
            'id': 'author-look',
        })
    )


text:
require "Window"

local TrackLineGroup  = {}

setmetatable(TrackLineGroup, {
  __call = function (cls, ...)
    return cls.new(...)
  end,
})

TrackLineGroup.TrackMode = {
	Line = 1,
	Circle = 2
}

function TrackLineGroup.new(parent)
	local self = setmetatable({}, { __index = TrackLineGroup })

    self.Enabled = false
    self.parent = parent
	self.bgColor = CColor.new(0,1,0,1)
	self.intermediateColor = CColor.new(0, 0, 1, 1)
	self.complementaryColor = CColor.new(1, 0, 1, 1)
	self.clearDistance = 0 --20
	self.target = nil
	self.Sprite = "Icons:Arrow"
	self.trackMode = TrackLineGroup.TrackMode.Line
    --self.trackMode = TrackLine.TrackMode.Circle

	self.rotation = 0
	self.updateRotation = true
	self.isVisible = false
	self.distance = 10
	self.distanceMarker = 2
	self.showDistanceMarker = true
    self.TrackLines = {}

	return self
end

function TrackLineGroup:Load(saveData)
	if saveData ~= nil then
        self.Enabled = saveData.Enabled
		self:SetBGColor(CColor.new(saveData.bgColor[1], saveData.bgColor[2], saveData.bgColor[3], saveData.bgColor[4]))
		self.Sprite = saveData.Sprite

		if saveData.trackMode ~= nil then
			self:SetTrackMode(saveData.trackMode)
		end

		if saveData.distance ~= nil then
			self:SetDistance(saveData.distance)
		end

		if saveData.showDistanceMarker ~= nil then
			self.showDistanceMarker = saveData.showDistanceMarker
		end

        GeminiPackages:Require("AuraMastery:TrackLine", function(trackLine)
            for i = 1, saveData.numberOfTrackLines or 0, 1 do
                local line = trackLine.new(self)
                line:Load(saveData)
                table.insert(self.TrackLines, line)
            end
    	end)
	end
end

function TrackLineGroup:Save()
	local saveData = { }
    saveData.Enabled = self.Enabled
	saveData.Sprite = self.Sprite
	saveData.bgColor = { self.bgColor.r, self.bgColor.g, self.bgColor.b, self.bgColor.a }
	saveData.trackMode = self.trackMode
	saveData.distance = self.distance
	saveData.showDistanceMarker = self.showDistanceMarker
    saveData.numberOfTrackLines = #self.TrackLines
	return saveData
end

function TrackLineGroup:SetConfig(configWnd)
    self.Enabled = configWnd:FindChild("TrackLineEnabled"):IsChecked()
    local numberOfTrackLines = tonumber(configWnd:FindChild("TrackLineNumberOfLines"):GetText())
    if #self.TrackLines < numberOfTrackLines then
        for i = #self.TrackLines + 1, numberOfTrackLines, 1 do
            GeminiPackages:Require("AuraMastery:TrackLine", function(trackLine)
                local line = trackLine.new(self)
                line:Load(self:Save())
                table.insert(self.TrackLines, line)
            end)
        end
    elseif #self.TrackLines > numberOfTrackLines then
        for i = #self.TrackLines, numberOfTrackLines + 1, -1 do
            self.TrackLines[i]:Destroy()
            table.remove(self.TrackLines, i)
        end
    end
end

function TrackLineGroup:NumberOfLines()
    return #self.TrackLines
end

function TrackLineGroup:Update()
    if not self.Enabled then return end

	self:UpdateTarget()
    for _, trackLine in pairs(self.TrackLines) do
        trackLine:Update()
    end
end

function TrackLineGroup:UpdateTarget()
    local targets = self.parent:GetTargets() or {}
    local i = 1
    for _, target in pairs(targets) do
        if self.TrackLines[i] == nil then return end
	    self.TrackLines[i]:SetTarget(target.Unit)
        i = i + 1
    end
    local numOfLines = #self.TrackLines
    for i = i, numOfLines, 1 do
        self.TrackLines[i]:SetTarget(nil)
    end
end

function TrackLineGroup:DrawTracker(target)
	self.isVisible = true
	if GameLib.GetPlayerUnit() ~= nil then
		local player = GameLib.GetPlayerUnit()
		local playerPos = GameLib.GetPlayerUnit():GetPosition()
		local playerVec = Vector3.New(playerPos.x, playerPos.y, playerPos.z)
		local targetVec = nil
		if Vector3.Is(target) then
			targetVec = target
		elseif Unit.is(target) then
			local targetPos = target:GetPosition()
			if targetPos then
				targetVec = Vector3.New(targetPos.x, targetPos.y, targetPos.z)
			end
		end
		if targetVec ~= nil then
			if self.trackMode == TrackLine.TrackMode.Line then
				self:DrawLineBetween(playerVec, targetVec)
			elseif self.trackMode == TrackLine.TrackMode.Circle then
				self:DrawCircleAround(playerVec, targetVec)
			end
		else
			self:HideLine()
		end
	else
		self:HideLine()
	end
end

function TrackLineGroup:SetBGColor(color)
	self.bgColor = color
    self.intermediateColor = color
    self.complementaryColor = color
	--self.intermediateColor = self.trackMaster.colorPicker:GetComplementaryOffset(self.bgColor)
	--self.complementaryColor = self.trackMaster.colorPicker:GetComplementary(self.bgColor)
	--self.marker[self.distanceMarker]:FindChild("Distance"):SetTextColor(color)
end

function TrackLineGroup:SetTrackMode(mode)
	self.trackMode = mode
end

function TrackLineGroup:SetDistance(distance)
	self.distance = distance
end

function TrackLineGroup:SetShowDistanceMarker(isShown)
	self.showDistanceMarker = isShown

	if self.showDistanceMarker then
		self.marker[self.distanceMarker]:FindChild("Distance"):Show(true, true)
		self.marker[self.distanceMarker]:FindChild("Distance"):SetTextColor(self.bgColor)
		self.marker[self.distanceMarker]:SetSprite("")
		self.marker[self.distanceMarker]:SetRotation(0)
	else
		self.marker[self.distanceMarker]:SetSprite(self.Sprite)
		self.marker[self.distanceMarker]:FindChild("Distance"):Show(false, true)
	end
end

local GeminiPackages = _G["GeminiPackages"]
GeminiPackages:NewPackage(TrackLineGroup, "AuraMastery:TrackLineGroup", 1)

redpajama_set_name: RedPajamaGithub


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const http_transaction_1 = require("./http-transaction");
class TransitionStructure {
    constructor(resource, title) {
        this.resource = resource;
        this.title = title;
        this.http_transactions = [];
    }
    hasMultipleRequest() {
        for (let i = 0; i < this.http_transactions.length; i += 1) {
            const request = this.http_transactions[i].request;
            if (request.hasSpecificUri())
                return true;
        }
        return false;
    }
    addHttpTransaction(http_transaction) {
        this.http_transactions.push(http_transaction);
    }
    createHttpTransaction() {
        return http_transaction_1.HttpTransaction.create(this);
    }
    static create(resource, data) {
        const title = data.meta.title.content;
        return new TransitionStructure(resource, title);
    }
}
exports.TransitionStructure = TransitionStructure;


text:
package com.mygdx.proj.util;

import com.badlogic.ashley.core.ComponentMapper;
import com.mygdx.proj.components.*;

public class Mappers {
    public static final ComponentMapper<PositionComponent>
            positionMapper =
            ComponentMapper.getFor(PositionComponent.class);

    public static final ComponentMapper<InputComponent>
            inputMapper =
            ComponentMapper.getFor(InputComponent.class);

    public static final ComponentMapper<RenderComponent>
            renderMapper =
            ComponentMapper.getFor(RenderComponent.class);

    public static final ComponentMapper<HitboxComponent>
            hitboxMapper =
            ComponentMapper.getFor(HitboxComponent.class);

    public static final ComponentMapper<ExplosionComponent>
            explosionMapper =
            ComponentMapper.getFor(ExplosionComponent.class);

    public static final ComponentMapper<DestroyComponent>
            destroyMapper =
            ComponentMapper.getFor(DestroyComponent.class);

    public static final ComponentMapper<BehaviourComponent>
            behaviourMapper =
            ComponentMapper.getFor(BehaviourComponent.class);
}


text:
CREATE TABLE rt_downtimes (
  downtime_id serial,
  entry_time int NOT NULL,
  host_id int NOT NULL,
  service_id int default NULL,

  actual_end_time int default NULL,
  actual_start_time int default NULL,
  author varchar(64) default NULL,
  cancelled boolean default NULL,
  comment_data text default NULL,
  deletion_time int default NULL,
  duration int default NULL,
  end_time int default NULL,
  fixed boolean default NULL,
  instance_id int default NULL,
  internal_id int default NULL,
  start_time int default NULL,
  started boolean default NULL,
  triggered_by int default NULL,
  type smallint default NULL,
  is_recurring boolean default NULL,
  recurring_interval int default NULL,
  recurring_timeperiod varchar(200) default NULL,

  PRIMARY KEY (downtime_id),
  UNIQUE (entry_time, host_id, service_id),
  INDEX (host_id),
  INDEX (instance_id),
  INDEX (entry_time),
  INDEX (host_id, start_time),
  FOREIGN KEY (host_id) REFERENCES rt_hosts (host_id)
    ON DELETE CASCADE,
  FOREIGN KEY (instance_id) REFERENCES rt_instances (instance_id)
    ON DELETE SET NULL
);


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.areen.jlib.gui.hpainter;

import java.awt.*;
import javax.swing.text.*;

/*
 *  Implements a simple highlight painter that renders a rectangle around the
 *  area to be highlighted.
 *
 * Code taken from:
 *   http://tips4java.wordpress.com/2008/10/28/rectangle-painter/
 *   Author: Rob Camick
 */
public class SquigglePainter extends DefaultHighlighter.DefaultHighlightPainter {

    public SquigglePainter(Color color) {
        super(color);
    }

    /**
     * Paints a portion of a highlight.
     *
     * @param g the graphics context
     * @param offs0 the starting model offset >= 0
     * @param offs1 the ending model offset >= offs1
     * @param bounds the bounding box of the view, which is not necessarily the region to paint.
     * @param c the editor
     * @param view View painting for
     * @return region drawing occured in
     */
    public Shape paintLayer(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c, View view) {
        Rectangle r = getDrawingArea(offs0, offs1, bounds, view);

        if (r == null) {
            return null;
        }

		//  Do your custom painting
        Color color = getColor();
        g.setColor(color == null ? c.getSelectionColor() : color);

		//  Draw the squiggles
        int squiggle = 2;
        int twoSquiggles = squiggle * 2;
        int y = r.y + r.height - twoSquiggles;

        for (int x = r.x; x <= r.x + r.width - twoSquiggles; x += twoSquiggles) {
            g.drawArc(x, y, squiggle, squiggle, 0, 180);
            g.drawArc(x + squiggle, y, squiggle, squiggle, 180, 181);
        }

		// Return the drawing area
        return r;
    }

    private Rectangle getDrawingArea(int offs0, int offs1, Shape bounds, View view) {
        // Contained in view, can just use bounds.

        if (offs0 == view.getStartOffset() && offs1 == view.getEndOffset()) {
            Rectangle alloc;

            if (bounds instanceof Rectangle) {
                alloc = (Rectangle) bounds;
            } else {
                alloc = bounds.getBounds();
            }

            return alloc;
        } else {
            // Should only render part of View.
            try {
                // --- determine locations ---
                Shape shape = view.modelToView(offs0, Position.Bias.Forward, offs1,
                        Position.Bias.Backward, bounds);
                Rectangle r = (shape instanceof Rectangle) ? (Rectangle) shape : shape.getBounds();

                return r;
            } catch (BadLocationException e) {
                // can't render
            }
        }

		// Can't render
        return null;
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTokensTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tokens', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('id_calendario')->unsigned;
            $table->integer('id_usuario_servicio')->unsigned;
            $table->string('uuid');
            $table->boolean('consumido');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('tokens');
    }
}


text:
package csb

//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// OutputParameter is a nested struct in csb response
type OutputParameter struct {
	MapStyle     int    `json:"MapStyle" xml:"MapStyle"`
	Optional     bool   `json:"Optional" xml:"Optional"`
	ParamType    string `json:"ParamType" xml:"ParamType"`
	PassMethod   string `json:"PassMethod" xml:"PassMethod"`
	ExtType      int    `json:"ExtType" xml:"ExtType"`
	CatType      int    `json:"CatType" xml:"CatType"`
	Depth        int    `json:"Depth" xml:"Depth"`
	OriginalName string `json:"OriginalName" xml:"OriginalName"`
	TargetName   string `json:"TargetName" xml:"TargetName"`
}


text:
namespace gamelib
{
    class VertexTool : public Tool
    {
        public:
            VertexTool();

            void onMousePressed() final override;
            void onDrag() final override;
            void drawGui() final override;
            void render(sf::RenderTarget& target) final override;

        private:
            size_t _selected;
            bool _snappoint;
    };
}

#endif


text:
export db_address=12.34.56.78
export db_port=5555
export server_port=8888

./user-data.sh

output=$(curl "http://localhost:$server_port")

if [[ $output == *"Hello, World"* ]]; then
  echo "Success! Got expected text from server."
else
  echo "Error. Did not get back expected text 'Hello, World'."
fi


text:
package com.dangdang.ddframe.job.internal.election;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public final class ElectionNodeTest {

    private ElectionNode electionNode = new ElectionNode("testJob");

    @Test
    public void assertIsShardingTotalCountPath() {
        assertTrue(electionNode.isLeaderHostPath("/testJob/leader/election/host"));
    }

    @Test
    public void assertIsNotShardingTotalCountPath() {
        assertFalse(electionNode.isLeaderHostPath("/testJob/leader/election/host1"));
    }
}


text:
package org.netling.ssh.transport.kex;

import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PublicKey;

import javax.crypto.KeyAgreement;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.DHPublicKeySpec;

import org.netling.ssh.common.SSHRuntimeException;
import org.netling.ssh.common.SecurityUtils;

/** Diffie-Hellman key generator. */
public class DH {

    private BigInteger p;
    private BigInteger g;
    private BigInteger e; // my public key
    private BigInteger f; // your public key
    private BigInteger K; // shared secret key
    private final KeyPairGenerator generator;
    private final KeyAgreement agreement;

    public DH() {
        try {
            generator = SecurityUtils.getKeyPairGenerator("DH");
            agreement = SecurityUtils.getKeyAgreement("DH");
        } catch (GeneralSecurityException e) {
            throw new SSHRuntimeException(e);
        }
    }

    public void setF(BigInteger f) {
        this.f = f;
    }

    public void setG(BigInteger g) {
        this.g = g;
    }

    public void setP(BigInteger p) {
        this.p = p;
    }

    public byte[] getE()
            throws GeneralSecurityException {
        if (e == null) {
            generator.initialize(new DHParameterSpec(p, g));
            final KeyPair kp = generator.generateKeyPair();
            agreement.init(kp.getPrivate());
            e = ((javax.crypto.interfaces.DHPublicKey) kp.getPublic()).getY();
        }
        return e.toByteArray();
    }

    public byte[] getK()
            throws GeneralSecurityException {
        if (K == null) {
            final KeyFactory keyFactory = SecurityUtils.getKeyFactory("DH");
            final DHPublicKeySpec keySpec = new DHPublicKeySpec(f, p, g);
            final PublicKey yourPubKey = keyFactory.generatePublic(keySpec);
            agreement.doPhase(yourPubKey, true);
            K = new BigInteger(agreement.generateSecret());
        }
        return K.toByteArray();
    }

}


text:
<pre>
  PIP: PIP-0042
  Title: Update OP_RECOVER to initial sense described on original WhitePaper and allow ASK FOR PASA feature
  Type: Protocol
  Impact: Hard-Fork
  Author: Albert Molina <bpascalblockchain@gmail.com>
  Copyright: Albert Molina, 2021 (All Rights Reserved)
  Comments-URI: https://discord.gg/gamPX9E4RF (Discord channel #pip-42)
  Status: Proposed
  Created: 2021-09-23
</pre>

## Summary

Update current OP_RECOVER operation in order to have a similar sense as described on [Original PascalCoin WhitePaper published on July 2016][1] few weeks before Genesis Block.

## Motivation

OP_RECOVER feature was defined on original PascalCoin Whitepaper published on July 2016 as a way to allow recover coins that has lost private key.

**PascalCoin WhitePaper:**
```
PascalCoin proposes an alternative to the basic operation of Bitcoin, through which change
several aspects for working on the new virtual currency:
...
  - PascalCoin provides a method set by protocol to retrieve coins that are not used
    instead (lost key). This method only applies if after a certain time the owner does not
    make any operation with the account private key.
...
(Page 2/8)
```

Basically was a way to mantain a constant and predectible inflation and available coin because burning coins are not possible.

Current problem is that WhitePaper definition is ambiguous and **certain time** was not specified, initial source code proposal was to **set a time value = 4 years** (420480 blocks in PascalCoin)

Another problem is that WhitePaper didn't specified who can retrieve coins that are not used, neither what to do with Pascal Accounts (aka **PASA**) not used.

## Proposal

This PIP specifies a more accurated OP_RECOVER feature that will mantain initial sense and will allow a fair PASA and coins distribution.

Update current OP_RECOVER to work as this:

1. The way to know if an Account is not used will be counting how many blocks since last private key signed this Account as an Active mode as defined on [PIP-0037][2].

2. Accounts without coins (amount = 0) can be reused to community usage in a ASK FOR PASA (OP_RECOVER special case) after 4 years if Account has not been used as specified on 1.

3. Coins stored in Accounts (where amount > 0) can be retrieved to MINER that generates a block as a fee in the OP_RECOVER operation after 10 years if Account has not been used as specified on 1.

4. ASK FOR PASA will be an OP_RECOVER special case operation signed by an Authority Account, Authority Account will be the Account stored in the type value of Account number 1 ( Account(1).type == Authority Account ).

5. Accounts 0 to 9 (inclusive) are exempt for OP_RECOVER operation.

## Specification

The following changes are required to implement this in PascalCoin.

### New OP_RECOVER fields

A new field `sign` will be added to OP_RECOVER that will be used in Proposal number 2. Value MUST be empty in other cases.

```
  TOpRecoverFoundsData = Record
    account: Cardinal;
    n_operation : Cardinal;
    fee: UInt64;
    new_publicKey: TAccountKey;
	// New field for PIP-0042
    sign: TECDSA_SIG;
  End;
```

### Update OP_RECOVER code

#### Changes on check

Check proposals 2 to 5:

```
  let A = target PASA
  let L4Years = 420480  ((24 hours * 60 minutes) DIV 5 minutes) * 365 days * 4 years)
  let L10Years = 1051200  ((24 hours * 60 minutes) DIV 5 minutes) * 365 days * 10 years)
  let LCurrentBlock = Current Blockchain new block number

  // Proposal 5 protection
  if (A.account<=9) then
     Error 'Accounts 0..9 are protected';

  // Proposal 2 protection
  if (A.updated_on_block_active_mode + L4Years >= LCurrentBlock) then
     Error 'Account is still active (less than 4 years without private key usage)';

  // Proposal 3 protection
  if (A.updated_on_block_active_mode + L10Years >= LCurrentBlock) AND (A.Balance > 0) then
     Error 'Account has balance>0 and still active (less than 10 years without private key usage)';

  let B = Account(1)
  let C = Account( B.type ) // Authority account
  let DATA = OP_RECOVER fields

  // Proposal 4 ASK FOR PASA signed by Authority account
  if ((DATA.new_publicKey) not null) AND (NOT IsValidSignature(DATA.sign, C.accountInfo.publicKey)) then
     Error 'Ask for Pasa feature must be signed by Authority account';

```

#### Changes on Execute

Execution is done only **after checks are passed**

```
  // Assume same fields than check code

  // Ask for Pasa
  if ((DATA.new_publicKey) not null) then
    set A.accountInfo.publicKey = DATA.new_publicKey

  set FEE = A.balance
  set A.balance = 0; // Sets Account balance to 0, balance will be a fee for the miner

  SaveAccount( A );

  // Only the miner will obtain coins as a Fee of the block, none other can retrieve coins
  IncrementNewBlockFee( FEE );

```

### Conclusion

Only miner can retrieve coins, this will help and add a miners and pools race

Current holders will have a reasonable time period (10 years) to hold coins

Ask for Pasa feature will be available since activation thanks to 4 years rule

## Affected PIP's

This PIP deactivates PIP-0012 and PIP-0019

## Backwards Compatibility

This change is not backwards compatible and requires a hard-fork activation.

## Links

1. [Original PascalCoin WhitePaper published on July 2016. Accessed 2021-09.][1]
2. [PIP-0037][2]

[1]: https://github.com/PascalCoin/PascalCoin/blob/c22184dd7a407c6646ab651494822071726ed36e/PascalCoin%20White%20Paper%20-%20EN.pdf
[2]: https://github.com/PascalCoin/PascalCoin/blob/master/PIP/PIP-0037.md


text:
class PatroniException(Exception):

    """Parent class for all kind of exceptions related to selected distributed configuration store"""

    def __init__(self, value):
        self.value = value

    def __str__(self):
        """
        >>> str(PatroniException('foo'))
        "'foo'"
        """
        return repr(self.value)

class PatroniFatalException(PatroniException):
    pass

class PostgresException(PatroniException):
    pass

class DCSError(PatroniException):
    pass

class PostgresConnectionException(PostgresException):
    pass

class WatchdogError(PatroniException):
    pass

class ConfigParseError(PatroniException):
    pass


text:
<?php
	namespace Build;

	class Repository {
		public $id;
		private $_error;

		public function __construct($id = null) {
			if (isset($id) && is_numeric($id)) {
				$this->id = $id;
				$this->details();
			}
		}

		public function add($parameters) {
			if (! isset($parameters['url']) || ! strlen($parameters['url'])) {
				$this->_error = "url required";
				return false;
			}

			$add_object_query = "
				INSERT
				INTO	build_repositories
				(		id,url)
				VALUES
				(		null,?)
			";
			$GLOBALS['_database']->Execute($add_object_query,array($parameters['url']));
			if ($GLOBALS['_database']->ErrorMsg()) {
				$this->_error = "SQL Error in Build::Repository::add(): ".$GLOBALS['_database']->ErrorMsg();
				return false;
			}
			$this->id = $GLOBALS['_database']->Insert_ID();
			return $this->update($parameters);
		}

		public function update($parameters = array()) {
			return $this->details();
		}

		public function get($url) {
			$get_object_query = "
				SELECT	id
				FROM	build_repositories
				WHERE	url = ?
			";

			$rs = $GLOBALS['_database']->Execute($get_object_query,array($url));
			if (! $rs) {
				$this->_error = "SQL Error in Build::Repository::get(): ".$GLOBALS['_database']->ErrorMsg();
				return false;
			}
			list($this->id) = $rs->FetchRow();
			if ($this->id > 0) {
				app_log("Found repository ".$this->id);
				return $this->details();
			}
			return false;
		}
		public function details() {
			$get_object_query = "
				SELECT	*
				FROM	build_repositories
				WHERE	id = ?
			";
			$rs = $GLOBALS['_database']->Execute($get_object_query,array($this->id));
			if (! $rs) {
				$this->_error = "SQL Error in Build::Repository::details(): ".$GLOBALS['_database']->ErrorMsg();
				return false;
			}
			$object = $rs->FetchNextObject(false);
			if ($object->id) {
				$this->id = $object->id;
				$this->url = $object->url;
				return true;
			}
			else {
				$this->id = null;
				return false;
			}
		}

		public function error() {
			return $this->_error;
		}
	}


text:
#ifndef HB_CFF_INTERP_COMMON_HH
#define HB_CFF_INTERP_COMMON_HH

namespace CFF {

using namespace OT;

typedef unsigned int op_code_t;

/* === Dict operators === */

/* One byte operators (0-31) */
#define OpCode_version		  0 /* CFF Top */
#define OpCode_Notice		  1 /* CFF Top */
#define OpCode_FullName		  2 /* CFF Top */
#define OpCode_FamilyName	  3 /* CFF Top */
#define OpCode_Weight		  4 /* CFF Top */
#define OpCode_FontBBox		  5 /* CFF Top */
#define OpCode_BlueValues	  6 /* CFF Private, CFF2 Private */
#define OpCode_OtherBlues	  7 /* CFF Private, CFF2 Private */
#define OpCode_FamilyBlues	  8 /* CFF Private, CFF2 Private */
#define OpCode_FamilyOtherBlues	  9 /* CFF Private, CFF2 Private */
#define OpCode_StdHW		 10 /* CFF Private, CFF2 Private */
#define OpCode_StdVW		 11 /* CFF Private, CFF2 Private */
#define OpCode_escape		 12 /* All. Shared with CS */
#define OpCode_UniqueID		 13 /* CFF Top */
#define OpCode_XUID		 14 /* CFF Top */
#define OpCode_charset		 15 /* CFF Top (0) */
#define OpCode_Encoding		 16 /* CFF Top (0) */
#define OpCode_CharStrings	 17 /* CFF Top, CFF2 Top */
#define OpCode_Private		 18 /* CFF Top, CFF2 FD */
#define OpCode_Subrs		 19 /* CFF Private, CFF2 Private */
#define OpCode_defaultWidthX	 20 /* CFF Private (0) */
#define OpCode_nominalWidthX	 21 /* CFF Private (0) */
#define OpCode_vsindexdict	 22 /* CFF2 Private/CS */
#define OpCode_blenddict	 23 /* CFF2 Private/CS */
#define OpCode_vstore		 24 /* CFF2 Top */
#define OpCode_reserved25	 25
#define OpCode_reserved26	 26
#define OpCode_reserved27	 27

/* Numbers */
#define OpCode_shortint		 28 /* 16-bit integer, All */
#define OpCode_longintdict	 29 /* 32-bit integer, All */
#define OpCode_BCD		 30 /* Real number, CFF2 Top/FD */
#define OpCode_reserved31	 31

/* 1-byte integers */
#define OpCode_OneByteIntFirst	 32 /* All. beginning of the range of first byte ints */
#define OpCode_OneByteIntLast	246 /* All. ending of the range of first byte int */

/* 2-byte integers */
#define OpCode_TwoBytePosInt0	247 /* All. first byte of two byte positive int (+108 to +1131) */
#define OpCode_TwoBytePosInt1	248
#define OpCode_TwoBytePosInt2	249
#define OpCode_TwoBytePosInt3	250

#define OpCode_TwoByteNegInt0	251 /* All. first byte of two byte negative int (-1131 to -108) */
#define OpCode_TwoByteNegInt1	252
#define OpCode_TwoByteNegInt2	253
#define OpCode_TwoByteNegInt3	254

/* Two byte escape operators 12, (0-41) */
#define OpCode_ESC_Base		256
#define Make_OpCode_ESC(byte2)	((op_code_t)(OpCode_ESC_Base + (byte2)))

inline op_code_t Unmake_OpCode_ESC (op_code_t op)  { return (op_code_t)(op - OpCode_ESC_Base); }
inline bool Is_OpCode_ESC (op_code_t op) { return op >= OpCode_ESC_Base; }
inline unsigned int OpCode_Size (op_code_t op) { return Is_OpCode_ESC (op) ? 2: 1; }

#define OpCode_Copyright	Make_OpCode_ESC(0) /* CFF Top */
#define OpCode_isFixedPitch	Make_OpCode_ESC(1) /* CFF Top (false) */
#define OpCode_ItalicAngle	Make_OpCode_ESC(2) /* CFF Top (0) */
#define OpCode_UnderlinePosition Make_OpCode_ESC(3) /* CFF Top (-100) */
#define OpCode_UnderlineThickness Make_OpCode_ESC(4) /* CFF Top (50) */
#define OpCode_PaintType	Make_OpCode_ESC(5) /* CFF Top (0) */
#define OpCode_CharstringType	Make_OpCode_ESC(6) /* CFF Top (2) */
#define OpCode_FontMatrix	Make_OpCode_ESC(7) /* CFF Top, CFF2 Top (.001 0 0 .001 0 0)*/
#define OpCode_StrokeWidth	Make_OpCode_ESC(8) /* CFF Top (0) */
#define OpCode_BlueScale	Make_OpCode_ESC(9) /* CFF Private, CFF2 Private (0.039625) */
#define OpCode_BlueShift	Make_OpCode_ESC(10) /* CFF Private, CFF2 Private (7) */
#define OpCode_BlueFuzz		Make_OpCode_ESC(11) /* CFF Private, CFF2 Private (1) */
#define OpCode_StemSnapH	Make_OpCode_ESC(12) /* CFF Private, CFF2 Private */
#define OpCode_StemSnapV	Make_OpCode_ESC(13) /* CFF Private, CFF2 Private */
#define OpCode_ForceBold	Make_OpCode_ESC(14) /* CFF Private (false) */
#define OpCode_reservedESC15	Make_OpCode_ESC(15)
#define OpCode_reservedESC16	Make_OpCode_ESC(16)
#define OpCode_LanguageGroup	Make_OpCode_ESC(17) /* CFF Private, CFF2 Private (0) */
#define OpCode_ExpansionFactor	Make_OpCode_ESC(18) /* CFF Private, CFF2 Private (0.06) */
#define OpCode_initialRandomSeed Make_OpCode_ESC(19) /* CFF Private (0) */
#define OpCode_SyntheticBase	Make_OpCode_ESC(20) /* CFF Top */
#define OpCode_PostScript	Make_OpCode_ESC(21) /* CFF Top */
#define OpCode_BaseFontName	Make_OpCode_ESC(22) /* CFF Top */
#define OpCode_BaseFontBlend	Make_OpCode_ESC(23) /* CFF Top */
#define OpCode_reservedESC24	Make_OpCode_ESC(24)
#define OpCode_reservedESC25	Make_OpCode_ESC(25)
#define OpCode_reservedESC26	Make_OpCode_ESC(26)
#define OpCode_reservedESC27	Make_OpCode_ESC(27)
#define OpCode_reservedESC28	Make_OpCode_ESC(28)
#define OpCode_reservedESC29	Make_OpCode_ESC(29)
#define OpCode_ROS		Make_OpCode_ESC(30) /* CFF Top_CID */
#define OpCode_CIDFontVersion	Make_OpCode_ESC(31) /* CFF Top_CID (0) */
#define OpCode_CIDFontRevision	Make_OpCode_ESC(32) /* CFF Top_CID (0) */
#define OpCode_CIDFontType	Make_OpCode_ESC(33) /* CFF Top_CID (0) */
#define OpCode_CIDCount		Make_OpCode_ESC(34) /* CFF Top_CID (8720) */
#define OpCode_UIDBase		Make_OpCode_ESC(35) /* CFF Top_CID */
#define OpCode_FDArray		Make_OpCode_ESC(36) /* CFF Top_CID, CFF2 Top */
#define OpCode_FDSelect		Make_OpCode_ESC(37) /* CFF Top_CID, CFF2 Top */
#define OpCode_FontName		Make_OpCode_ESC(38) /* CFF Top_CID */

/* === CharString operators === */

#define OpCode_hstem		  1 /* CFF, CFF2 */
#define OpCode_Reserved2	  2
#define OpCode_vstem		  3 /* CFF, CFF2 */
#define OpCode_vmoveto		  4 /* CFF, CFF2 */
#define OpCode_rlineto		  5 /* CFF, CFF2 */
#define OpCode_hlineto		  6 /* CFF, CFF2 */
#define OpCode_vlineto		  7 /* CFF, CFF2 */
#define OpCode_rrcurveto	  8 /* CFF, CFF2 */
#define OpCode_Reserved9	  9
#define OpCode_callsubr		 10 /* CFF, CFF2 */
#define OpCode_return		 11 /* CFF */
//#define OpCode_escape		 12 /* CFF, CFF2 */
#define OpCode_Reserved13	 13
#define OpCode_endchar		 14 /* CFF */
#define OpCode_vsindexcs	 15 /* CFF2 */
#define OpCode_blendcs		 16 /* CFF2 */
#define OpCode_Reserved17	 17
#define OpCode_hstemhm		 18 /* CFF, CFF2 */
#define OpCode_hintmask		 19 /* CFF, CFF2 */
#define OpCode_cntrmask		 20 /* CFF, CFF2 */
#define OpCode_rmoveto		 21 /* CFF, CFF2 */
#define OpCode_hmoveto		 22 /* CFF, CFF2 */
#define OpCode_vstemhm		 23 /* CFF, CFF2 */
#define OpCode_rcurveline	 24 /* CFF, CFF2 */
#define OpCode_rlinecurve	 25 /* CFF, CFF2 */
#define OpCode_vvcurveto	 26 /* CFF, CFF2 */
#define OpCode_hhcurveto	 27 /* CFF, CFF2 */
//#define OpCode_shortint	 28 /* CFF, CFF2 */
#define OpCode_callgsubr	 29 /* CFF, CFF2 */
#define OpCode_vhcurveto	 30 /* CFF, CFF2 */
#define OpCode_hvcurveto	 31 /* CFF, CFF2 */

#define OpCode_fixedcs		255 /* 32-bit fixed */

/* Two byte escape operators 12, (0-41) */
#define OpCode_dotsection	Make_OpCode_ESC(0) /* CFF (obsoleted) */
#define OpCode_ReservedESC1	Make_OpCode_ESC(1)
#define OpCode_ReservedESC2	Make_OpCode_ESC(2)
#define OpCode_and		Make_OpCode_ESC(3) /* CFF */
#define OpCode_or		Make_OpCode_ESC(4) /* CFF */
#define OpCode_not		Make_OpCode_ESC(5) /* CFF */
#define OpCode_ReservedESC6	Make_OpCode_ESC(6)
#define OpCode_ReservedESC7	Make_OpCode_ESC(7)
#define OpCode_ReservedESC8	Make_OpCode_ESC(8)
#define OpCode_abs		Make_OpCode_ESC(9) /* CFF */
#define OpCode_add		Make_OpCode_ESC(10) /* CFF */
#define OpCode_sub		Make_OpCode_ESC(11) /* CFF */
#define OpCode_div		Make_OpCode_ESC(12) /* CFF */
#define OpCode_ReservedESC13	Make_OpCode_ESC(13)
#define OpCode_neg		Make_OpCode_ESC(14) /* CFF */
#define OpCode_eq		Make_OpCode_ESC(15) /* CFF */
#define OpCode_ReservedESC16	Make_OpCode_ESC(16)
#define OpCode_ReservedESC17	Make_OpCode_ESC(17)
#define OpCode_drop		Make_OpCode_ESC(18) /* CFF */
#define OpCode_ReservedESC19	Make_OpCode_ESC(19)
#define OpCode_put		Make_OpCode_ESC(20) /* CFF */
#define OpCode_get		Make_OpCode_ESC(21) /* CFF */
#define OpCode_ifelse		Make_OpCode_ESC(22) /* CFF */
#define OpCode_random		Make_OpCode_ESC(23) /* CFF */
#define OpCode_mul		Make_OpCode_ESC(24) /* CFF */
//#define OpCode_reservedESC25	Make_OpCode_ESC(25)
#define OpCode_sqrt		Make_OpCode_ESC(26) /* CFF */
#define OpCode_dup		Make_OpCode_ESC(27) /* CFF */
#define OpCode_exch		Make_OpCode_ESC(28) /* CFF */
#define OpCode_index		Make_OpCode_ESC(29) /* CFF */
#define OpCode_roll		Make_OpCode_ESC(30) /* CFF */
#define OpCode_reservedESC31	Make_OpCode_ESC(31)
#define OpCode_reservedESC32	Make_OpCode_ESC(32)
#define OpCode_reservedESC33	Make_OpCode_ESC(33)
#define OpCode_hflex		Make_OpCode_ESC(34) /* CFF, CFF2 */
#define OpCode_flex		Make_OpCode_ESC(35) /* CFF, CFF2 */
#define OpCode_hflex1		Make_OpCode_ESC(36) /* CFF, CFF2 */
#define OpCode_flex1		Make_OpCode_ESC(37) /* CFF, CFF2 */

#define OpCode_Invalid		0xFFFFu

struct number_t
{
  void set_int (int v)       { value = v; }
  int to_int () const        { return value; }

  void set_fixed (int32_t v) { value = v / 65536.0; }
  int32_t to_fixed () const  { return value * 65536.0; }

  void set_real (double v)   { value = v; }
  double to_real () const    { return value; }

  bool in_int_range () const
  { return ((double) (int16_t) to_int () == value); }

  bool operator >  (const number_t &n) const { return value > n.to_real (); }
  bool operator <  (const number_t &n) const { return n > *this; }
  bool operator >= (const number_t &n) const { return !(*this < n); }
  bool operator <= (const number_t &n) const { return !(*this > n); }

  const number_t &operator += (const number_t &n)
  {
    set_real (to_real () + n.to_real ());

    return *this;
  }

  protected:
  double value = 0.;
};

/* byte string */
struct UnsizedByteStr : UnsizedArrayOf <HBUINT8>
{
  hb_ubytes_t as_ubytes (unsigned l) const
  { return hb_ubytes_t ((const unsigned char *) this, l); }

  // encode 2-byte int (Dict/CharString) or 4-byte int (Dict)
  template <typename T, typename V>
  static bool serialize_int (hb_serialize_context_t *c, op_code_t intOp, V value)
  {
    TRACE_SERIALIZE (this);

    HBUINT8 *p = c->allocate_size<HBUINT8> (1);
    if (unlikely (!p)) return_trace (false);
    *p = intOp;

    T *ip = c->allocate_size<T> (T::static_size);
    if (unlikely (!ip)) return_trace (false);
    return_trace (c->check_assign (*ip, value, HB_SERIALIZE_ERROR_INT_OVERFLOW));
  }

  template <typename V>
  static bool serialize_int4 (hb_serialize_context_t *c, V value)
  { return serialize_int<HBINT32> (c, OpCode_longintdict, value); }

  template <typename V>
  static bool serialize_int2 (hb_serialize_context_t *c, V value)
  { return serialize_int<HBINT16> (c, OpCode_shortint, value); }

  /* Defining null_size allows a Null object may be created. Should be safe because:
   * A descendent struct Dict uses a Null pointer to indicate a missing table,
   * checked before access.
   */
  DEFINE_SIZE_MIN(0);
};

/* A byte string associated with the current offset and an error condition */
struct byte_str_ref_t
{
  byte_str_ref_t () { init (); }

  void init ()
  {
    str = hb_ubytes_t ();
    offset = 0;
    error = false;
  }

  void fini () {}

  byte_str_ref_t (const hb_ubytes_t &str_, unsigned int offset_ = 0)
    : str (str_), offset (offset_), error (false) {}

  void reset (const hb_ubytes_t &str_, unsigned int offset_ = 0)
  {
    str = str_;
    offset = offset_;
    error = false;
  }

  const unsigned char& operator [] (int i) {
    if (unlikely ((unsigned int) (offset + i) >= str.length))
    {
      set_error ();
      return Null (unsigned char);
    }
    return str[offset + i];
  }

  /* Conversion to hb_ubytes_t */
  operator hb_ubytes_t () const { return str.sub_array (offset, str.length - offset); }

  hb_ubytes_t sub_array (unsigned int offset_, unsigned int len_) const
  { return str.sub_array (offset_, len_); }

  bool avail (unsigned int count=1) const
  { return (!in_error () && offset + count <= str.length); }
  void inc (unsigned int count=1)
  {
    if (likely (!in_error () && (offset <= str.length) && (offset + count <= str.length)))
    {
      offset += count;
    }
    else
    {
      offset = str.length;
      set_error ();
    }
  }

  void set_error ()      { error = true; }
  bool in_error () const { return error; }

  hb_ubytes_t       str;
  unsigned int  offset; /* beginning of the sub-string within str */

  protected:
  bool	  error;
};

using byte_str_array_t = hb_vector_t<hb_ubytes_t>;

/* stack */
template <typename ELEM, int LIMIT>
struct cff_stack_t
{
  ELEM& operator [] (unsigned int i)
  {
    if (unlikely (i >= count))
    {
      set_error ();
      return Crap (ELEM);
    }
    return elements[i];
  }

  void push (const ELEM &v)
  {
    if (likely (count < LIMIT))
      elements[count++] = v;
    else
      set_error ();
  }
  ELEM &push ()
  {
    if (likely (count < LIMIT))
      return elements[count++];
    else
    {
      set_error ();
      return Crap (ELEM);
    }
  }

  ELEM& pop ()
  {
    if (likely (count > 0))
      return elements[--count];
    else
    {
      set_error ();
      return Crap (ELEM);
    }
  }
  void pop (unsigned int n)
  {
    if (likely (count >= n))
      count -= n;
    else
      set_error ();
  }

  const ELEM& peek ()
  {
    if (unlikely (count == 0))
    {
      set_error ();
      return Null (ELEM);
    }
    return elements[count - 1];
  }

  void unpop ()
  {
    if (likely (count < LIMIT))
      count++;
    else
      set_error ();
  }

  void clear () { count = 0; }

  bool in_error () const { return (error); }
  void set_error ()      { error = true; }

  unsigned int get_count () const { return count; }
  bool is_empty () const          { return !count; }

  hb_array_t<const ELEM> sub_array (unsigned start, unsigned length) const
  { return hb_array_t<const ELEM> (elements).sub_array (start, length); }

  private:
  bool error = false;
  unsigned int count = 0;
  ELEM elements[LIMIT];
};

/* argument stack */
template <typename ARG=number_t>
struct arg_stack_t : cff_stack_t<ARG, 513>
{
  void push_int (int v)
  {
    ARG &n = S::push ();
    n.set_int (v);
  }

  void push_fixed (int32_t v)
  {
    ARG &n = S::push ();
    n.set_fixed (v);
  }

  void push_real (double v)
  {
    ARG &n = S::push ();
    n.set_real (v);
  }

  ARG& pop_num () { return this->pop (); }

  int pop_int ()  { return this->pop ().to_int (); }

  unsigned int pop_uint ()
  {
    int i = pop_int ();
    if (unlikely (i < 0))
    {
      i = 0;
      S::set_error ();
    }
    return (unsigned) i;
  }

  void push_longint_from_substr (byte_str_ref_t& str_ref)
  {
    push_int ((str_ref[0] << 24) | (str_ref[1] << 16) | (str_ref[2] << 8) | (str_ref[3]));
    str_ref.inc (4);
  }

  bool push_fixed_from_substr (byte_str_ref_t& str_ref)
  {
    if (unlikely (!str_ref.avail (4)))
      return false;
    push_fixed ((int32_t)*(const HBUINT32*)&str_ref[0]);
    str_ref.inc (4);
    return true;
  }

  private:
  typedef cff_stack_t<ARG, 513> S;
};

/* an operator prefixed by its operands in a byte string */
struct op_str_t
{
  hb_ubytes_t str;
  op_code_t  op;
};

/* base of OP_SERIALIZER */
struct op_serializer_t
{
  protected:
  bool copy_opstr (hb_serialize_context_t *c, const op_str_t& opstr) const
  {
    TRACE_SERIALIZE (this);

    HBUINT8 *d = c->allocate_size<HBUINT8> (opstr.str.length);
    if (unlikely (!d)) return_trace (false);
    memcpy (d, &opstr.str[0], opstr.str.length);
    return_trace (true);
  }
};

template <typename VAL>
struct parsed_values_t
{
  void init ()
  {
    opStart = 0;
    values.init ();
  }
  void fini () { values.fini (); }

  void alloc (unsigned n)
  {
    values.alloc (n);
  }

  void add_op (op_code_t op, const byte_str_ref_t& str_ref = byte_str_ref_t ())
  {
    VAL *val = values.push ();
    val->op = op;
    val->str = str_ref.str.sub_array (opStart, str_ref.offset - opStart);
    opStart = str_ref.offset;
  }

  void add_op (op_code_t op, const byte_str_ref_t& str_ref, const VAL &v)
  {
    VAL *val = values.push (v);
    val->op = op;
    val->str = str_ref.sub_array ( opStart, str_ref.offset - opStart);
    opStart = str_ref.offset;
  }

  bool has_op (op_code_t op) const
  {
    for (const auto& v : values)
      if (v.op == op) return true;
    return false;
  }

  unsigned get_count () const { return values.length; }
  const VAL &get_value (unsigned int i)   const { return values[i]; }
  const VAL &operator [] (unsigned int i) const { return get_value (i); }

  unsigned int       opStart;
  hb_vector_t<VAL>   values;
};

template <typename ARG=number_t>
struct interp_env_t
{
  interp_env_t () {}
  interp_env_t (const hb_ubytes_t &str_)
  {
    str_ref.reset (str_);
  }
  bool in_error () const
  { return error || str_ref.in_error () || argStack.in_error (); }

  void set_error () { error = true; }

  op_code_t fetch_op ()
  {
    op_code_t  op = OpCode_Invalid;
    if (unlikely (!str_ref.avail ()))
      return OpCode_Invalid;
    op = (op_code_t)(unsigned char)str_ref[0];
    if (op == OpCode_escape) {
      if (unlikely (!str_ref.avail ()))
	return OpCode_Invalid;
      op = Make_OpCode_ESC(str_ref[1]);
      str_ref.inc ();
    }
    str_ref.inc ();
    return op;
  }

  const ARG& eval_arg (unsigned int i) { return argStack[i]; }

  ARG& pop_arg () { return argStack.pop (); }
  void pop_n_args (unsigned int n) { argStack.pop (n); }

  void clear_args () { pop_n_args (argStack.get_count ()); }

  byte_str_ref_t
		str_ref;
  arg_stack_t<ARG>
		argStack;
  protected:
  bool		error = false;
};

using num_interp_env_t =  interp_env_t<>;

template <typename ARG=number_t>
struct opset_t
{
  static void process_op (op_code_t op, interp_env_t<ARG>& env)
  {
    switch (op) {
      case OpCode_shortint:
	env.argStack.push_int ((int16_t)((env.str_ref[0] << 8) | env.str_ref[1]));
	env.str_ref.inc (2);
	break;

      case OpCode_TwoBytePosInt0: case OpCode_TwoBytePosInt1:
      case OpCode_TwoBytePosInt2: case OpCode_TwoBytePosInt3:
	env.argStack.push_int ((int16_t)((op - OpCode_TwoBytePosInt0) * 256 + env.str_ref[0] + 108));
	env.str_ref.inc ();
	break;

      case OpCode_TwoByteNegInt0: case OpCode_TwoByteNegInt1:
      case OpCode_TwoByteNegInt2: case OpCode_TwoByteNegInt3:
	env.argStack.push_int ((-(int16_t)(op - OpCode_TwoByteNegInt0) * 256 - env.str_ref[0] - 108));
	env.str_ref.inc ();
	break;

      default:
	/* 1-byte integer */
	if (likely ((OpCode_OneByteIntFirst <= op) && (op <= OpCode_OneByteIntLast)))
	{
	  env.argStack.push_int ((int)op - 139);
	} else {
	  /* invalid unknown operator */
	  env.clear_args ();
	  env.set_error ();
	}
	break;
    }
  }
};

template <typename ENV>
struct interpreter_t
{
  interpreter_t (ENV& env_) : env (env_) {}
  ENV& env;
};

} /* namespace CFF */

#endif /* HB_CFF_INTERP_COMMON_HH */


text:
package com.gooddata.sdk.model.project;

import org.testng.annotations.Test;

import static com.gooddata.sdk.common.util.ResourceUtils.readObjectFromResource;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.text.MatchesPattern.matchesPattern;

public class RolesTest {

    @Test
    public void testDeserialization() throws Exception {
        final Roles roles = readObjectFromResource("/project/project-roles.json", Roles.class);

        assertThat(roles, notNullValue());
        assertThat(roles.getRoles(), hasSize(2));
        assertThat(roles.getRoles(), hasItem("/gdc/projects/PROJECT_ID/roles/ROLE1"));
        assertThat(roles.getRoles(), hasItem("/gdc/projects/PROJECT_ID/roles/ROLE2"));
    }

    @Test
    public void testToStringFormat() throws Exception {
        final Roles roles = readObjectFromResource("/project/project-roles.json", Roles.class);

        assertThat(roles.toString(), matchesPattern(Roles.class.getSimpleName() + "\\[.*\\]"));
    }
}


text:
/**
 * region.empty( )
 *
 * Iterate over each component in this region and call .close() on it
 */
module.exports = function empty() {
	FRAMEWORK.debug(this.parent.id + ' :: Emptying region: ' + this.id);
	while (this._children.length > 0) {
		this.remove(0);
	}
};


text:
layout: page
title: Munoz Sub Networks Dinner
date: 2016-05-24
author: Carl Arias
tags: weekly links, java
status: published
summary: Lorem ipsum dolor sit amet, consectetur.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 06/06/2019
  endDate: 06/07/2019
  ctyhocn: LACOLHX
  groupCode: MSND
published: true
---
Phasellus leo turpis, lobortis eu sapien vel, pharetra varius enim. Donec volutpat lacus vel est semper, id mattis est pretium. Nullam nec eros non nisl venenatis fringilla nec at purus. Donec suscipit odio et lorem convallis, in convallis libero tempus. In et egestas enim. Integer tincidunt nibh massa, at sodales tellus malesuada in. Duis ac arcu tortor. Vivamus vehicula sapien tempor, rutrum lorem nec, finibus nisl. Morbi at arcu velit. Praesent efficitur nisi nisi, vitae facilisis arcu molestie tempor. Ut vitae rhoncus magna. Maecenas et luctus ex, ac tristique ex. Quisque molestie justo quis nibh hendrerit egestas. Pellentesque purus arcu, egestas at condimentum ac, congue at libero. Aenean at metus at mi dapibus porttitor.
Aenean accumsan ac lorem eu ultrices. Etiam pellentesque risus fermentum scelerisque gravida. Aliquam leo tellus, fermentum at tortor nec, tempus iaculis arcu. Ut at dictum neque, non laoreet odio. Cras vulputate pellentesque ante quis aliquet. Morbi commodo velit a efficitur tincidunt. Integer eget mauris varius, malesuada lectus vel, sagittis mauris. Curabitur dignissim feugiat sem eu vulputate.

* Vestibulum commodo odio at est gravida laoreet.

Etiam ac purus ornare, pretium justo a, lacinia magna. Mauris porttitor nisi et est blandit rhoncus. Nulla tristique dolor at posuere tincidunt. Morbi mollis pretium nunc in gravida. Pellentesque odio augue, sodales at varius sed, gravida at sem. Vestibulum at dui massa. Quisque eu ligula nunc. Curabitur luctus, elit quis interdum consectetur, lorem ante tincidunt lorem, eu dapibus sem est sed eros. Quisque et imperdiet turpis. Nulla sit amet accumsan quam, sed viverra sem. Nunc eget velit non tortor euismod molestie quis et erat.


text:
Boost for Heroku
================

Boost for Heroku is a simple app for scaling Heroku dynos from an iOS device.
I created it because managing Heroku apps from a mobile browser is nearly
impossible due to the dashboard interface.

**Update:** Since releasing this app, Heroku seems to have made it much easier to use their website on mobile devices. The problems with trying to move the dyno slider seem to have been remedied.

<img src="https://raw.githubusercontent.com/mgartner/boost/master/screenshots/iOS%20Simulator%20Screen%20shot%20Oct%2017,%202013%204.56.16%20PM.png" alt="Boost" width="380px"/>

I built Boost with [RubyMotion](http://www.rubymotion.com/).

If you have a RubyMotion license you can build the app yourself. If not,
the app is available for free in the [App Store](https://itunes.apple.com/US/app/id728159221).

I blogged about the app [here](http://www.marcusgartner.com/blog/2013/10/27/boost-for-heroku/).

Please feel free to ping me with any questions or comments about the app.


text:
package instagram

import (
	"fmt"
	"net/url"
)

// CommentsService handles communication with the comments related
// methods of the Instagram API.
//
// Instagram API docs: http://instagram.com/developer/endpoints/comments/
type CommentsService struct {
	client *Client
}

// Comment represents a comment on Instagram's media.
type Comment struct {
	CreatedTime int64  `json:"created_time,string,omitempty"`
	Text        string `json:"text,omitempty"`
	From        *User  `json:"from,omitempty"`
	ID          string `json:"id,omitempty"`
}

// MediaComments gets a full list of comments on a media.
//
// Instagram API docs: http://instagram.com/developer/endpoints/comments/#get_media_comments
func (s *CommentsService) MediaComments(mediaID string) ([]Comment, error) {
	u := fmt.Sprintf("media/%v/comments", mediaID)
	req, err := s.client.NewRequest("GET", u, "")
	if err != nil {
		return nil, err
	}

	comments := new([]Comment)
	_, err = s.client.Do(req, comments)
	return *comments, err
}

// Add a comment on a media.
//
// Instagram API docs: http://instagram.com/developer/endpoints/comments/#post_media_comments
func (s *CommentsService) Add(mediaID string, text []string) error {
	u := fmt.Sprintf("media/%v/comments", mediaID)
	params := url.Values{
		"text": text,
	}

	req, err := s.client.NewRequest("POST", u, params.Encode())
	if err != nil {
		return err
	}

	_, err = s.client.Do(req, nil)
	return err
}

// Delete a comment either on the authenticated user's media or authored by
// the authenticated user.
//
// Instagram API docs: http://instagram.com/developer/endpoints/comments/#delete_media_comments
func (s *CommentsService) Delete(mediaID, commentID string) error {
	u := fmt.Sprintf("media/%v/comments/%v", mediaID, commentID)
	req, err := s.client.NewRequest("DELETE", u, "")
	if err != nil {
		return err
	}

	_, err = s.client.Do(req, nil)
	return err
}


text:
树莓派自动发送IP到邮箱

`sudo vi send_ip.py`

```
#!/usr/bin/env python3
#-*-coding: utf-8-*-
import socket
import time
import smtplib
import urllib.request
from email.mime.text import MIMEText
from email.header import Header

def sendEmail(smtpserver,username,password,sender,receiver,subject):
        message = MIMEText(subject, '', 'utf-8')
        message['From'] = Header(sender, 'utf-8')
        message['To'] =  Header(','.join(receiver), 'utf-8')
        subject = 'pi ipaddr'
        message['Subject'] = Header(subject, 'utf-8')

        try:
            smtpObj = smtplib.SMTP()
            smtpObj.connect(smtpserver, 25)
            smtpObj.login(username,password)
            smtpObj.sendmail(sender, receiver, message.as_string())
            print("Yes")
        except Exception as err:
            print(err)
        finally:
            print("end!")

def check_network():
        while True:
            try:
                result=urllib.request.urlopen('http://baidu.com').read()
                # print(result)
                print("Network is Ready!")
                break
            except Exception as e:
                print(e)
                print("Network is not ready,Sleep 5s...")
                time.sleep(5)
        return True

def get_ip_address():
        s =socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(("8.8.8.8",80))
        ipaddr=s.getsockname()[0]
        s.close()
        return ipaddr

if  __name__ == '__main__' :
        time.sleep(120)
        check_network()
        ipaddr= get_ip_address()
        print(ipaddr)
        sendEmail("smtp.exmail.qq.com",'pi@xxx.cn','password','pi@xxx.cn',['youremail@xxx.cn'],'IP Address of Raspberry PI:' + ipaddr)
```

`sudo chmod 777 ./send_ip.py`

修改 rc.local

`sudo vi /etc/rc.local`

```
su pi -c "exec /send_ip.py"
exit 0
```

需要开机等待两分钟保证已经获取到IP.


text:
module Foursquared
  # Error class
  class Error < StandardError
    attr_reader :code, :type, :detail
    def initialize meta
      @code = meta["code"]
      @detail = meta["errorDetail"]
      @type = meta["errorType"]
    end

    # Error message to be displayed on encountering Foursquare::Error
    def message
      "#{type}: #{detail} (#{code})"
    end
    alias :to_s :message
  end
end


text:
% Get feedback from a module, log in the background, and plot offline.
%
% Assumes that you have a group created with at least 1 module in it.
%
% HEBI Robotics
% June 2018

%% Setup
clear *;
close all;
HebiLookup.initialize();

% Use Scope to change select a module and change the name and family to
% match the names below.  Following examples will use the same names.
familyName = 'Test Family';
moduleNames = 'Test IO Board';
group = HebiLookup.newGroupFromNames( familyName, moduleNames );

%% Visualize analog input a1
disp('  We need to come up with something fun for the I/O Board...');

% Start logging in the background
group.startLog( 'dir', 'logs' );

figure(1);
clf;

duration = 10; % [sec]
timer = tic();
while toc(timer) < duration

   % Read feedback
   fbk = group.getNextFeedbackIO();

   % Display
   bar( fbk.a1 );

   % Format plot
   yAxisMaxLim = 5;
   yAxisMinLim = -5;
   ylim([yAxisMinLim yAxisMaxLim]);
   title( 'Module Output Velocity' );
   ylabel( 'Angular Velocity (rad/sec)');
   grid on;
   drawnow;

end

disp('  All done!');

% Stop background logging
log = group.stopLogIO();

%% Plot the logged feedback
figure(101);
plot(log.time,log.a1);
title('Pin a1');
xlabel('time (sec)');
ylabel('value');
grid on;


text:
A simple database agnostic JavasScript object modeling and validation library.

## Instalation

`npm install --save schemerjs`

## Basic Example:

```javascript
const Schema = require("schemerjs").Schema;
const rules = require("schemerjs").rules;

let User = new Schema({
  firstname: "string",
  lastname: "string",
  bio: {
    type: "string",
    optional: true,
    rules: [
      rules.max(150)
    ]
  }
});

let fakeUser = {
  firstname: "John",
  lastname: "Doe",
  bio: "A generic person"
}

let result = User.validate(fakeUser);

console.log(result) // {isValid: true, invalidProps: [], reasons: {}}
```

## Schema Definition:

Each property definition takes the following syntax:

```javascript
let example = new Schema({
  propName: {
    type: ["string"],
    optional: true,
    rules: [],
    subRules: []
  }
});
```

Where `propName` is the property to be validated. If the object being validated
has a property not defined in the schema, the object is considered to be
invalid.

If all you care about is the key name and type you can use the shorthand
syntax like this:

```javascript
let example = new Schema({
  keyName: "number"
});
```

## Schema Property Constraints:

(The constraints that go inside of the the property definition)

### type `String`

The type the property must be.

##### Valid types:

- `"string"`
- `"number"`
- `"boolean"`
- `"array"`
- `"object"`
- `"date"`
- `"math"`
- `"regexp"`
- `"json"`
- `"error"`

For a property of an unspecified type use `"any"`. To specify an array of a
certain type use the syntax: `["type"]` (Note that the array is itself not a
string).

You can also set the type to another SchemerJS schema:

```javascript
  let SubSchema = new Schema({
    bar: {
      type: "string"
    }
  });

  let TopSchema = new Schema({
    foo: {
      type: SubSchema
    },
    arrayofsubschema: {
      type: [SubSchema]
    }
  });
```

### optional `Boolean`

A boolean representing whether the property is needed for the object to be
considered valid. defaults to false.

### rules `[functions]`

An array of functions that return either a `Boolean` or an `Error`. The object
being validated is considered to be invalid if the any of the functions return false
or an Error. The error.message is listed as a reason for failure if specified. Each
rule function is called as rule(propertyVal, proptertyDefinition.type)

##### Example:

```javascript
let ruleFunc = function(val, type) {
    // type == "string" (not used)
    // returns an error if val !== "world"
    if (val !== "world") {
      return new Error("does not equal world");
    }
};

let Example = new Schema({
  hello: {
    type: "string",
    rules: [
      ruleFunc // Note the we do not call ruleFunc here i.e. don't do ruleFunc()
    ]
  }
});

let pass = Example.validate({hello: "world"}); // isValid == true
let fail = Example.validate({hello: "universe"}); // isValid == false
```

### subRules `[functions]`

Sub-rules are like regular rules except they are run on each value of an array.

## Schema Functions:

### validate `Schema.validate(object)`

Returns an object with the following properties:

- isValid `Boolean`
- invalidProps `["string"]`
- reasons `"Object" // error messages for each of the invalidProps`

### getRequiredProps `Schema.getRequiredProps()`

Returns an `Array` of all the props needed for an object validated with this
schema definition to be considered valid.

## Predefined rules:

SchemerJS comes with a few predefined rules for convenience.

- min
- max
- regex

Usage:

```javascript
const Schema = require("schemerjs").Schema;
const rules = require("schemerjs").rules;

let Example = new Schema({
  hello: {
    type: "string",
    rules: [
      rules.min(1), // We use () because these functions return another function
      rules.max(6),
      rules.regex(/world/)
    ]
  }
});
```

### min `min(num)`

Takes a `Number` and returns a `Function`. The function that min returns can be
passed a `Number` `String` or `Array`. With a `Number` the function returns an
`Error` if the value the function is given is less than the number passed to
min. With a `String` or an `Array` the function returns an `Error` if the the
value.length the function is given is less than the number passed to min.

Usage:

```javascript
const rules = require("schemerjs").rules;

let atLeastFive = rules.min(5);

let passNum = atLeastFive(7); // returns undefined
let failNum = atLeastFive(2); // returns an Error
let passStr = atLeastFive('abcdefg'); // returns undefined
let failStr = atLeastFive('abc'); //returns an Error
let passArr = atLeastFive([1,2,3,4,5,6])// returns undefined
let failArr = atLeastFive([1,2,3])// returns an Error
```

### max `max(num)`

Takes a `Number` and returns a `Function`. The function that max returns can be
passed a `Number` `String` or `Array`. With a `Number` the function returns an
`Error` if the value the function is given is greater than the number passed to
max. With a `String` or an `Array` the function returns an `Error` if the the
value.length the function is given is greater than the number passed to max.

Usage:

```javascript
const rules = require("schemerjs").rules;

let atMostFive = rules.max(5);

let passNum = atMostFive(2); // returns undefined
let failNum = atMostFive(7); // returns an Error
let passStr = atMostFive('abc'); // returns undefined
let failStr = atMostFive('abcdefg'); //returns an Error
let passArr = atMostFive([1,2,4])// returns undefined
let failArr = atMostFive([1,2,3,4,5,6])// returns an Error
```

### regex `regex(regExp)`

Takes a regular expression and returns a `Function`. The function that regex
returns can be passed a `String`. If this `String` does not pass the regex test
it returns an error

Usage:

```javascript
const rules = require("schemerjs").rules;

let onlyWorld = rules.regex(/world/);

let pass = onlyWorld("world"); // returns undefined
let fail = onlyWorld("hello"); // returns an Error
```


text:
package com.github.devicehive.websocket.model.repsonse;

import com.github.devicehive.rest.model.Device;
import com.google.gson.annotations.SerializedName;

import java.util.List;

public class DeviceListResponse extends ResponseAction {
    @SerializedName("devices")
    private List<Device> devices;

    public List<Device> getDevices() {
        return devices;
    }

    public void setDevices(List<Device> devices) {
        this.devices = devices;
    }

    @Override
    public String toString() {
        return "{\n\"DeviceListResponse\":{\n"
                + "\"status\":\"" + getStatus() + "\""
                + ",\n \"devices\":" + devices
                + ",\n \"action\":\"" + getAction() + "\""
                + ",\n \"requestId\":\"" + getRequestId() + "\""
                + "}\n}";
    }
}


text:
var express = require('express'),
    app = express(),
    port = process.env.PORT || <%= port %>;

var http = require('http');
var fs = require('fs');

var server = http.createServer(app);

// jdebug-server
require('jdebug-server')(app, server);
// static files handler
app.use(express.static(__dirname));
// jdebug-server
app.jDebugServer();
// for any other requests
app.get('*', function (req, res, next) {
    res.sendFile(__dirname + '/index.html');
});

server.listen(port);
console.log('Server listening on port: ' + port);


text:
// This file is automatically generated.

package adila.db;

/*
 * Samsung Galaxy S6
 *
 * DEVICE: zerofltespr
 * MODEL: SM-G920P
 */
final class zerofltespr {
    public static final String DATA = "Samsung|Galaxy S6|Galaxy S";
}


text:
@interface XHHPhotoListViewController ()
@property (weak, nonatomic) IBOutlet UILabel *labelInfo;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *activityView;
@property (weak, nonatomic) IBOutlet ADBannerView *adBannerView;
@property NSMutableData* _responseData;
@property NSString* startId;
@property int pageFatched;
@end

@implementation XHHPhotoListViewController

-(void) updateUISize
{
    CGPoint center = CGPointMake(self.view.bounds.size.width / 2,self.view.bounds.size.height/ 2);

    [self.labelInfo setCenter:center];
    center.y -= 60;
    [self.activityView setCenter:center];
    center.y = self.view.bounds.size.height - self.adBannerView.frame.size.height/2;
    [self.adBannerView setFrame:self.view.bounds];
    [self.adBannerView setCenter:center];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self updateUISize];

    self.pageFatched = 0;
    self.startId = nil;
    self.labelInfo.text = [@"Fetching image list of " stringByAppendingString:self.board];

    self.photos = [[NSMutableArray alloc] init];

    [self fetchImgList];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self updateUISize];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
    [self updateUISize];
}

-(void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
}

-(void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self updateUISize];
}

-(void) fetchImgList
{
    NSString *pageURL = [@"https://bbs.sjtu.edu.cn/bbsfdoc2?board=" stringByAppendingString:self.board ];

    if(self.startId != nil) {
        pageURL = [NSString stringWithFormat:@"%@&start=%@", pageURL, self.startId];
    }

    // Create the request.
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:pageURL]];
    if(self.startId != nil) {
        [request  setCachePolicy:  NSURLRequestReturnCacheDataElseLoad];
    }

    // Create url connection and fire request
    [NSURLConnection connectionWithRequest:request delegate:self];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
  if ([[segue identifier] isEqualToString:@"toImageViewSegue"]) {

      [self.photos sortUsingComparator:^NSComparisonResult(NSString* obj1, NSString* obj2) {
          return [obj2 compare:obj1
                  ];
      }];

      XHHViewController *vc = (XHHViewController*)[[segue.destinationViewController viewControllers] objectAtIndex:0];
    vc.photos = [[NSMutableArray alloc] init];
    for (NSString* photo in self.photos) {

        XHHImageInfo *ii = [[XHHImageInfo alloc] init];
        [ii setImageUrl:photo];
        [vc.photos addObject:ii];
    }
  }
}

-(void) onDownloaded:(NSString*)rawHTML {
    self.pageFatched ++;
    [self extractImages:rawHTML];
    [self extractPreviousStartId:rawHTML];
    self.labelInfo.text = [self.labelInfo.text stringByAppendingString: @"."];

    if(self.pageFatched < 5 && self.startId != nil) {
        [self fetchImgList];
    } else {
        [self performSegueWithIdentifier:@"toImageViewSegue" sender:self] ;
    }
}

-(void) extractImages:(NSString*)rawHTML
{
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(<a href=(.*?(jpg|gif|png)) target)+?"
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];

    NSArray *matches = [regex matchesInString:rawHTML
                                      options:0
                                        range:NSMakeRange(0, [rawHTML length])];

    NSLog(@"total matches %d",[matches count]);

    for (NSTextCheckingResult *match in matches) {
        NSString *img = [rawHTML substringWithRange:[match rangeAtIndex:2]] ;
       // NSLog(@"%@",img);
        // add image to the array
        [self.photos addObject:img];
    }
}

-(void) extractPreviousStartId:(NSString*)rawHTML
{
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"start=([^>]+)>上一页"
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];

    NSArray *matches = [regex matchesInString:rawHTML
                                      options:0
                                        range:NSMakeRange(0, [rawHTML length])];

    self.startId = nil;
    for (NSTextCheckingResult *match in matches) {
        self.startId  = [rawHTML substringWithRange:[match rangeAtIndex:1]];
    }
}

#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    self._responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [self._responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    // Cache pages only with start parameter
    NSString* url = [connection.currentRequest.URL absoluteString];
    if ( [url rangeOfString:@"start="].location == NSNotFound)
        return nil;
    return cachedResponse;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSString *rawHTML = [[NSString alloc]initWithData:self._responseData encoding:enc];
    [self onDownloaded:rawHTML];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
}

@end


text:
define({
  "commonWebmap": {
    "selector": {
      "lblWebMap": "Mapa",
      "lblLocation": "Local",
      "lblContent": "Conteúdo",
      "lblPopup": "Janela Pop-up",
      "lblControls": "Extras",
      "lblOverview": "Vista Geral do Mapa",
      "lblLegend": "Legenda",
      "lblGeocoder": "Localizador (Finder) de Endereços, Locais e Elementos",
      "tooltipGeocoder": "Permita que os seus leitores procurem endereços, locais e/ou elementos no seu mapa. As opções de pesquisa podem ser configuradas na página do item de um mapa web, em Definições > Mapa Web > Aplicação > Encontrar Locais.",
      "lblEsriGeocoder": "World Placefinder",
      "loadingTitle": "Carregando título",
      "entry": "Entrada",
      "entries": "Entradas",
      "section": "Secção",
      "sections": "Secções",
      "and": "e",
      "action": "Ação na secção",
      "actions": "Ação nas secções",
      "originalWebmap": "Mapa utilizado para publicar o %TPL_NAME%",
      "browseMaps": "Selecionar um mapa",
      "createMap": "Criar um mapa",
      "noResults": "Não foram encontrados resultados",
      "loadingResults": "A carregar...",
      "current": "Mapa atual",
      "select": "Selecionar ou criar um mapa",
      "newMap": "Mapa web recém-selecionado",
      "newCreatedMap": "Mapa web recém-criado",
      "webmapDefault": "Padrão de mapa",
      "customCfg": "Configuração personalizada",
      "tooltipLocation": "Defina a localização em que o mapa exibido.",
      "tooltipContent": "Definir as camadas visíveis.",
      "tooltipPopup": "Escolher um pop-up que irá ser aberto quando este mapa for exibido.",
      "tooltipOverview": "Exiba um pequeno mapa de vista geral juntamente com o mapa principal.",
      "tooltipLegend": "Exiba a legenda de mapa no mapa, útil quando o mapa tem muitas camadas e símbolos.",
      "mapCfgInvite": "Utilize estes controlos para configurar o seu mapa",
      "lblLocationAlt": "Herdado do primeiro mapa",
      "tooltipLocationAlt": "A localização deste mapa é sincronizada para o primeiro mapa da série. Para alterar este comportamento para a sua série, vá a Definições > Opções de Mapa."
    },
    "configure": {
      "btnReset": "Repor definições padrão",
      "btnCancel": "Cancelar",
      "tocTitle": "Conteúdo do mapa",
      "tocExplain": "Escolha as camadas que serão exibidas.",
      "tocNoData": "Nenhuma camada pode ser configurada.",
      "tocSave": "Guardar conteúdo do mapa",
      "extentTitle": "Localização do Mapa",
      "extentExplain": "Mova e amplie o mapa para definir como este aparecerá aos leitores.",
      "extentSave": "Guardar localização do Mapa",
      "popupTitle": "Mapa pop-up",
      "popupExplain": "Clique num elemento para abrir o pop-up que pretende exibir.",
      "popupSave": "Guarde a configuração pop-up",
      "hintNavigation": "Navegação no mapa desativada."
    },
    "editor": {
      "loading": "Por favor aguarde enquanto o editor de mapas está a carregar",
      "newTitle": "Criar um novo mapa",
      "editTitle": "Editar mapa",
      "titleLbl": "Título",
      "titlePh": "Título do mapa...",
      "folderLbl": "O mapa será criado no mesmo mapa que a história.",
      "creating": "A criar o mapa",
      "saving": "A guardar o mapa",
      "success": "Mapa guardado",
      "successCreate": "Mapa criado",
      "cancelTitle": "Rejeitar alterações não guardadas?",
      "close": "Fechar",
      "save": "Guardar",
      "confirm": "Sim, fechar mapa",
      "deny": "Não, continuar a trabalhar",
      "errorDuplicate": "Já existe um mapa com esse título.",
      "errorCreate": "Impossível criar mapa. Por favor, tente novamente.",
      "errorSave": "Não é possível guardar mapa. Por favor, tente novamente.",
      "notavailable1": "Lamentamos, criar ou editar um mapa não é suportado no Firefox devido a uma limitação técnica. Poderá querer construir a sua história utilizando outro navegador web ou optar pela seguinte resolução alternativa.",
      "notavailable2": "Lamentamos, criar ou editar um mapa não é suportado porque a aplicação do story map não se encontra alojada em %PRODUCT%. Por favor contacte o seu administrador ArcGIS para obter mais informações.",
      "notavailable3": "Lamentamos, criar ou editar um mapa não é suportado nesta versão do Portal for ArcGIS (requer a versão 10.4 ou posterior). Por favor contacte o seu administrador ArcGIS para obter mais informações.",
      "notavailable4": "Pode criar um mapa utilizando %MV%, e depois regressar aqui para o adicionar à sua história.",
      "notavailable5": "Pode criar um mapa utilizando %MV%, e depois regressar aqui e %apply% para ver as alterações.",
      "notavailable6": "visualizador de mapas",
      "notavailable7": "recarregar o mapa"
    }
  },
  "configure": {
    "mapdlg": {
      "items": {
        "organizationLabel": "A Organização",
        "onlineLabel": "ArcGIS Online",
        "contentLabel": "O Meu Conteúdo",
        "favoritesLabel": "Os Meus Favoritos"
      },
      "title": "Selecionar um mapa",
      "searchTitle": "Pesquisar",
      "ok": "OK",
      "cancel": "Cancelar",
      "placeholder": "Introduza termo de pesquisa ou a ID de mapa web..."
    }
  }
});


text:
package org.apache.ivyde.internal.eclipse;

import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.ClasspathVariableInitializer;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;

public class IvyDEClasspathVariableInitializer extends ClasspathVariableInitializer {

    public static final String IVY_HOME_VARIABLE = "IVY_HOME";

    public void initialize(String variable) {
        try {
            JavaCore.setClasspathVariable(IVY_HOME_VARIABLE, new Path(System
                    .getProperty("user.home")).append(".ivy2"), null);
        } catch (JavaModelException e) {
            IvyPlugin.log(e);
        }
    }

}


text:
<?php

namespace Aws\Redshift\Exception;

/**
 * The specified reserved compute node not found.
 */
class ReservedNodeNotFoundException extends RedshiftException {}