text:
/**
 * @author Alexei Y. Zakharov
 * @version $Revision: 1.1.2.4 $
 */

package org.apache.harmony.jndi.provider.dns;

import java.util.Vector;
import java.util.Enumeration;

import org.apache.harmony.jndi.internal.nls.Messages;

/**
 * This class represents a domain protocol message.
 *
 * @author Alexei Zakharov
 * @version $Revision: 1.1.2.4 $
 * @see RFC 1035
 */
public class Message {

    // header section fields

    /** an ID */
    private int id = 0;

    /** QR; false stands for QUERY request, true for RESPONSE */
    private boolean qr = ProviderConstants.QR_QUERY;

    /** OPCODE; QUERY or IQUERY or STATUS */
    private int opCode = 0;

    /** AA, Authoritative Answer*/
    private boolean aa = false;

    /** TC, TrunCation */
    private boolean tc = false;

    /** RD, Recursion Desired */
    private boolean rd = false;

    /** RA, Recursion Available */
    private boolean ra = false;

    /** Z, always should be zero */
    //private int z;

    /** RCODE, Response CODE */
    private int rCode = 0;

    /** QDCOUNT, number of records in question section */
    private int qdCount = 0;

    /** ANCOUNT, number of records in answer section */
    private int anCount = 0;

    /** NSCOUNT, number of records in authority records section */
    private int nsCount = 0;

    /** ARCOUNT, number of records in additional section */
    private int arCount = 0;

    private Vector<QuestionRecord> questionRecords = null;
    private Vector<ResourceRecord> answerRRs = null;
    private Vector<ResourceRecord> authorityRRs = null;
    private Vector<ResourceRecord> additionalRRs = null;

    /** */
    public Message() {
        questionRecords = new Vector<QuestionRecord>();
        answerRRs = new Vector<ResourceRecord>();
        authorityRRs = new Vector<ResourceRecord>();
        additionalRRs = new Vector<ResourceRecord>();
    }

    /**
     * Constructs Message object from given parameters
     *
     * @param id ID
     * @param qr QR
     * @param opCode OPCODE
     * @param aa AA
     * @param tc TC
     * @param rd RA
     * @param ra RA
     * @param rCode RCODE
     * @param qdCount QDCOUNT
     * @param anCount ANCOUNT
     * @param nsCount NSCOUNT
     * @param arCount ARCOUNT
     */
    public Message(
            int id,
            boolean qr,
            int opCode,
            boolean aa,
            boolean tc,
            boolean rd,
            boolean ra,
            int rCode,
            int qdCount,
            int anCount,
            int nsCount,
            int arCount)
    {
        this.id = id;
        this.qr = qr;
        this.opCode = opCode;
        this.aa = aa;
        this.tc = tc;
        this.rd = rd;
        this.ra = ra;
        this.rCode = rCode;
        this.qdCount = qdCount;
        this.anCount = anCount;
        this.nsCount = nsCount;
        this.arCount = arCount;
        questionRecords = new Vector<QuestionRecord>();
        answerRRs = new Vector<ResourceRecord>();
        authorityRRs = new Vector<ResourceRecord>();
        additionalRRs = new Vector<ResourceRecord>();
    }

    /**
     * Generates sequence of bytes that represents the message.
     *
     * @param buffer the buffer to write bytes into
     * @param startIdx the index of buffer to start writing at
     * @return updated index of the buffer
     * @throws DomainProtocolException if something went wrong
     */
    public int writeBytes(byte[] buffer, int startIdx)
            throws DomainProtocolException
    {
        int idx = startIdx;
        int tmp = 0;

        // basic check
        if (buffer == null) {
            // jndi.32=buffer is null
            throw new DomainProtocolException(Messages.getString("jndi.32")); //$NON-NLS-1$
        }
        // ID
        idx = ProviderMgr.write16Int(id, buffer, idx);
        // QR
        tmp = ProviderMgr.setBit(tmp, ProviderConstants.QR_MASK, qr);
        // OPCODE
        tmp &= ~ProviderConstants.OPCODE_MASK;
        tmp |= (opCode & 0xf) << ProviderConstants.OPCODE_SHIFT;
        // AA
        tmp = ProviderMgr.setBit(tmp, ProviderConstants.AA_MASK, aa);
        // TC
        tmp = ProviderMgr.setBit(tmp, ProviderConstants.TC_MASK, tc);
        // RD
        tmp = ProviderMgr.setBit(tmp, ProviderConstants.RD_MASK, rd);
        // RA
        tmp = ProviderMgr.setBit(tmp, ProviderConstants.RA_MASK, ra);
        // Z, drop all those bits
        tmp &= ~ProviderConstants.Z_MASK;
        // RCODE
        tmp &= ~ProviderConstants.RCODE_MASK;
        tmp |= (rCode & 0xf) << ProviderConstants.RCODE_SHIFT;
        // write to buffer
        idx = ProviderMgr.write16Int(tmp, buffer, idx);
        // QDCOUNT
        idx = ProviderMgr.write16Int(qdCount, buffer, idx);
        // ANCOUNT
        idx = ProviderMgr.write16Int(anCount, buffer, idx);
        // NSCOUNT
        idx = ProviderMgr.write16Int(nsCount, buffer, idx);
        // ARCOUNT
        idx = ProviderMgr.write16Int(arCount, buffer, idx);
        // question section
        for (int i = 0; i < questionRecords.size(); i++) {
            QuestionRecord qr = questionRecords.elementAt(i);

            idx = qr.writeBytes(buffer, idx);
        }
        // answer section
        for (int i = 0; i < answerRRs.size(); i++) {
            ResourceRecord rr = answerRRs.elementAt(i);

            idx = rr.writeBytes(buffer, idx);
        }
        // authority section
        for (int i = 0; i < authorityRRs.size(); i++) {
            ResourceRecord rr = answerRRs.elementAt(i);

            idx = rr.writeBytes(buffer, idx);
        }
        // additional section
        for (int i = 0; i < additionalRRs.size(); i++) {
            ResourceRecord rr = answerRRs.elementAt(i);

            idx = rr.writeBytes(buffer, idx);
        }
        return idx;
    }

    /**
     * Parses given sequence of bytes and constructs a message object from it.
     *
     * @param mesBytes the byte array that should be parsed
     * @param startIdx an index of mesBytes array to start the
     *  parsing at
     * @param mes an object to write a result to, should already be created
     * @return updated index of mesBytes array
     * @throws DomainProtocolException if some error has occured
     */
    public static int parseMessage(byte[] mesBytes, int startIdx,
            Message mesObj) throws DomainProtocolException
    {
        int idx = startIdx;
        int tmp, tmp2;
        int qdCnt;
        int anCnt;
        int nsCnt;
        int arCnt;

        if (mesObj == null) {
            // jndi.58=The value of parameter mesObj is null
            throw new DomainProtocolException(Messages.getString("jndi.58")); //$NON-NLS-1$
        }
        // header section
        // ID
        mesObj.setId(ProviderMgr.parse16Int(mesBytes, idx));
        idx += 2;
        // QR & opCode & AA & TC & RD & RA & Z & rCode
        tmp = ProviderMgr.parse16Int(mesBytes, idx);
        idx += 2;
        // QR
        mesObj.setQR(ProviderMgr.checkBit(tmp, ProviderConstants.QR_MASK));
        // OPCODE
        tmp2 = (tmp & ProviderConstants.OPCODE_MASK)
                        >> ProviderConstants.OPCODE_SHIFT;
        mesObj.setOpCode(tmp2);
        // AA
        mesObj.setAA(ProviderMgr.checkBit(tmp, ProviderConstants.AA_MASK));
        // TC
        mesObj.setTc(ProviderMgr.checkBit(tmp, ProviderConstants.TC_MASK));
        // RD
        mesObj.setRD(ProviderMgr.checkBit(tmp, ProviderConstants.RD_MASK));
        // RA
        mesObj.setRA(ProviderMgr.checkBit(tmp, ProviderConstants.RA_MASK));
        // RCODE
        tmp2 = (tmp & ProviderConstants.RCODE_MASK)
                        >> ProviderConstants.RCODE_SHIFT;
        mesObj.setRCode(tmp2);
        // QDCOUNT
        qdCnt = ProviderMgr.parse16Int(mesBytes, idx);
        mesObj.setQDCount(qdCnt);
        idx += 2;
        // ANCOUNT
        anCnt = ProviderMgr.parse16Int(mesBytes, idx);
        mesObj.setANCount(anCnt);
        idx += 2;
        // NSCOUNT
        nsCnt = ProviderMgr.parse16Int(mesBytes, idx);
        mesObj.setNSCount(nsCnt);
        idx += 2;
        // ARCOUNT
        arCnt = ProviderMgr.parse16Int(mesBytes, idx);
        mesObj.setARCount(arCnt);
        idx += 2;
        // question section
        for (int i = 0; i < qdCnt; i++) {
            QuestionRecord qr = new QuestionRecord();
            idx = QuestionRecord.parseRecord(mesBytes, idx, qr);
            mesObj.addQuestionRecord(qr);
        }
        // answer section
        for (int i = 0; i < anCnt; i++) {
            ResourceRecord rr = new ResourceRecord();
            idx = ResourceRecord.parseRecord(mesBytes, idx, rr);
            mesObj.addAnswerRR(rr);
        }
        // authority section
        for (int i = 0; i < nsCnt; i++) {
            ResourceRecord rr = new ResourceRecord();
            idx = ResourceRecord.parseRecord(mesBytes, idx, rr);
            mesObj.addAuthorityRR(rr);
        }
        // additional section
        for (int i = 0; i < arCnt; i++) {
            ResourceRecord rr = new ResourceRecord();
            idx = ResourceRecord.parseRecord(mesBytes, idx, rr);
            mesObj.addAdditionalRR(rr);
        }
        return idx;
    }

    /**
     * @return string representation of this message
     */
    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer();

        sb.append("ID=" + id + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        if (qr) {
            sb.append(" QR"); //$NON-NLS-1$
        }
        sb.append(" OPCODE=" + opCode); //$NON-NLS-1$
        if (aa) {
            sb.append(" AA"); //$NON-NLS-1$
        }
        if (tc) {
            sb.append(" TC"); //$NON-NLS-1$
        }
        if (rd) {
            sb.append(" RD"); //$NON-NLS-1$
        }
        if (ra) {
            sb.append(" RA"); //$NON-NLS-1$
        }
        sb.append(" RCODE=" + rCode); //$NON-NLS-1$
        sb.append("\n"); //$NON-NLS-1$
        sb.append("QDCOUNT=" + qdCount); //$NON-NLS-1$
        for (int i = 0; i < questionRecords.size(); i++) {
            sb.append("\n"); //$NON-NLS-1$
            sb.append(questionRecords.elementAt(i).toString());
        }
        sb.append("\n"); //$NON-NLS-1$
        sb.append(" ANCOUNT=" + anCount); //$NON-NLS-1$
        for (int i = 0; i < answerRRs.size(); i++) {
            sb.append("\n"); //$NON-NLS-1$
            sb.append(answerRRs.elementAt(i).toString());
        }
        sb.append("\n"); //$NON-NLS-1$
        sb.append(" NSCOUNT=" + nsCount); //$NON-NLS-1$
        for (int i = 0; i < authorityRRs.size(); i++) {
            sb.append("\n"); //$NON-NLS-1$
            sb.append(authorityRRs.elementAt(i).toString());
        }
        sb.append("\n"); //$NON-NLS-1$
        sb.append(" ARCOUNT=" + arCount); //$NON-NLS-1$
        for (int i = 0; i < additionalRRs.size(); i++) {
            sb.append("\n"); //$NON-NLS-1$
            sb.append(additionalRRs.elementAt(i).toString());
        }
        return sb.toString();
    }

    // setters and getters

    /**
     * @return Returns the AA.
     */
    public boolean isAA() {
        return aa;
    }
    /**
     * @param aa The AA to set.
     */
    public void setAA(boolean aa) {
        this.aa = aa;
    }
    /**
     * @return Returns the anCount.
     */
    public int getANCount() {
        return anCount;
    }
    /**
     * @param anCount The anCount to set.
     */
    public void setANCount(int anCount) {
        this.anCount = anCount;
    }
    /**
     * @return Returns the arCount.
     */
    public int getARCount() {
        return arCount;
    }
    /**
     * @param arCount The arCount to set.
     */
    public void setARCount(int arCount) {
        this.arCount = arCount;
    }
    /**
     * @return Returns the id.
     */
    public int getId() {
        return id;
    }
    /**
     * @param id The id to set.
     */
    public void setId(int id) {
        this.id = id;
    }
    /**
     * @return Returns the nsCount.
     */
    public int getNSCount() {
        return nsCount;
    }
    /**
     * @param nsCount The nsCount to set.
     */
    public void setNSCount(int nsCount) {
        this.nsCount = nsCount;
    }
    /**
     * @return Returns the opCode.
     */
    public int getOpCode() {
        return opCode;
    }
    /**
     * @param opCode The opCode to set.
     */
    public void setOpCode(int opCode) {
        this.opCode = opCode;
    }
    /**
     * @return Returns the qdCount.
     */
    public int getQDCount() {
        return qdCount;
    }
    /**
     * @param qdCount The qdCount to set.
     */
    public void setQDCount(int qdCount) {
        this.qdCount = qdCount;
    }
    /**
     * @return Returns the QR.
     */
    public boolean getQR() {
        return qr;
    }
    /**
     * @param qr The QR to set.
     */
    public void setQR(boolean qr) {
        this.qr = qr;
    }
    /**
     * @return Returns the RA.
     */
    public boolean isRA() {
        return ra;
    }
    /**
     * @param ra The RA to set.
     */
    public void setRA(boolean ra) {
        this.ra = ra;
    }
    /**
     * @return Returns the rCode.
     */
    public int getRCode() {
        return rCode;
    }
    /**
     * @param code The rCode to set.
     */
    public void setRCode(int code) {
        rCode = code;
    }
    /**
     * @return Returns the RD.
     */
    public boolean isRD() {
        return rd;
    }
    /**
     * @param rd The RD to set.
     */
    public void setRD(boolean rd) {
        this.rd = rd;
    }
    /**
     * @return Returns the TC.
     */
    public boolean isTc() {
        return tc;
    }
    /**
     * @param tc The TC to set.
     */
    public void setTc(boolean tc) {
        this.tc = tc;
    }

    /**
     * @return question records that are contained by the current message.
     */
    public Enumeration<QuestionRecord> getQuestionRecords() {
        return questionRecords.elements();
    }

    /**
     * Adds a new question record to the message.
     * @param qr a record to add
     */
    public void addQuestionRecord(QuestionRecord qr) {
        questionRecords.addElement(qr);
    }

    /**
     * @return available answer resource records
     */
    public Enumeration<ResourceRecord> getAnswerRRs() {
        return answerRRs.elements();
    }

    /**
     * Adds a new question record to the message.
     * @param rr a record to add
     */
    public void addAnswerRR(ResourceRecord rr) {
        answerRRs.addElement(rr);
    }

    /**
     * @return available authority resource records
     */
    public Enumeration<ResourceRecord> getAuthorityRRs() {
        return authorityRRs.elements();
    }

    /**
     * Adds a new question record to the message.
     * @param rr a record to add
     */
    public void addAuthorityRR(ResourceRecord rr) {
        authorityRRs.addElement(rr);
    }

    /**
     * @return available additional resource records
     */
    public Enumeration<ResourceRecord> getAdditionalRRs() {
        return additionalRRs.elements();
    }

    /**
     * Adds a new question record to the message.
     * @param rr a record to add
     */
    public void addAdditionalRR(ResourceRecord rr) {
        additionalRRs.addElement(rr);
    }

}


text:
import sys

def rotate(tile):
    return list(''.join(x[::-1]) for x in zip(*tile))

def flip(tile):
    return list(reversed(tile.copy()))

def build_tile_transformations(tile):
    tile90 = rotate(tile)
    tile180 = rotate(tile90)
    tile270 = rotate(tile180)
    return [tile, tile90, tile180, tile270, flip(tile), flip(tile90), flip(tile180), flip(tile270)]

def get_monster_indexes():
    monster_pattern = [
        '                  # ',
        '#    ##    ##    ###',
        ' #  #  #  #  #  #   '
    ]
    return [(r, c) for r in range(len(monster_pattern)) for c in range(len(monster_pattern[r])) if monster_pattern[r][c] == '#']

def assemble_tiles(tile_transformations):
    n = int(len(tile_transformations)**0.5)
    assembled = [[(0, 0)] * n for _ in range(n)]
    remaining = set(tile_transformations.keys())

    def _assemble_tiles(rowcolumn):
        if rowcolumn == n * n:
            return True
        r, c = rowcolumn // n, rowcolumn % n
        for tileid in list(remaining):
            for i, transformation in enumerate(tile_transformations[tileid]):
                up_ok = left_ok = True
                if r > 0:
                    up_tileid, up_transformation = assembled[r - 1][c]
                    up_tile = tile_transformations[up_tileid][up_transformation]
                    up_ok = all(transformation[0][i] ==
                                up_tile[9][i] for i in range(10))
                if c > 0:
                    left_tileid, left_transformation = assembled[r][c - 1]
                    left_tile = tile_transformations[left_tileid][left_transformation]
                    left_ok = all(
                        transformation[i][0] == left_tile[i][9] for i in range(10))
                if up_ok and left_ok:
                    assembled[r][c] = (tileid, i)
                    remaining.remove(tileid)
                    if _assemble_tiles(rowcolumn + 1):
                        return True
                    remaining.add(tileid)
        return False
    _assemble_tiles(0)

    return assembled

def part1(tile_matrix):
    return tile_matrix[0][0][0] * tile_matrix[0][-1][0] * tile_matrix[-1][0][0] * tile_matrix[-1][-1][0]

def part2(tile_matrix, tile_transformations):
    n = int(len(tile_transformations)**0.5)
    image = [['.'] * (n * 8) for _ in range(n * 8)]

    for r in range(n):
        for c in range(n):
            tileid, transformation = tile_matrix[r][c]
            tile = tile_transformations[tileid][transformation]
            for i in range(1, 9):
                for j in range(1, 9):
                    image[8 * r + i - 1][8 * c + j - 1] = tile[i][j]

    for image in build_tile_transformations(image):
        monster = 0
        for r in range(len(image) - 3):
            for c in range(len(image) - 20):
                if all(image[r + dr][c + dc] == '#' for dr, dc in get_monster_indexes()):
                    monster += 1
        if monster > 0:
            total = sum(row.count('#') for row in image)
            return total - monster * len(get_monster_indexes())

lines = open('20.in').read().splitlines() + ['']

tiles = {}
tileid, matrix = 0, []
for line in lines:
    if not line:
        tiles[tileid] = matrix
        tileid, matrix = 0, []
    elif line.startswith('Tile'):
        tileid = int(line.replace(':', '').split()[1])
    else:
        matrix.append(line)

tile_transformations = {tileid: build_tile_transformations(
    tile) for tileid, tile in tiles.items()}
tile_matrix = assemble_tiles(tile_transformations)

print(
    f'Part 1: {part1(tile_matrix)}, Part 2: {part2(tile_matrix, tile_transformations)}')

redpajama_set_name: RedPajamaGithub


text:
using Parlot;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;

namespace Fluid.Ast
{
    public class CommentStatement : Statement
    {
        private readonly TextSpan _text;

        public CommentStatement(in TextSpan text)
        {
            _text = text;
        }

        public ref readonly TextSpan Text => ref _text;

        public override ValueTask<Completion> WriteToAsync(TextWriter writer, TextEncoder encoder, TemplateContext context)
        {
            context.IncrementSteps();

            return Normal();
        }
    }
}


text:
package com.github.mobile.ui.user;

import static com.actionbarsherlock.app.ActionBar.NAVIGATION_MODE_LIST;
import static com.github.mobile.ui.user.HomeDropdownListAdapter.ACTION_BOOKMARKS;
import static com.github.mobile.ui.user.HomeDropdownListAdapter.ACTION_DASHBOARD;
import static com.github.mobile.ui.user.HomeDropdownListAdapter.ACTION_GISTS;
import static com.github.mobile.util.TypefaceUtils.ICON_FOLLOW;
import static com.github.mobile.util.TypefaceUtils.ICON_NEWS;
import static com.github.mobile.util.TypefaceUtils.ICON_PUBLIC;
import static com.github.mobile.util.TypefaceUtils.ICON_TEAM;
import static com.github.mobile.util.TypefaceUtils.ICON_WATCH;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.view.Window;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.github.mobile.R.id;
import com.github.mobile.R.menu;
import com.github.mobile.accounts.AccountUtils;
import com.github.mobile.core.user.UserComparator;
import com.github.mobile.persistence.AccountDataManager;
import com.github.mobile.ui.TabPagerActivity;
import com.github.mobile.ui.gist.GistsActivity;
import com.github.mobile.ui.issue.FiltersViewActivity;
import com.github.mobile.ui.issue.IssueDashboardActivity;
import com.github.mobile.ui.repo.OrganizationLoader;
import com.github.mobile.util.AvatarLoader;
import com.github.mobile.util.PreferenceUtils;
import com.google.inject.Inject;
import com.google.inject.Provider;

import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.egit.github.core.User;

/**
 * Home screen activity
 */
public class HomeActivity extends TabPagerActivity<HomePagerAdapter> implements
        OnNavigationListener, OrganizationSelectionProvider,
        LoaderCallbacks<List<User>> {

    private static final String TAG = "HomeActivity";

    private static final String PREF_ORG_ID = "orgId";

    @Inject
    private AccountDataManager accountDataManager;

    @Inject
    private Provider<UserComparator> userComparatorProvider;

    private boolean isDefaultUser;

    private List<User> orgs = Collections.emptyList();

    private HomeDropdownListAdapter homeAdapter;

    private Set<OrganizationSelectionListener> orgSelectionListeners = new LinkedHashSet<OrganizationSelectionListener>();

    private User org;

    @Inject
    private AvatarLoader avatars;

    @Inject
    private SharedPreferences sharedPreferences;

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

        getSupportLoaderManager().initLoader(0, null, this);
    }

    private void reloadOrgs() {
        getSupportLoaderManager().restartLoader(0, null,
                new LoaderCallbacks<List<User>>() {

                    @Override
                    public Loader<List<User>> onCreateLoader(int id,
                            Bundle bundle) {
                        return HomeActivity.this.onCreateLoader(id, bundle);
                    }

                    @Override
                    public void onLoadFinished(Loader<List<User>> loader,
                            final List<User> users) {
                        HomeActivity.this.onLoadFinished(loader, users);
                        if (users.isEmpty())
                            return;

                        Window window = getWindow();
                        if (window == null)
                            return;
                        View view = window.getDecorView();
                        if (view == null)
                            return;

                        view.post(new Runnable() {

                            @Override
                            public void run() {
                                isDefaultUser = false;
                                setOrg(users.get(0));
                            }
                        });
                    }

                    @Override
                    public void onLoaderReset(Loader<List<User>> loader) {
                        HomeActivity.this.onLoaderReset(loader);
                    }
                });
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Restart loader if default account doesn't match currently loaded
        // account
        List<User> currentOrgs = orgs;
        if (currentOrgs != null && !currentOrgs.isEmpty()
                && !AccountUtils.isUser(this, currentOrgs.get(0)))
            reloadOrgs();
    }

    private void configureActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setNavigationMode(NAVIGATION_MODE_LIST);

        homeAdapter = new HomeDropdownListAdapter(this, orgs, avatars);
        actionBar.setListNavigationCallbacks(homeAdapter, this);
    }

    private void setOrg(User org) {
        Log.d(TAG, "setOrg : " + org.getLogin());

        PreferenceUtils.save(sharedPreferences.edit().putInt(PREF_ORG_ID,
                org.getId()));

        // Don't notify listeners or change pager if org hasn't changed
        if (this.org != null && this.org.getId() == org.getId())
            return;

        this.org = org;

        boolean isDefaultUser = AccountUtils.isUser(this, org);
        boolean changed = this.isDefaultUser != isDefaultUser;
        this.isDefaultUser = isDefaultUser;
        if (adapter == null)
            configureTabPager();
        else if (changed) {
            int item = pager.getCurrentItem();
            adapter.clearAdapter(isDefaultUser);
            adapter.notifyDataSetChanged();
            createTabs();
            if (item >= adapter.getCount())
                item = adapter.getCount() - 1;
            pager.setItem(item);
        }

        for (OrganizationSelectionListener listener : orgSelectionListeners)
            listener.onOrganizationSelected(org);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu optionMenu) {
        getSupportMenuInflater().inflate(menu.home, optionMenu);

        return super.onCreateOptionsMenu(optionMenu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case id.m_search:
            onSearchRequested();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
        if (homeAdapter.isOrgPosition(itemPosition)) {
            homeAdapter.setSelected(itemPosition);
            setOrg(orgs.get(itemPosition));
        } else if (homeAdapter.getOrgCount() > 0) {
            switch (homeAdapter.getAction(itemPosition)) {
            case ACTION_GISTS:
                startActivity(new Intent(this, GistsActivity.class));
                break;
            case ACTION_DASHBOARD:
                startActivity(new Intent(this, IssueDashboardActivity.class));
                break;
            case ACTION_BOOKMARKS:
                startActivity(FiltersViewActivity.createIntent());
                break;
            }
            int orgSelected = homeAdapter.getSelected();
            ActionBar actionBar = getSupportActionBar();
            if (orgSelected < actionBar.getNavigationItemCount())
                actionBar.setSelectedNavigationItem(orgSelected);
        }
        return true;
    }

    @Override
    public Loader<List<User>> onCreateLoader(int i, Bundle bundle) {
        return new OrganizationLoader(this, accountDataManager,
                userComparatorProvider);
    }

    @Override
    public void onLoadFinished(Loader<List<User>> listLoader, List<User> orgs) {
        this.orgs = orgs;

        if (homeAdapter != null)
            homeAdapter.setOrgs(orgs);
        else
            configureActionBar();

        int sharedPreferencesOrgId = sharedPreferences.getInt(PREF_ORG_ID, -1);
        int targetOrgId = org == null ? sharedPreferencesOrgId : org.getId();

        ActionBar actionBar = getSupportActionBar();
        for (int i = 0; i < orgs.size(); i++)
            if (orgs.get(i).getId() == targetOrgId) {
                actionBar.setSelectedNavigationItem(i);
                break;
            }
    }

    @Override
    public void onLoaderReset(Loader<List<User>> listLoader) {
    }

    @Override
    public User addListener(OrganizationSelectionListener listener) {
        if (listener != null)
            orgSelectionListeners.add(listener);
        return org;
    }

    @Override
    public OrganizationSelectionProvider removeListener(
            OrganizationSelectionListener listener) {
        if (listener != null)
            orgSelectionListeners.remove(listener);
        return this;
    }

    @Override
    protected HomePagerAdapter createAdapter() {
        return new HomePagerAdapter(this, isDefaultUser);
    }

    @Override
    protected String getIcon(int position) {
        switch (position) {
        case 0:
            return ICON_NEWS;
        case 1:
            return ICON_PUBLIC;
        case 2:
            return isDefaultUser ? ICON_WATCH : ICON_TEAM;
        case 3:
            return ICON_FOLLOW;
        default:
            return super.getIcon(position);
        }
    }
}


text:
package sample.secure.oauth2.resource;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.hateoas.MediaTypes;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;

/**
 * Series of automated integration tests to verify proper behavior of auto-configured,
 * OAuth2-secured system
 *
 * @author Greg Turnquist
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SampleSecureOAuth2ResourceApplication.class)
@WebIntegrationTest(randomPort = true)
public class SampleSecureOAuth2ResourceApplicationTests {

	@Autowired
	WebApplicationContext context;

	@Autowired
	FilterChainProxy filterChain;

	private MockMvc mvc;

	@Before
	public void setUp() {
		this.mvc = webAppContextSetup(this.context).addFilters(this.filterChain).build();
		SecurityContextHolder.clearContext();
	}

	@Test
	public void homePageAvailable() throws Exception {
		this.mvc.perform(get("/").accept(MediaTypes.HAL_JSON)).andExpect(status().isOk())
				.andDo(print());
	}

	@Test
	public void flightsSecuredByDefault() throws Exception {
		this.mvc.perform(get("/flights").accept(MediaTypes.HAL_JSON))
				.andExpect(status().isUnauthorized()).andDo(print());
		this.mvc.perform(get("/flights/1").accept(MediaTypes.HAL_JSON))
				.andExpect(status().isUnauthorized()).andDo(print());
	}

	@Test
	public void profileAvailable() throws Exception {
		this.mvc.perform(get("/profile").accept(MediaTypes.HAL_JSON))
				.andExpect(status().isOk()).andDo(print());
	}

}


text:
$.getScript("//static.cottagelabs.com/d3/topojson.v1.min.js");

$.fn.holder.display.map = function(obj) {
  var options = obj.holder.options;

  if ( !$('div.'+options.class+'.world').length ) {
		obj.append('

');
		$('div.'+options.class+'.world').append('\
			<svg class="' + options.class + ' world"></svg>'
		);
	}
  if ( !$('svg.'+options.class+'.world').attr('height') ) {
		var dh = $('div.'+options.class+'.world').height() - ($('svg.'+options.class+'.world').offset().top - $('svg.'+options.class+'.world').parent().offset().top);
    $('svg.'+options.class+'.world').attr('height',dh);
  }
	if ( !$('svg.'+options.class+'.world').attr('width') ) {
		var dw = $('div.'+options.class+'.world').width();
    $('svg.'+options.class+'.world').attr('width',dw);
  }

  var makemap = function(data) {
    var topo,projection,path,svg,g,draw;
    var updatemap = function() {
      draw(topo,data);
    }

    var tooltip = d3.select("svg.holder.world").append("div").attr("class", "tooltip hidden");

    function setup() {
      var svg = d3.select("svg.holder.world")
      var margin = {top: 0, right: 0, bottom: 0, left: 0};
      var width = +svg.attr("width") - margin.left - margin.right;
      var height = +svg.attr("height") - margin.top - margin.bottom;
      projection = d3.geoMercator()
        .translate([(width/2), (height/1.55)])
        .scale( width / 2 / Math.PI)
        .center([0, 0 ]);

      path = d3.geoPath().projection(projection);

      g = svg.append("g");
    }
    setup();

    d3.json("//static.cottagelabs.com/maps/world-topo.json", function(error, world) {
      topo = topojson.feature(world, world.objects.countries).features;
      draw(topo);
      updatemap();
    });

    function addpoint(lon,lat) {
      var gpoint = g.append("g").attr("class", "gpoint");
      var x = projection([lon,lat])[0];
      var y = projection([lon,lat])[1];

      gpoint.append("svg:circle")
        .attr("cx", x)
        .attr("cy", y)
        .attr("class","point")
        .attr("r", 2);
    }

    draw = function(topo,data) {
      var country = g.selectAll(".country").data(topo);
      country.enter().insert("path")
        .attr("class", "country")
        .attr("d", path)
        .attr("id", function(d,i) { return d.id; });

      if (data) {
        data.forEach(function(i) {
          if ( i['location.geo.lat'] && i['location.geo.lon'] ) {
            addpoint(
              i['location.geo.lon'][0],
              i['location.geo.lat'][0]
            );
          } else if ( i.location && i.location.geo && i.location.geo.lat && i.location.geo.lon) {
            addpoint(
              i.location.geo.lon,
              i.location.geo.lat
            );
          }
        });
      }
    }

  }
  makemap(options.records);

};


text:
using System.Diagnostics.CodeAnalysis;

namespace EncompassRest.Company.Users.Rights
{
    /// <summary>
    /// UnprotectedDocumentsRights
    /// </summary>
    public sealed class UnprotectedDocumentsRights : DirtyExtensibleObject
    {
        private DirtyValue<bool?>? _deleteDocument;
        private EditDocumentRights? _editDocument;

        /// <summary>
        /// UnprotectedDocumentsRights DeleteDocument
        /// </summary>
        public bool? DeleteDocument { get => _deleteDocument; set => SetField(ref _deleteDocument, value); }

        /// <summary>
        /// UnprotectedDocumentsRights EditDocument
        /// </summary>
        [AllowNull]
        public EditDocumentRights EditDocument { get => GetField(ref _editDocument); set => SetField(ref _editDocument, value); }
    }
}


text:
using System;
using FluentAssertions;
using Microsoft.AspNet.Identity;
using NUnit.Framework;

namespace AspNet.Identity.Cassandra.IntegrationTests
{
    /// <summary>
    /// Tests for storing, authenticating, and changing user passwords.
    /// </summary>
    [TestFixture]
    public class PasswordTests : IntegrationTestBase
    {
        public override void TestSetup()
        {
            base.TestSetup();
            UserManager.UserTokenProvider = new TotpSecurityStampBasedTokenProvider<CassandraUser, Guid>();
        }

        [Test]
        public async void HasPassword()
        {
            // Create a user
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "passwordUser1" };
            await UserManager.CreateAsync(user);

            // Verify they are created without a password
            bool hasPassword = await UserManager.HasPasswordAsync(user.Id);
            hasPassword.Should().BeFalse();

            // Create a user with a password
            user = new CassandraUser(Guid.NewGuid()) {UserName = "passwordUser2"};
            await UserManager.CreateAsync(user, "somePassword");

            // Verify they have a password
            hasPassword = await UserManager.HasPasswordAsync(user.Id);
            hasPassword.Should().BeTrue();
        }

        [Test]
        public async void AddRemovePassword()
        {
            // Create user without password
            var user = new CassandraUser(Guid.NewGuid()) {UserName = "passwordUser3"};
            await UserManager.CreateAsync(user);

            // Adding a password should succeed
            IdentityResult result = await UserManager.AddPasswordAsync(user.Id, "somePassword");
            result.ShouldBeSuccess();
            bool hasPassword = await UserManager.HasPasswordAsync(user.Id);
            hasPassword.Should().BeTrue();

            // Now removing a password should succeed
            result = await UserManager.RemovePasswordAsync(user.Id);
            result.ShouldBeSuccess();
            hasPassword = await UserManager.HasPasswordAsync(user.Id);
            hasPassword.Should().BeFalse();
        }

        [Test]
        public async void Authenticate()
        {
            // Create a user with a password
            var user = new CassandraUser(Guid.NewGuid()) {UserName = "passwordUser4"};
            await UserManager.CreateAsync(user, "somePassword");

            // Should be able to authenticate user with password
            bool authenticated = await UserManager.CheckPasswordAsync(user, "somePassword");
            authenticated.Should().BeTrue();
        }

        [Test]
        public async void ChangePassword()
        {
            // Create a user with a password
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "passwordUser5" };
            await UserManager.CreateAsync(user, "somePassword");

            // Should be able to change the password
            IdentityResult result = await UserManager.ChangePasswordAsync(user.Id, "somePassword", "someNewPassword");
            result.ShouldBeSuccess();

            // Should be able to authenticate with new password
            user = await UserManager.FindByIdAsync(user.Id);
            bool authenticated = await UserManager.CheckPasswordAsync(user, "someNewPassword");
            authenticated.Should().BeTrue();

            // Should not be able to authenticate with old password
            authenticated = await UserManager.CheckPasswordAsync(user, "somePassword");
            authenticated.Should().BeFalse();
        }

        [Test]
        public async void ResetPassword()
        {
            // Create a user with a password
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "passwordUser6" };
            await UserManager.CreateAsync(user, "somePassword");

            // Generate a reset token and then reset the password should succeed
            string token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
            IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, token, "someNewPassword");
            result.ShouldBeSuccess();

            // Should now be able to authenticate with new password
            user = await UserManager.FindByIdAsync(user.Id);
            bool authenticated = await UserManager.CheckPasswordAsync(user, "someNewPassword");
            authenticated.Should().BeTrue();

            // Should not be able to authenticate with old password
            authenticated = await UserManager.CheckPasswordAsync(user, "somePassword");
            authenticated.Should().BeFalse();
        }
    }
}


text:
package net.spy.memcached.plugin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import net.sf.ehcache.Element;
import net.spy.memcached.internal.GetFuture;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.ops.StatusCode;

/**
 * Future returned for GET operations.
 *
 * Not intended for general use.
 *
 * @param <T> Type of object returned from the get
 */
public class FrontCacheGetFuture<T> extends GetFuture<T> {

  private static final OperationStatus END =
          new OperationStatus(true, "END", StatusCode.SUCCESS);
  private final Element element;

  public FrontCacheGetFuture(Element element) {
    super(null, 0);
    this.element = element;
  }

  @Override
  public boolean cancel(boolean mayInterruptIfRunning) {
    return false;
  }

  @Override
  public T get() throws InterruptedException, ExecutionException {
    return getValue();
  }

  @Override
  public OperationStatus getStatus() {
    return END;
  }

  @SuppressWarnings("unchecked")
  private T getValue() {
    return (T) this.element.getObjectValue();
  }

  @Override
  public T get(long timeout, TimeUnit unit) throws InterruptedException,
          ExecutionException, TimeoutException {
    return getValue();
  }

  @Override
  public boolean isCancelled() {
    return false;
  }

  @Override
  public boolean isDone() {
    return true;
  }

}


text:
package org.springframework.cloud.deployer.spi.scheduler.cloudfoundry;

import org.junit.jupiter.api.Test;

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

/**
 * Verify that {@linkCloudFoundryScheduleSSLException} has the expected behavior.
 *
 * @author Glenn Renfro
 */
public class CloudFoundryScheduleSSLExceptionTests {

	@Test
	public void testExceptionMessageOnly() {
		try {
			throw new CloudFoundryScheduleSSLException("oops");
		}
		catch (CloudFoundryScheduleSSLException cfe) {
			assertThat(cfe.getMessage()).isEqualTo("oops");
		}
	}

	@Test
	public void testExceptionMessageWithException() {
		RuntimeException rte = new RuntimeException("RTE");
		try {
			throw new CloudFoundryScheduleSSLException("oops", rte);
		}
		catch (CloudFoundryScheduleSSLException cfe) {
			assertThat(cfe.getMessage()).isEqualTo("oops");
			assertThat(cfe.getCause()).isEqualTo(rte);
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/text1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:fontFamily="sans-serif-light"
  android:gravity="center"
  android:text="@string/no_results_found"
  android:textAppearance="@style/TextAppearance.AppCompat.Light.SearchResult.Subtitle" />


text: © Resistance Ecology {% now "Y" %} |  resistanceecology@gmail.com |


text:
use std::ops::Index;
use std::cmp::Ordering;
use sdl2::ttf::{Font, Sdl2TtfContext};

pub struct FontSet<'ttf> {
    font_size: u16,
    /// Font object without outline
    font_regular: Font<'ttf,'static>,
    /// Font object with light outline
    font_lightbold: Font<'ttf,'static>,
    /// Font object with outline
    font_bold: Font<'ttf,'static>,
}

impl<'ttf> Eq for FontSet<'ttf> {}

impl<'ttf> PartialEq for FontSet<'ttf> {
    fn eq(&self, other: &Self) -> bool {
        self.font_size.eq(&other.font_size)
    }
}

impl<'ttf> PartialOrd for FontSet<'ttf> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.font_size.partial_cmp(&other.font_size)
    }
}

impl<'ttf> Ord for FontSet<'ttf> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.font_size.cmp(&other.font_size)
    }
}

impl<'ttf> Index<usize> for FontList<'ttf> {
    type Output = FontSet<'ttf>;
    fn index(&self, index: usize) -> &FontSet<'ttf> {
        &self.get_font_set(index).unwrap()
    }
}

impl<'ttf> FontSet<'ttf> {
    #[inline]
    pub fn get_regular_font(&self) -> &Font {
        &self.font_regular
    }

    #[inline]
    pub fn get_outline_font(&self) -> &Font {
        &self.font_bold
    }

    #[inline]
    pub fn get_light_outline_font(&self) -> &Font {
        &self.font_lightbold
    }

    pub fn get_outline_width(font_size: u16, width: usize) -> u16 {
        match width {
            0 => 0,
            1 => (font_size / 30) + 1,
            2 => (font_size / 20) + 2,
            _ => 0,
        }
    }

    pub fn get_font_size(&self) -> u16 {
        self.font_size
    }
}

// MADE PUBLIC FOR TESTS, MAKE PRIVATE WHEN NOT NECESSARY ANYMORE
pub struct FontList<'ttf> {
    // font list is a SORTED font list
    fonts: Vec<FontSet<'ttf>>,
}

const DEJAVUSANS_MONO_BYTES: &'static [u8] = include_bytes!("../../res/DejaVuSansMono-Bold-WithJap.\
                                                             ttf");

impl<'ttf> FontList<'ttf> {
    pub fn new(ttf_context: &'ttf Sdl2TtfContext) -> Result<FontList<'ttf>, String> {
        use sdl2::rwops::RWops;
        let mut result = FontList { fonts: Vec::<FontSet>::new() };
        let mut font_size = 3;
        let font_size_max = 128;
        let font_size_increment = 1;
        'fontlist: while (font_size < font_size_max) {
            let rwops_regular: RWops<'static> = try!(RWops::from_bytes(DEJAVUSANS_MONO_BYTES));
            let rwops_bold: RWops<'static> = try!(RWops::from_bytes(DEJAVUSANS_MONO_BYTES));
            let rwops_lbold: RWops<'static> = try!(RWops::from_bytes(DEJAVUSANS_MONO_BYTES));
            let font_regular = try!(ttf_context.load_font_from_rwops(rwops_regular, font_size));
            let mut font_bold = try!(ttf_context.load_font_from_rwops(rwops_bold, font_size));
            let mut font_lbold = try!(ttf_context.load_font_from_rwops(rwops_lbold, font_size));
            font_lbold.set_outline_width(FontSet::get_outline_width(font_size, 1));
            font_bold.set_outline_width(FontSet::get_outline_width(font_size, 2));
            result.fonts.push(FontSet {
                font_size: font_size,
                font_regular: font_regular,
                font_bold: font_bold,
                font_lightbold: font_lbold,
            });
            font_size += font_size_increment;
        }
        Ok(result)
    }

    pub fn get_font_set(&self, index: usize) -> Option<&FontSet<'ttf>> {
        self.fonts.get(index)
    }

    /// Given a string and a maximum width, get the fittest font from the FontList
    pub fn get_fittest_font_set_id(&self,
                                   string: &str,
                                   max_dims: (Option<u32>, Option<u32>),
                                   outline: usize)
                                   -> Result<usize, String> {
        if max_dims == (None, None) {
            Err(String::from("can't get fittiest font if both dims are None")) // cant get the fittiest if both are None !
        } else {
            match self.fonts.len() {
                0 => Err(String::from("can't get the fittest font if there is none available")),
                1 => Ok(0),
                _ => {
                    let search_result = self.fonts.binary_search_by(|fontset| {
                        let search_font = match outline {
                            0 => &fontset.font_regular,
                            1 => &fontset.font_lightbold,
                            2 => &fontset.font_bold,
                            _ => {
                                warn!("wrong font_set size set");
                                &fontset.font_regular
                            }
                        };
                        let string_dims = search_font.size_of(string)
                            .expect("Failed to get dimensions");
                        match max_dims {
                            (Some(width), Some(height)) => {
                                match (string_dims.0.cmp(&width), string_dims.1.cmp(&height)) {
                                    (Ordering::Greater, _) |
                                    (_, Ordering::Greater) => Ordering::Greater,
                                    (Ordering::Equal, _) |
                                    (_, Ordering::Equal) => Ordering::Equal,
                                    _ => Ordering::Less,
                                }
                            }
                            (Some(width), None) => string_dims.0.cmp(&width),
                            (None, Some(height)) => string_dims.1.cmp(&height),
                            (None, None) => unreachable!(),
                        }
                    });
                    match search_result {
                        Ok(index) => Ok(index),
                        Err(0) => Ok(0),
                        Err(index) if index == self.fonts.len() => Ok(self.fonts.len() - 1),
                        Err(index) => Ok(index - 1),
                        // it should fit, meaning that if we can't find something exactly we should
                        // take the first that fits
                    }
                }
            }
        }
    }
}


text:
#include "peer_database.h"

#include <string.h>
#include "app_util.h"
#include "peer_manager_types.h"
#include "peer_manager_internal.h"
#include "peer_data_storage.h"
#include "pm_buffer.h"
#include "sdk_common.h"

#define MAX_REGISTRANTS    6                         /**< The number of user that can register with the module. */

#define N_WRITE_BUFFERS        8                     /**< The number of write buffers available. */
#define N_WRITE_BUFFER_RECORDS (N_WRITE_BUFFERS)     /**< The number of write buffer records. */

/**@brief Macro for verifying that the data ID is among the values eligible for using the write buffer.
 *
 * @param[in] data_id  The data ID to verify.
 */
#define VERIFY_DATA_ID_WRITE_BUF(data_id)                                                    \
do                                                                                \
{                                                                                \
    if (((data_id) != PM_PEER_DATA_ID_BONDING) && ((data_id) != PM_PEER_DATA_ID_GATT_LOCAL)) \
    {                                                                                \
        return NRF_ERROR_INVALID_PARAM;                                                      \
    }                                                                                \
} while(0)

/**@brief Struct for keeping track of one write buffer, from allocation, until it is fully written
 *        or cancelled.
 */
typedef struct
{
    pm_peer_id_t        peer_id;               /**< The peer ID this buffer belongs to. */
    pm_peer_data_id_t   data_id;               /**< The data ID this buffer belongs to. */
    uint8_t             buffer_block_id;       /**< The index of the first (or only) buffer block containing peer data. */
    uint32_t            n_bufs;                /**< The number of buffer blocks containing peer data. */
    uint8_t             store_busy       : 1;  /**< Flag indicating that the buffer was attempted written to flash, but a busy error was returned and the operation should be retried. */
    uint8_t             store_flash_full : 1;  /**< Flag indicating that the buffer was attempted written to flash, but a flash full error was returned and the operation should be retried after room has been made. */
    uint8_t             store_requested  : 1;  /**< Flag indicating that the buffer is being written to flash. */
    pm_prepare_token_t  prepare_token;         /**< Token given by Peer Data Storage if room in flash has been reserved. */
    pm_store_token_t    store_token;           /**< Token given by Peer Data Storage when a flash write has been successfully requested. */
} pdb_buffer_record_t;

/**@brief Struct for keeping track of the state of the module.
 */
typedef struct
{
    pdb_evt_handler_t   evt_handlers[MAX_REGISTRANTS];                /**< All registered event handlers. */
    uint8_t             n_registrants;                                /**< The number of registered event handlers. */
    pm_buffer_t         write_buffer;                                 /**< The state of the write buffer. */
    pdb_buffer_record_t write_buffer_records[N_WRITE_BUFFER_RECORDS]; /**< The available write buffer records. */
    uint32_t            n_writes;                                     /**< The number of pending (Not yet successfully requested in Peer Data Storage) store operations. */
} pdb_t;

static pdb_t m_pdb = {.n_registrants = 0}; /**< The state of the module. */

#define MODULE_INITIALIZED (m_pdb.n_registrants > 0) /**< Expression which is true when the module is initialized. */
#include "sdk_macros.h"

/**@brief Function for invalidating a record of a write buffer allocation.
 *
 * @param[in]  p_record  The record to invalidate.
 */
static void write_buffer_record_invalidate(pdb_buffer_record_t * p_record)
{
    p_record->peer_id          = PM_PEER_ID_INVALID;
    p_record->data_id          = PM_PEER_DATA_ID_INVALID;
    p_record->buffer_block_id  = BUFFER_INVALID_ID;
    p_record->store_busy       = false;
    p_record->store_flash_full = false;
    p_record->store_requested  = false;
    p_record->n_bufs           = 0;
    p_record->prepare_token    = PDS_PREPARE_TOKEN_INVALID;
    p_record->store_token      = PM_STORE_TOKEN_INVALID;
}

/**@brief Function for finding a record of a write buffer allocation.
 *
 * @param[in]    peer_id  The peer ID in the record.
 * @param[inout] p_index  In: The starting index, out: The index of the record
 *
 * @return  A pointer to the matching record, or NULL if none was found.
 */
static pdb_buffer_record_t * write_buffer_record_find_next(pm_peer_id_t peer_id, int * p_index)
{
    for (uint32_t i = *p_index; i < N_WRITE_BUFFER_RECORDS; i++)
    {
        if ((m_pdb.write_buffer_records[i].peer_id == peer_id))
        {
            return &m_pdb.write_buffer_records[i];
        }
    }
    return NULL;
}

/**@brief Function for finding a record of a write buffer allocation.
 *
 * @param[in]  peer_id  The peer ID in the record.
 * @param[in]  data_id  The data ID in the record.
 *
 * @return  A pointer to the matching record, or NULL if none was found.
 */
static pdb_buffer_record_t * write_buffer_record_find(pm_peer_id_t      peer_id,
                                                      pm_peer_data_id_t data_id)
{
    int index = 0;
    pdb_buffer_record_t * p_record = write_buffer_record_find_next(peer_id, &index);

    while ((p_record != NULL) && (p_record->data_id != data_id))
    {
        index++;
        p_record = write_buffer_record_find_next(peer_id, &index);
    }

    return p_record;
}

/**@brief Function for finding an available record for write buffer allocation.
 *
 * @return  A pointer to the available record, or NULL if none was found.
 */
static pdb_buffer_record_t * write_buffer_record_find_unused(void)
{
    return write_buffer_record_find(PM_PEER_ID_INVALID, PM_PEER_DATA_ID_INVALID);
}

/**@brief Function for gracefully deactivating a write buffer record.
 *
 * @details This function will first release any buffers, then invalidate the record.
 *
 * @param[inout] p_write_buffer_record  The record to release.
 *
 * @return  A pointer to the matching record, or NULL if none was found.
 */
static void write_buffer_record_release(pdb_buffer_record_t * p_write_buffer_record)
{
    for (uint32_t i = 0; i < p_write_buffer_record->n_bufs; i++)
    {
        pm_buffer_release(&m_pdb.write_buffer, p_write_buffer_record->buffer_block_id + i);
    }

    write_buffer_record_invalidate(p_write_buffer_record);
}

/**@brief Function for claiming and activating a write buffer record.
 *
 * @param[out] pp_write_buffer_record  The claimed record.
 * @param[in]   peer_id                 The peer ID this record should have.
 * @param[in]  data_id                 The data ID this record should have.
 */
static void write_buffer_record_get(pdb_buffer_record_t ** pp_write_buffer_record, pm_peer_id_t peer_id, pm_peer_data_id_t data_id)
{
    if (pp_write_buffer_record == NULL)
    {
        return;
    }
    *pp_write_buffer_record = write_buffer_record_find_unused();
    if (*pp_write_buffer_record == NULL)
    {
        // This also means the buffer is full.
        return;
    }
    (*pp_write_buffer_record)->peer_id = peer_id;
    (*pp_write_buffer_record)->data_id = data_id;
}

/**@brief Function for dispatching outbound events to all registered event handlers.
 *
 * @param[in]  p_event  The event to dispatch.
 */
static void pdb_evt_send(pdb_evt_t * p_event)
{
    for (uint32_t i = 0; i < m_pdb.n_registrants; i++)
    {
        m_pdb.evt_handlers[i](p_event);
    }
}

/**@brief Function for resetting the internal state of the Peer Database module.
 *
 * @param[out] p_event  The event to dispatch.
 */
static void internal_state_reset(pdb_t * pdb)
{
    memset(pdb, 0, sizeof(pdb_t));
    for (uint32_t i = 0; i < N_WRITE_BUFFER_RECORDS; i++)
    {
        write_buffer_record_invalidate(&pdb->write_buffer_records[i]);
    }
}

/**@brief Function for handling events from the Peer Data Storage module.
 *
 * @param[in]  p_event  The event to handle.
 */
static void pds_evt_handler(pds_evt_t const * p_event)
{
    ret_code_t            err_code;
    pdb_buffer_record_t * p_write_buffer_record;
    bool                  retry_flash_full = false;
    pdb_evt_t             event =
    {
        .peer_id = p_event->peer_id,
        .data_id = p_event->data_id,
    };

    p_write_buffer_record = write_buffer_record_find(p_event->peer_id, p_event->data_id);

    switch (p_event->evt_id)
    {
        case PDS_EVT_STORED:
        case PDS_EVT_UPDATED:
            if (   (p_write_buffer_record != NULL)
                //&& (p_write_buffer_record->store_token == p_event->store_token)
                && (p_write_buffer_record->store_requested))
            {
                write_buffer_record_release(p_write_buffer_record);
                event.evt_id = PDB_EVT_WRITE_BUF_STORED;
                event.params.write_buf_stored_evt.update = (p_event->evt_id == PDS_EVT_UPDATED);
                pdb_evt_send(&event);
            }
            else
            {
                event.evt_id = PDB_EVT_RAW_STORED;
                event.params.raw_stored_evt.store_token = p_event->store_token;
                pdb_evt_send(&event);
            }
            break;
        case PDS_EVT_ERROR_STORE:
        case PDS_EVT_ERROR_UPDATE:
            if (   (p_write_buffer_record != NULL)
                && (p_write_buffer_record->store_token == p_event->store_token)
                && (p_write_buffer_record->store_requested))
            {
                // Retry if internal buffer.
                m_pdb.n_writes++;
                p_write_buffer_record->store_requested = false;
                p_write_buffer_record->store_busy      = true;
            }
            else
            {
                event.evt_id                              = PDB_EVT_RAW_STORE_FAILED;
                event.params.error_raw_store_evt.err_code = p_event->result;
                pdb_evt_send(&event);
            }
            break;
        case PDS_EVT_CLEARED:
            event.evt_id = PDB_EVT_CLEARED;
            pdb_evt_send(&event);
            break;
        case PDS_EVT_ERROR_CLEAR:
            event.evt_id = PDB_EVT_CLEAR_FAILED;
            event.params.clear_failed_evt.err_code = p_event->result;
            pdb_evt_send(&event);
            break;
        case PDS_EVT_PEER_ID_CLEAR:
            event.evt_id = PDB_EVT_PEER_FREED;
            pdb_evt_send(&event);
            break;
        case PDS_EVT_ERROR_PEER_ID_CLEAR:
            event.evt_id = PDB_EVT_PEER_FREE_FAILED;
            event.params.peer_free_failed_evt.err_code = p_event->result;
            pdb_evt_send(&event);
            break;
        case PDS_EVT_COMPRESSED:
            retry_flash_full = true;
            event.evt_id = PDB_EVT_COMPRESSED;
            pdb_evt_send(&event);
            break;
        case PDS_EVT_ERROR_UNEXPECTED:
            event.params.error_unexpected.err_code = p_event->result;
            break;
        default:
            break;
    }

    if (m_pdb.n_writes > 0)
    {
        for (uint32_t i = 0; i < N_WRITE_BUFFER_RECORDS; i++)
        {
            if  ((m_pdb.write_buffer_records[i].store_busy)
              || (m_pdb.write_buffer_records[i].store_flash_full && retry_flash_full))
            {
                err_code = pdb_write_buf_store(m_pdb.write_buffer_records[i].peer_id,
                                               m_pdb.write_buffer_records[i].data_id);
                if (err_code != NRF_SUCCESS)
                {
                    event.peer_id = m_pdb.write_buffer_records[i].peer_id;
                    event.data_id = m_pdb.write_buffer_records[i].data_id;
                    if (err_code == NRF_ERROR_NO_MEM)
                    {
                        event.evt_id = PDB_EVT_ERROR_NO_MEM;
                    }
                    else
                    {
                        event.evt_id                           = PDB_EVT_ERROR_UNEXPECTED;
                        event.params.error_unexpected.err_code = err_code;
                    }

                    pdb_evt_send(&event);
                    break;
                }
            }
        }
    }
}

ret_code_t pdb_register(pdb_evt_handler_t evt_handler)
{
    if (m_pdb.n_registrants >= MAX_REGISTRANTS)
    {
        return NRF_ERROR_NO_MEM;
    }

    VERIFY_PARAM_NOT_NULL(evt_handler);

    if (!MODULE_INITIALIZED)
    {
        ret_code_t err_code;

        internal_state_reset(&m_pdb);
        err_code = pds_register(pds_evt_handler);
        if (err_code != NRF_SUCCESS)
        {
            return NRF_ERROR_INTERNAL;
        }
        PM_BUFFER_INIT(&m_pdb.write_buffer, N_WRITE_BUFFERS, PDB_WRITE_BUF_SIZE, err_code);
        if (err_code != NRF_SUCCESS)
        {
            return NRF_ERROR_INTERNAL;
        }
    }

    m_pdb.evt_handlers[m_pdb.n_registrants] = evt_handler;
    m_pdb.n_registrants += 1;

    return NRF_SUCCESS;
}

pm_peer_id_t pdb_peer_allocate(void)
{
    if (!MODULE_INITIALIZED)
    {
        return PM_PEER_ID_INVALID;
    }

    return pds_peer_id_allocate();
}

ret_code_t pdb_peer_free(pm_peer_id_t peer_id)
{
    VERIFY_MODULE_INITIALIZED();
    ret_code_t err_code_in  = NRF_SUCCESS;
    ret_code_t err_code_out = NRF_SUCCESS;

    int index = 0;
    pdb_buffer_record_t * p_record = write_buffer_record_find_next(peer_id, &index);

    while (p_record != NULL)
    {
        err_code_in = pdb_write_buf_release(peer_id, p_record->data_id);

        if (   (err_code_in != NRF_SUCCESS)
            && (err_code_in != NRF_ERROR_NOT_FOUND))
        {
            err_code_out = NRF_ERROR_INTERNAL;
        }

        index++;
        p_record = write_buffer_record_find_next(peer_id, &index);
    }

    if (err_code_out == NRF_SUCCESS)
    {
        err_code_in = pds_peer_id_free(peer_id);

        if (err_code_in == NRF_SUCCESS)
        {
            // No action needed.
        }
        else if (err_code_in == NRF_ERROR_INVALID_PARAM)
        {
            err_code_out = NRF_ERROR_INVALID_PARAM;
        }
        else
        {
            err_code_out = NRF_ERROR_INTERNAL;
        }
    }

    return err_code_out;
}

ret_code_t pdb_read_buf_get(pm_peer_id_t           peer_id,
                            pm_peer_data_id_t      data_id,
                            pm_peer_data_flash_t * p_peer_data,
                            pm_store_token_t     * p_token)
{
    VERIFY_MODULE_INITIALIZED();

    return pds_peer_data_read_ptr_get(peer_id, data_id, p_peer_data, p_token);
}

static void peer_data_point_to_buffer(pm_peer_data_t * p_peer_data, pm_peer_data_id_t data_id, uint8_t * p_buffer_memory, uint16_t n_bufs)
{
    uint16_t n_bytes = n_bufs * PDB_WRITE_BUF_SIZE;
    p_peer_data->data_id    = data_id;

    p_peer_data->p_all_data   = (pm_peer_data_bonding_t *)p_buffer_memory;
    p_peer_data->length_words = BYTES_TO_WORDS(n_bytes);
}

static void peer_data_const_point_to_buffer(pm_peer_data_const_t * p_peer_data, pm_peer_data_id_t data_id,  uint8_t * p_buffer_memory, uint32_t n_bufs)
{
    peer_data_point_to_buffer((pm_peer_data_t*)p_peer_data, data_id, p_buffer_memory, n_bufs);
}

static void write_buf_length_words_set(pm_peer_data_const_t * p_peer_data)
{
    switch (p_peer_data->data_id)
    {
        case PM_PEER_DATA_ID_BONDING:
            p_peer_data->length_words = PM_BONDING_DATA_N_WORDS();
            break;
        case PM_PEER_DATA_ID_SERVICE_CHANGED_PENDING:
            p_peer_data->length_words = PM_SC_STATE_N_WORDS();
            break;
        case PM_PEER_DATA_ID_PEER_RANK:
            p_peer_data->length_words = PM_USAGE_INDEX_N_WORDS();
            break;
        case PM_PEER_DATA_ID_GATT_LOCAL:
            p_peer_data->length_words = PM_LOCAL_DB_N_WORDS(p_peer_data->p_local_gatt_db->len);
            break;
        default:
            // No action needed.
            break;
    }
}

ret_code_t pdb_write_buf_get(pm_peer_id_t       peer_id,
                             pm_peer_data_id_t  data_id,
                             uint32_t           n_bufs,
                             pm_peer_data_t   * p_peer_data)
{
    VERIFY_MODULE_INITIALIZED();
    VERIFY_PARAM_NOT_NULL(p_peer_data);
    VERIFY_DATA_ID_WRITE_BUF(data_id);
    if (   (n_bufs == 0)
        || (n_bufs > N_WRITE_BUFFERS)
        || !pds_peer_id_is_allocated(peer_id))
    {
        return NRF_ERROR_INVALID_PARAM;
    }

    pdb_buffer_record_t * write_buffer_record;
    uint8_t             * p_buffer_memory;
    bool                  new_record = false;

    write_buffer_record = write_buffer_record_find(peer_id, data_id);

    if ((write_buffer_record != NULL) && (write_buffer_record->n_bufs < n_bufs))
    {
        // @TODO: Copy?
        // Existing buffer is too small.
        for (uint8_t i = 0; i < write_buffer_record->n_bufs; i++)
        {
            pm_buffer_release(&m_pdb.write_buffer, write_buffer_record->buffer_block_id + i);
        }
        write_buffer_record_invalidate(write_buffer_record);
        write_buffer_record = NULL;
    }
    else if ((write_buffer_record != NULL) && write_buffer_record->n_bufs > n_bufs)
    {
        // Release excess blocks.
        for (uint8_t i = n_bufs; i < write_buffer_record->n_bufs; i++)
        {
            pm_buffer_release(&m_pdb.write_buffer, write_buffer_record->buffer_block_id + i);
        }
    }

    if (write_buffer_record == NULL)
    {
        write_buffer_record_get(&write_buffer_record, peer_id, data_id);
        if (write_buffer_record == NULL)
        {
            return NRF_ERROR_BUSY;
        }
    }

    if (write_buffer_record->buffer_block_id == BUFFER_INVALID_ID)
    {
        write_buffer_record->buffer_block_id = pm_buffer_block_acquire(&m_pdb.write_buffer, n_bufs);

        if (write_buffer_record->buffer_block_id == BUFFER_INVALID_ID)
        {
            write_buffer_record_invalidate(write_buffer_record);
            return NRF_ERROR_BUSY;
        }

        new_record = true;
    }

    write_buffer_record->n_bufs = n_bufs;

    p_buffer_memory = pm_buffer_ptr_get(&m_pdb.write_buffer, write_buffer_record->buffer_block_id);

    if (p_buffer_memory == NULL)
    {
        return NRF_ERROR_INTERNAL;
    }

    peer_data_point_to_buffer(p_peer_data, data_id, p_buffer_memory, n_bufs);
    if (new_record && (data_id == PM_PEER_DATA_ID_GATT_LOCAL))
    {
        p_peer_data->p_local_gatt_db->len = PM_LOCAL_DB_LEN(p_peer_data->length_words);
    }

    return NRF_SUCCESS;
}

ret_code_t pdb_write_buf_release(pm_peer_id_t peer_id, pm_peer_data_id_t data_id)
{
    VERIFY_MODULE_INITIALIZED();

    ret_code_t            err_code = NRF_SUCCESS;
    pdb_buffer_record_t * p_write_buffer_record;
    p_write_buffer_record = write_buffer_record_find(peer_id, data_id);

    if (p_write_buffer_record == NULL)
    {
        return NRF_ERROR_NOT_FOUND;
    }

    if (p_write_buffer_record->prepare_token != PDS_PREPARE_TOKEN_INVALID)
    {
        err_code = pds_peer_data_write_prepare_cancel(p_write_buffer_record->prepare_token);
        if (err_code != NRF_SUCCESS)
        {
            err_code = NRF_ERROR_INTERNAL;
        }
    }

    write_buffer_record_release(p_write_buffer_record);

    return err_code;
}

ret_code_t pdb_write_buf_store_prepare(pm_peer_id_t peer_id, pm_peer_data_id_t data_id)
{
    VERIFY_MODULE_INITIALIZED();
    VERIFY_DATA_ID_WRITE_BUF(data_id);

    ret_code_t            err_code = NRF_SUCCESS;
    pdb_buffer_record_t * p_write_buffer_record;
    p_write_buffer_record = write_buffer_record_find(peer_id, data_id);

    if (p_write_buffer_record == NULL)
    {
        return NRF_ERROR_NOT_FOUND;
    }

    if (p_write_buffer_record->prepare_token == PDS_PREPARE_TOKEN_INVALID)
    {
        uint8_t * p_buffer_memory = pm_buffer_ptr_get(&m_pdb.write_buffer, p_write_buffer_record->buffer_block_id);
        pm_peer_data_const_t peer_data = {.data_id = data_id};

        if (p_buffer_memory == NULL)
        {
            return NRF_ERROR_INTERNAL;
        }

        peer_data_const_point_to_buffer(&peer_data, data_id, p_buffer_memory, p_write_buffer_record->n_bufs);

        write_buf_length_words_set(&peer_data);

        err_code = pds_peer_data_write_prepare(&peer_data, &p_write_buffer_record->prepare_token);
        if (err_code == NRF_ERROR_INVALID_LENGTH)
        {
            return NRF_ERROR_INTERNAL;
        }
    }

    return err_code;
}

static ret_code_t write_or_update(pm_peer_id_t           peer_id,
                                  pm_peer_data_id_t      data_id,
                                  pm_peer_data_const_t * p_peer_data,
                                  pm_store_token_t     * p_store_token,
                                  pm_prepare_token_t     prepare_token)
{
    pm_peer_data_flash_t old_peer_data;
    pm_store_token_t     old_store_token;
    ret_code_t err_code = pds_peer_data_read_ptr_get(peer_id, data_id, &old_peer_data, &old_store_token);

    if (err_code == NRF_SUCCESS)
    {
        err_code = pds_peer_data_write_prepare_cancel(prepare_token);
        if ((err_code == NRF_SUCCESS) || (err_code == NRF_ERROR_NULL))
        {
            err_code = pds_peer_data_update(peer_id, p_peer_data, old_store_token, p_store_token);
        }
        else
        {
            err_code = NRF_ERROR_INTERNAL;
        }
    }
    else if (err_code == NRF_ERROR_NOT_FOUND)
    {
        if (prepare_token == PDS_PREPARE_TOKEN_INVALID)
        {
            err_code = pds_peer_data_write(peer_id, p_peer_data, p_store_token);
        }
        else
        {
            err_code = pds_peer_data_write_prepared(peer_id, p_peer_data, prepare_token, p_store_token);
        }
    }
    return err_code;
}

ret_code_t pdb_write_buf_store(pm_peer_id_t      peer_id,
                               pm_peer_data_id_t data_id)
{
    VERIFY_MODULE_INITIALIZED();
    VERIFY_DATA_ID_WRITE_BUF(data_id);

    ret_code_t            err_code = NRF_SUCCESS;
    pdb_buffer_record_t * p_write_buffer_record;
    uint8_t             * p_buffer_memory;
    pm_peer_data_const_t  peer_data = {.data_id = data_id};

    p_write_buffer_record = write_buffer_record_find(peer_id, data_id);

    if (p_write_buffer_record == NULL)
    {
        return NRF_ERROR_NOT_FOUND;
    }

    if (p_write_buffer_record->store_requested)
    {
        return NRF_SUCCESS;
    }

    p_buffer_memory = pm_buffer_ptr_get(&m_pdb.write_buffer, p_write_buffer_record->buffer_block_id);

    if (p_buffer_memory == NULL)
    {
        return NRF_ERROR_INTERNAL;
    }

    peer_data_const_point_to_buffer(&peer_data, data_id, p_buffer_memory, p_write_buffer_record->n_bufs);

    write_buf_length_words_set(&peer_data);

    err_code = write_or_update(peer_id, data_id, &peer_data, &p_write_buffer_record->store_token, p_write_buffer_record->prepare_token);

    if (p_write_buffer_record->store_busy && p_write_buffer_record->store_flash_full)
    {
        m_pdb.n_writes--;
    }

    if (err_code == NRF_SUCCESS)
    {
        p_write_buffer_record->store_requested  = true;
        p_write_buffer_record->store_busy       = false;
        p_write_buffer_record->store_flash_full = false;
    }
    else
    {
        if (err_code == NRF_ERROR_BUSY)
        {
            m_pdb.n_writes++;
            p_write_buffer_record->store_busy       = true;
            p_write_buffer_record->store_flash_full = false;
            err_code = NRF_SUCCESS;
        }
        else if (err_code == NRF_ERROR_NO_MEM)
        {
            m_pdb.n_writes++;
            p_write_buffer_record->store_busy       = false;
            p_write_buffer_record->store_flash_full = true;
        }
        else if ((err_code != NRF_ERROR_NO_MEM) && (err_code != NRF_ERROR_INVALID_PARAM))
        {
            err_code = NRF_ERROR_INTERNAL;
        }
    }

    return err_code;
}

ret_code_t pdb_clear(pm_peer_id_t peer_id, pm_peer_data_id_t data_id)
{
    VERIFY_MODULE_INITIALIZED();

    return pds_peer_data_clear(peer_id, data_id);
}

uint32_t pdb_n_peers(void)
{
    if (!MODULE_INITIALIZED)
    {
        return 0;
    }

    return pds_n_peers();
}

pm_peer_id_t pdb_next_peer_id_get(pm_peer_id_t prev_peer_id)
{
    if (!MODULE_INITIALIZED)
    {
        return PM_PEER_ID_INVALID;
    }

    return pds_next_peer_id_get(prev_peer_id);
}

ret_code_t pdb_raw_read(pm_peer_id_t      peer_id,
                        pm_peer_data_id_t data_id,
                        pm_peer_data_t  * p_peer_data)
{
    VERIFY_MODULE_INITIALIZED();
    return pds_peer_data_read(peer_id, data_id, p_peer_data, &p_peer_data->length_words);
}

ret_code_t pdb_raw_store(pm_peer_id_t           peer_id,
                         pm_peer_data_const_t * p_peer_data,
                         pm_store_token_t     * p_store_token)
{
    VERIFY_MODULE_INITIALIZED();

    return write_or_update(peer_id, p_peer_data->data_id, p_peer_data, p_store_token, PDS_PREPARE_TOKEN_INVALID);
}


text:
-- DROP TABLE carerecipients;

CREATE TABLE carerecipients
(
  id bigint NOT NULL,
  owner bigint,
  name character varying(250),
  modified bigint,
  intrusion double precision,
  omission double precision,
  repetition double precision,
  locating double precision,
  indentifying double precision,
  operate_appliances double precision,
  inactivity double precision,
  CONSTRAINT carerecipient_pk PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE carerecipients
  OWNER TO test;


text:
public class GenericClass<T> {
    [JetBrains.Annotations.NotNull]
    public T NonNullProperty { get; set; }
}


text:
local storyboard = require("storyboard")
local widget = require("widget")
local scene = storyboard.newScene()
local external = require("external")

function scene:willEnterScene( event )
    local group = self.view
    storyboard.removeAll()
end

function scene:createScene( event )
    local screenGroup = self.view

    local W = display.contentWidth
    local H = display.contentHeight

    local moveOption1, moveOption2, nextButton

    local shape, option1, option2, createShape, restartButton, menuButton
    local endGame = false
    local diamondDone = false
    local circleDone = false
    local squareDone = false
    local starDone = false
    local rectangleDone = false
    local ovalDone = false
    local triangleDone = false
    local option1Correct = false
    local option2Correct = false
    local randomBlackShapes, rBlack, createOptions, rand2
    local questionNumber = 1
    local scoreNum = 0

    local instr = display.newImage("images/instructions/tagalog_identShapes.png")
        instr.x = display.contentWidth * 0.5
        instr.y = display.contentHeight * 0.5
    instr:scale(0.7,0.7)
    external.intruct("tagShape")

    local bg = display.newImageRect("images/bg5.png", W, H)
    bg.x = W * 0.5
    bg.y = H * 0.5
    screenGroup:insert(bg)

    local title = display.newText("Tukuyin ang hugis", 0, 0, "Chinacat", 40)
    title.x = W * 0.2725
    title.y = H * 0.2
    title:setFillColor(0,0,0)
    screenGroup:insert(title)

    local score = display.newText("Score: "..scoreNum, 0, 0, "Chinacat", 30)
    score.x = display.contentWidth * 0.73
    score.y = display.contentHeight * 0.2
    score:setFillColor(0,0,0)
    screenGroup:insert(score)

    local message = display.newText("", 0, 0, "Chinacat", 40)
    message.x = display.contentWidth * 0.2725
    message.y = display.contentHeight * 0.5
    message:setTextColor(0,0,0)
    message.alpha = 0
    screenGroup:insert(message)

    local questionNumText = display.newText("Hugis # "..questionNumber, 0, 0, "Chinacat", 30)
    questionNumText.x = display.contentWidth * 0.725
    questionNumText.y = display.contentHeight * 0.11
    questionNumText:setFillColor(0,0,0)
    screenGroup:insert(questionNumText)

    local function randomBlackNum()
        rBlack = math.random(1,7)
        randomBlackShapes()
    end

    function randomBlackShapes()
        if rBlack == 1 then
            if diamondDone == false then
                diamondDone = true
                shape = display.newImage("images/shapeGame/diamondBlack.png")
                external.shape("diamante")
                shape.x = W * 0.27
                shape.y = H * 0.55
                screenGroup:insert(shape)
            else
                randomBlackNum()
            end
        elseif rBlack == 2 then
            if circleDone == false then
                circleDone = true
                shape = display.newImage("images/shapeGame/circleBlack.png")
                external.shape("bilog")
                shape.x = W * 0.27
                shape.y = H * 0.55
                screenGroup:insert(shape)
            else
                randomBlackNum()
            end
        elseif rBlack == 3 then
            if squareDone == false then
                squareDone = true
                shape = display.newImage("images/shapeGame/squareBlack.png")
                external.shape("parisukat")
                shape.x = W * 0.27
                shape.y = H * 0.55
                screenGroup:insert(shape)
            else
                randomBlackNum()
            end
        elseif rBlack == 4 then
            if starDone == false then
                starDone = true
                shape = display.newImage("images/shapeGame/starBlack.png")
                external.shape("bituin")
                shape.x = W * 0.27
                shape.y = H * 0.55
                screenGroup:insert(shape)
            else
                randomBlackNum()
            end
        elseif rBlack == 5 then
            if rectangleDone == false then
                rectangleDone = true
                shape = display.newImage("images/shapeGame/rectangleBlack.png")
                external.shape("parihaba")
                shape.x = W * 0.27
                shape.y = H * 0.55
                screenGroup:insert(shape)
            else
                randomBlackNum()
            end
        elseif rBlack == 6 then
            if ovalDone == false then
                ovalDone = true
                shape = display.newImage("images/shapeGame/ovalBlack.png")
                external.shape("habilog")
                shape.x = W * 0.27
                shape.y = H * 0.55
                screenGroup:insert(shape)
            else
                randomBlackNum()
            end
        elseif rBlack == 7 then
            if triangleDone == false then
                triangleDone = true
                shape = display.newImage("images/shapeGame/triangleBlack.png")
                external.shape("tatsulok")
                shape.x = W * 0.27
                shape.y = H * 0.55
                screenGroup:insert(shape)
            else
                randomBlackNum()
            end
        end
    end

    local function answerShape(r)
        if r == 1 then
            return "images/shapeGame/diamond.png"
        elseif r == 2 then
           --external.correctionEffects("correct")
            return "images/shapeGame/circle.png"
        elseif r == 3 then
            --external.correctionEffects("correct")
            return "images/shapeGame/square.png"
        elseif r == 4 then
           --external.correctionEffects("correct")
            return "images/shapeGame/star.png"
        elseif r == 5 then
            --external.correctionEffects("correct")
            return "images/shapeGame/rectangle.png"
        elseif r == 6 then
            --external.correctionEffects("correct")
            return "images/shapeGame/oval.png"
        elseif r == 7 then
            --external.correctionEffects("correct")
            return "images/shapeGame/triangle.png"
        end
    end

    local function randomShapes()
        if rand2 == 1 then
            return "images/shapeGame/diamond.png"
        elseif rand2 == 2 then
            return "images/shapeGame/circle.png"
        elseif rand2 == 3 then
            return "images/shapeGame/square.png"
        elseif rand2 == 4 then
            return "images/shapeGame/star.png"
        elseif rand2 == 5 then
            return "images/shapeGame/rectangle.png"
        elseif rand2 == 6 then
            return "images/shapeGame/oval.png"
        elseif rand2 == 7 then
            return "images/shapeGame/triangle.png"
        end
    end

    function createOptions()
        local randOption = math.random(1,2)
        rand2 = math.random(1,7)
        if randOption == 1 then
            option1Correct = true
            option1 = display.newImage(answerShape(rBlack))
            if rand2 == rBlack then
                while rand2 == rBlack do
                    rand2 = math.random(1,7)
                end
                option2 = display.newImage(randomShapes())
            else
                option2 = display.newImage(randomShapes())
            end
        else
            option2Correct = true
            option2 = display.newImage(answerShape(rBlack))
            if rand2 == rBlack then
                while rand2 == rBlack do
                    rand2 = math.random(1,7)
                end
                option1 = display.newImage(randomShapes())
            else
                option1 = display.newImage(randomShapes())
            end
        end

        option1.x = W * 0.625
        option1.y = H * 0.475
        option1:scale(0.7,0.7)

        option2.x = W * 0.875
        option2.y = H * 0.475
        option2:scale(0.7,0.7)

        screenGroup:insert(option1)
        screenGroup:insert(option2)

        option1:addEventListener("touch", moveOption1)
        option2:addEventListener("touch", moveOption2)
    end

    function createShape()

        option1Correct = false
        option2Correct = false
        if shape ~= nil then
            shape:removeSelf()
        end

        if option1 ~= nil then
            option1:removeSelf()
        end

        if option2 ~= nil then
            option2:removeSelf()
        end

        randomBlackNum()

        if endGame == false then
            createOptions()
        end
    end

    local function gameOver()
        option1.alpha = 0
        option2.alpha = 0
        shape.alpha = 0
        menuButton.alpha = 1
        questionNumText.alpha = 0
        score.size = 50
        transition.to(score, {x = title.x, y = H * 0.4, time = 500})
        transition.to(restartButton, {x = title.x, y = H * 0.75, time = 500})
        transition.to(menuButton, {x = title.x, y = H * 0.6, time = 500})
        external.correctionEffects("yehey")
        title.text = "Magaling!"
        endGame = true
    end

    local isOption1 = false
    local isOption2 = false

    moveOption1 = function(event)
        if isOption2 == false then
            isOption1 = true
            if event.phase == "ended" then
                if (option1.x <= shape.x + 100 and option1.x >= shape.x - 100) and (option1.y <= shape.y + 100 and option1.y >= shape.y - 100) then
                    if option1Correct == true then
                        scoreNum = scoreNum + 1
                        score.text = "Score: "..scoreNum
                        if questionNumber ~= 5 then
                            option1Correct = false
                            isOption1 = false
                            option1.alpha = 0
                            option2.alpha = 0
                            shape.alpha = 0
                            message.text = "Tama!"
                            external.feeds("tama")
                            message.alpha = 1
                            nextButton.alpha = 1
                        else
                            gameOver()
                        end
                    else
                        if questionNumber ~= 5 then
                            isOption1 = false
                            option1.alpha = 0
                            option2.alpha = 0
                            shape.alpha = 0
                            message.text = "Mali"
                            external.feeds("mali")
                            message.alpha = 1
                            nextButton.alpha = 1
                        else
                            gameOver()
                        end
                    end
                else
                    isOption1 = false
                    transition.to(option1, {x = W * 0.625, y = H * 0.475, xScale = 0.7, yScale = 0.7, transition=easing.inOutExpo, time = 500})
                end
            else
                if event.x <= 900 and event.x >= 60 and event.y <= 560 and event.y >= 60 then
                    option1.xScale = 1; option1.yScale = 1
                    option1.x = event.x
                    option1.y = event.y
                end
            end
        end
    end

    moveOption2 = function(event)
        if isOption1 == false then
            isOption2 = true
            if event.phase == "ended" then
                if (option2.x <= shape.x + 100 and option2.x >= shape.x - 100) and (option2.y <= shape.y + 100 and option2.y >= shape.y - 100) then
                    if option2Correct == true then
                        scoreNum = scoreNum + 1
                        score.text = "Score: "..scoreNum
                        if questionNumber ~= 5 then
                            option2Correct = false
                            isOption2 = false
                            option1.alpha = 0
                            option2.alpha = 0
                            shape.alpha = 0
                            message.text = "Tama!"
                            external.feeds("tama")
                            message.alpha = 1
                            nextButton.alpha = 1
                        else
                            gameOver()
                        end
                    else
                        if questionNumber ~= 5 then
                            isOption2 = false
                            option1.alpha = 0
                            option2.alpha = 0
                            shape.alpha = 0
                            message.text = "Mali!"
                            external.feeds("mali")
                            message.alpha = 1
                            nextButton.alpha = 1
                        else
                            gameOver()
                        end
                    end
                else
                    isOption2 = false
                    transition.to(option2, {x = W * 0.875, y = H * 0.475, xScale = 0.7, yScale = 0.7, transition=easing.inOutExpo, time = 500})
                end
            else
                if event.x <= 900 and event.x >= 60 and event.y <= 560 and event.y >= 60 then
                    option2.xScale = 1; option2.yScale = 1
                    option2.x = event.x
                    option2.y = event.y
                end
            end
        end
    end

    createShape()

    -- restartButton = widget.newButton{
    --     defaultFile = "images/buttons/restart.png",
    --     overFile = "images/buttons/restartOver.png",
    --     onRelease = function()
    --         storyboard.gotoScene("refresh_identifyShapes", "fade", 200)
    --     end,
    -- }
    -- restartButton.x = W * 0.625
    -- restartButton.y = H * 0.85
    -- restartButton:scale(1.5,1.75)
    -- screenGroup:insert(restartButton)

    menuButton = widget.newButton{
        defaultFile = "buttons/tagalog/sunod.png",
        overFile = "buttons/tagalog/sunodOver.png",
        onRelease = function()
            storyboard.gotoScene("storyTagalog_countingNumGame", "fade", 400)
        end,
    }
    menuButton.alpha = 0
    menuButton.x = W * 0.875
    menuButton.y = H * 0.85
    menuButton:scale(1.5,1.75)
    screenGroup:insert(menuButton)

    nextButton = widget.newButton
    {
        defaultFile = "images/buttons/next2.png",
        overFile = "images/buttons/next2Over.png",
        onRelease = function()
            questionNumber = questionNumber + 1
            questionNumText.text = "Hugis # "..questionNumber
            nextButton.alpha = 0
            message.alpha = 0
            createShape()
        end,
    }
    nextButton.x = W * 0.26
    nextButton.y = H * 0.75
    nextButton:scale(2,2)
    nextButton.alpha = 0
    screenGroup:insert(nextButton)

    local function disappearScreen()
        --transition.to(logo, {alpha = 0, time = 2000})
        transition.to(instr, {alpha = 0, time = 2000})
        timer.performWithDelay(1000, mainSplash, 1)
    end

    timer.performWithDelay(2000, disappearScreen, 1)
end

function scene:exitScene( event )
    external.setPreviousScene("identifyShapes")
end

scene:addEventListener( "exitScene", scene )
scene:addEventListener( "createScene", scene )
scene:addEventListener( "willEnterScene", scene )

return scene


text:
package communication

/*
import (
    "github.com/raincious/trap/trap/core/types"

    "io"
)*/

type Common struct {
}


text:
""" Use a timer to toggle the canvas background back
and forth between red and blue every 3 seconds.
Locate the appropriate call to change
the background color of the canvas."""

import simplegui

color = 'Red'

# Timer handler
def tick():
    global color
    if color == 'Red':
        color = 'Blue'
    else:
        color = 'Red'
    frame.set_canvas_background(color)

# Create frame and timer
frame = simplegui.create_frame('Counter with buttons', 200, 200)
frame.set_canvas_background(color)
timer = simplegui.create_timer(3000, tick)

# Start timer
frame.start()
timer.start()


text:
var workspace                 = require('../controllers/Workspace.js')
  , helpers                   = require('../libs/Helpers.js');

function updateWorkspace(req, res, next) {
  workspace.updateWorkspaceTitle(req.params.wsId, req.body.title, function(err, result){

    if( err ) {
      err.where = 'updateWorkspace workspace.updateWorkspaceTitle';
      helpers.errorResponse(res, 400, err);
      return;
    }

    helpers.successResponse(res, {})
  });
}

exports.updateWorkspace = updateWorkspace;


text:
package org.auraframework.impl.root.parser.handler;

import com.google.common.collect.ImmutableSet;
import org.auraframework.adapter.ConfigAdapter;
import org.auraframework.adapter.DefinitionParserAdapter;
import org.auraframework.def.DependencyDef;
import org.auraframework.def.RootDefinition;
import org.auraframework.impl.root.DependencyDefImpl;
import org.auraframework.impl.util.TypeParser;
import org.auraframework.impl.util.TypeParser.Type;
import org.auraframework.service.DefinitionService;
import org.auraframework.system.TextSource;
import org.auraframework.throwable.quickfix.DefinitionNotFoundException;
import org.auraframework.throwable.quickfix.QuickFixException;
import org.auraframework.util.AuraTextUtil;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.util.Set;

/**
 * aura:dependency tags.
 */
public class DependencyDefHandler<P extends RootDefinition> extends ParentedTagHandler<DependencyDef, P> {

    public static final String TAG = "aura:dependency";

    private static final String ATTRIBUTE_RESOURCE = "resource";
    private static final String ATTRIBUTE_TYPE = "type";

    private final static Set<String> ALLOWED_ATTRIBUTES = ImmutableSet.of(ATTRIBUTE_RESOURCE, ATTRIBUTE_TYPE);

    private DependencyDefImpl.Builder builder;

    public DependencyDefHandler() {
        super();
    }

    public DependencyDefHandler(RootTagHandler<P> parentHandler, XMLStreamReader xmlReader, TextSource<?> source,
                                boolean isInInternalNamespace, DefinitionService definitionService,
                                ConfigAdapter configAdapter, DefinitionParserAdapter definitionParserAdapter) throws DefinitionNotFoundException {
        super(parentHandler, xmlReader, source, isInInternalNamespace, definitionService, configAdapter, definitionParserAdapter);

        this.builder = new DependencyDefImpl.Builder();
        this.builder.setLocation(getLocation());
        this.builder.setParentDescriptor(parentHandler.getDefDescriptor());
        this.builder.setAccess(getAccess(isInInternalNamespace));
    }

    @Override
    public Set<String> getAllowedAttributes() {
        return ALLOWED_ATTRIBUTES;
    }

    @Override
    protected void readAttributes() {
        // make sure we handle default namespace for [resource]
        String resource = getAttributeValue(ATTRIBUTE_RESOURCE);
        Type tag = TypeParser.parseTag(resource);
        if (tag != null && isDefaultNamespaceUsed(tag.namespace)) {
            if (AuraTextUtil.isNullEmptyOrWhitespace(tag.prefix)) {
                resource = String.format("%s:%s", source.getDescriptor().getNamespace(), tag.name);
            } else {
                resource = String.format("%s://%s:%s", tag.prefix, source.getDescriptor().getNamespace(), tag.name);
            }
        }

        builder.setResource(resource);
        builder.setType(getAttributeValue(ATTRIBUTE_TYPE));
    }

    @Override
    protected void finishDefinition() {
    }

    @Override
    protected DependencyDef createDefinition() throws QuickFixException {
        return builder.build();
    }

    @Override
    public String getHandledTag() {
        return TAG;
    }

    @Override
    protected void handleChildTag() throws XMLStreamException, QuickFixException {
        error("Dependency cannot have a child tag");
    }

    @Override
    protected void handleChildText() throws XMLStreamException, QuickFixException {
        error("Dependency cannot have child text");
    }
}


text:
edges
=====

Extensions to core Lua


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace NuGet
{
    /// <summary>
    /// This repository implementation keeps track of packages that are referenced in a project but
    /// it also has a reference to the repository that actually contains the packages. It keeps track
    /// of packages in an xml file at the project root (packages.xml).
    /// </summary>
    public class PackageReferenceRepository : PackageRepositoryBase, IPackageLookup, IPackageConstraintProvider
    {
        public static readonly string PackageReferenceFile = "packages.config";
        private readonly PackageReferenceFile _packageReferenceFile;
        private readonly string _fullPath;

        public PackageReferenceRepository(IFileSystem fileSystem, ISharedPackageRepository sourceRepository)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException("fileSystem");
            }
            if (sourceRepository == null)
            {
                throw new ArgumentNullException("sourceRepository");
            }
            _packageReferenceFile = new PackageReferenceFile(fileSystem, PackageReferenceFile);
            _fullPath = fileSystem.GetFullPath(PackageReferenceFile);
            SourceRepository = sourceRepository;
        }

        public override string Source
        {
            get
            {
                return PackageReferenceFile;
            }
        }

        public override bool SupportsPrereleasePackages
        {
            get { return true; }
        }

        private ISharedPackageRepository SourceRepository
        {
            get;
            set;
        }

        private string PackageReferenceFileFullPath
        {
            get
            {
                return _fullPath;
            }
        }

        public PackageReferenceFile ReferenceFile
        {
            get
            {
                return _packageReferenceFile;
            }
        }

        public override IQueryable<IPackage> GetPackages()
        {
            return GetPackagesCore().AsSafeQueryable();
        }

        private IEnumerable<IPackage> GetPackagesCore()
        {
            foreach (var reference in _packageReferenceFile.GetPackageReferences())
            {
                IPackage package;

                if (String.IsNullOrEmpty(reference.Id) ||
                    reference.Version == null ||
                    !SourceRepository.TryFindPackage(reference.Id, reference.Version, out package))
                {

                    // Skip bad entries
                    continue;
                }
                else
                {
                    yield return package;
                }
            }
        }

        public override void AddPackage(IPackage package)
        {
            _packageReferenceFile.AddEntry(package.Id, package.Version);

            // Notify the source repository every time we add a new package to the repository.
            // This doesn't really need to happen on every package add, but this is over agressive
            // to combat scenarios where the 2 repositories get out of sync. If this repository is already
            // registered in the source then this will be ignored
            SourceRepository.RegisterRepository(PackageReferenceFileFullPath);
        }

        public override void RemovePackage(IPackage package)
        {
            if (_packageReferenceFile.DeleteEntry(package.Id, package.Version))
            {
                // Remove the repository from the source
                SourceRepository.UnregisterRepository(PackageReferenceFileFullPath);
            }
        }

        public IPackage FindPackage(string packageId, SemanticVersion version)
        {
            if (!_packageReferenceFile.EntryExists(packageId, version))
            {
                return null;
            }

            return SourceRepository.FindPackage(packageId, version);
        }

        public void RegisterIfNecessary()
        {
            if (GetPackages().Any())
            {
                SourceRepository.RegisterRepository(PackageReferenceFileFullPath);
            }
        }

        public IVersionSpec GetConstraint(string packageId)
        {
            // Find the reference entry for this package
            PackageReference reference = _packageReferenceFile.GetPackageReferences().FirstOrDefault(p => p.Id.Equals(packageId, StringComparison.OrdinalIgnoreCase));
            if (reference != null)
            {
                return reference.VersionConstraint;
            }
            return null;
        }
    }
}