text:
namespace Google.Cloud.VMMigration.V1.Snippets
{
    // [START vmmigration_v1_generated_VmMigration_UpdateTargetProject_async]
    using Google.Cloud.VMMigration.V1;
    using Google.LongRunning;
    using Google.Protobuf.WellKnownTypes;
    using System.Threading.Tasks;

    public sealed partial class GeneratedVmMigrationClientSnippets
    {
        /// <summary>Snippet for UpdateTargetProjectAsync</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public async Task UpdateTargetProjectRequestObjectAsync()
        {
            // Create client
            VmMigrationClient vmMigrationClient = await VmMigrationClient.CreateAsync();
            // Initialize request argument(s)
            UpdateTargetProjectRequest request = new UpdateTargetProjectRequest
            {
                UpdateMask = new FieldMask(),
                TargetProject = new TargetProject(),
                RequestId = "",
            };
            // Make the request
            Operation<TargetProject, OperationMetadata> response = await vmMigrationClient.UpdateTargetProjectAsync(request);

            // Poll until the returned long-running operation is complete
            Operation<TargetProject, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
            // Retrieve the operation result
            TargetProject result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation<TargetProject, OperationMetadata> retrievedResponse = await vmMigrationClient.PollOnceUpdateTargetProjectAsync(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                TargetProject retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END vmmigration_v1_generated_VmMigration_UpdateTargetProject_async]
}


text:
// This file is automatically generated.

package adila.db;

/*
 * Positivo YPY7 wifi
 *
 * DEVICE: YPY_07STA
 * MODEL: YPY_07STA
 */
final class ypy5f07sta_ypy5f07sta {
    public static final String DATA = "Positivo|YPY7 wifi|";
}

redpajama_set_name: RedPajamaGithub


text:
elementAt :: [a] -> Int -> a
elementAt [] _ = error "Empty list"
elementAt (x:_) 1 = x
elementAt (x:xs) k
    |k<1 = error "Index out of bounds"
    |otherwise = elementAt xs (k-1)


text:
Contact Us
----------
Join the KM3Pipe channel here: https://chat.km3net.de/channel/km3pipe

Filing Bugs or Feature Requests
-------------------------------

Please **always** create an issue when you encounter any bugs, problems or
need a new feature. Emails and private messages are not meant to communicate
such things!

Use the appropriate template and file a new issue here:
https://git.km3net.de/km3py/km3pipe/issues

You can browse all the issues here: https://git.km3net.de/km3py/km3pipe/issues

Please follow the instructions in the templates to provide all the
necessary information which will help other people to understand the
situation.

Improve KM3Pipe
---------------

Check out our KanBan board https://git.km3net.de/km3py/km3pipe/boards,
which shows all the open issues in three columns:

- *discussion*: The issues which are yet to be discussed (e.g. not clear how to proceed)
- *todo*: Issues tagged with this label are ready to be tackled
- *doing*: These issues are currently "work in progress". They can however be
  put tossed back to *todo* column at any time if the development is suspended.

Here is the recommended workflow if you want to improve KM3Pipe. This is a
standard procedure for collaborative software development, nothing exotic!

Feel free to contribute ;)

Make a Fork of KM3Pipe
~~~~~~~~~~~~~~~~~~~~~~

You create a fork (your full own copy of the
repository), change the code and when you are happy with the changes, you create
a merge request, so we can review, discuss and add your contribution.
Merge requests are automatically tested on our GitLab CI server and you
don't have to do anything special.

Go to https://git.km3net.de/km3py/km3pipe and click on "Fork".

After that, you will have a full copy of KM3Pipe with write access under an URL
like this: ``https://git.km3net.de/your_git_username/km3pipe``

Clone your Fork to your PC
~~~~~~~~~~~~~~~~~~~~~~~~~~

Get a local copy to work on (use the SSH address `git@git...`, not the HTTP one)::

    git clone git@git.km3net.de:your_git_username/km3pipe.git

Now you need to add a reference to the original repository, so you can sync your
own fork with the KM3Pipe repository::

    cd km3pipe
    git remote add upstream git@git.km3net.de:km3py/km3pipe.git

Keep your Fork Up to Date
~~~~~~~~~~~~~~~~~~~~~~~~~

To get the most recent commits (including all branches), run::

    git fetch upstream

This will download all the missing commits and branches which are now accessible
using the ``upstream/...`` prefix::

    $ git fetch upstream
    From git.km3net.de:km3py/km3pipe
     * [new branch]        gitlab_jenkins_ci_test -> upstream/gitlab_jenkins_ci_test
     * [new branch]        legacy                 -> upstream/legacy
     * [new branch]        master                 -> upstream/master

If you want to update for example your **own** ``master`` branch
to contain all the changes on the official ``master`` branch of KM3Pipe,
switch to it first with::

    git checkout master

and then merge the ``upstream/master`` into it::

    git merge upstream/master

Make sure to regularly ``git fetch upstream`` and merge changes to your own branches.

Push your changes to Gitlab regularly
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Make sure to keep your fork up to date on the GitLab server by pushing
all your commits regularly using::

    git push

Install in Developer Mode
~~~~~~~~~~~~~~~~~~~~~~~~~

KM3Pipe can be installed in ``dev-mode``, which means, it links itself to your
site-packages and you can edit the sources and test them without the need
to reinstall KM3Pipe all the time. Although you will need to restart any
``python``, ``ipython`` or ``jupyter``-notebook (only the kernel!) if you
imported km3pipe before  you made the changes.

Go to your own fork folder (as described above) and check out the branch you
want to work on::

    git checkout master  # the main development branch (should always be stable)
    make install-dev

Running the Test Suite
~~~~~~~~~~~~~~~~~~~~~~

Make sure to run the test suite first to see if everything is working
correctly::

    $ make test

This should give you a green bar, with an output like this::

    $ make test
    py.test --junitxml=./reports/junit.xml km3pipe
    ================================== test session starts ===================================
    platform darwin -- Python 3.6.4, pytest-3.5.1, py-1.5.3, pluggy-0.6.0
    rootdir: ~/Dev/km3pipe, inifile: pytest.ini
    plugins: pylint-0.9.0, flake8-1.0.1, cov-2.5.1
    collected 309 items

    km3pipe/io/tests/test_aanet.py ....                         [  1%]
    km3pipe/io/tests/test_ch.py .                               [  1%]
    km3pipe/io/tests/test_clb.py ........                       [  4%]
    km3pipe/io/tests/test_daq.py ........                       [  6%]
    ...
    ...
    ...
    km3pipe/tests/test_style.py ........................        [ 87%]
    km3pipe/tests/test_testing.py ..                            [ 88%]
    km3pipe/tests/test_time.py ..................               [ 93%]
    km3pipe/tests/test_tools.py ...................             [100%]

    ----- generated xml file: ~/Dev/km3pipe/reports/junit.xml ------
    =================== 467 passed in 6.21 seconds ===================

Run the tests every time you make changes to see if you broke anything! It usually
takes just a few seconds and ensures that you don't break existing code. It's
also an easy way to spot syntax errors ;)

You can also start a script which will watch for file changes and retrigger
a test suite run every time for you. It's a nice practice to have a terminal
open running this script to check your test results continuously::

    make test-loop

Time to Code
~~~~~~~~~~~~

We develop new features and fix bugs on separate branches and merge them
back to ``master`` when they are stable. Merge requests (see below) are also
pointing towards this branch.

If you are working on your own fork, you can stay on your own ``master`` branch
and create merge requests from that.

Code Style
~~~~~~~~~~

Make sure to run ``black`` over the code, which ensures that the code style
matches the one we love and respect. We have a tool which makes it easy::

    make black

Create a Merge Request (aka Pull Request)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Go to https://git.km3net.de/km3py/km3pipe/merge_requests/new and select
your source branch, which contains the changes you want to be included in KM3Pipe
and select the ``master`` branch as target branch.

That's it, the merge will be accepted if everything is OK ;)

If you want to join the KM3Pipe dev-team, let us know!:)


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<config>
    <modules>
        <Packt_Shipme>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Mage_Shipping />
            </depends>
        </Packt_Shipme>
    </modules>
</config>


text:
Handlebars.registerHelper('filename', function(name) {

    return name.split('/').pop();
});


text:
package iso20022

// Indicates one of the constraints of a range of business values.
type Term1 struct {

	// Provides the relationship between a variable and a fixed value.
	Operator *Operator1Code `xml:"Oprtr"`

	// Indicates the value.
	Value *RateOrAbsoluteValue1Choice `xml:"Val"`
}

func (t *Term1) SetOperator(value string) {
	t.Operator = (*Operator1Code)(&value)
}

func (t *Term1) AddValue() *RateOrAbsoluteValue1Choice {
	t.Value = new(RateOrAbsoluteValue1Choice)
	return t.Value
}


text:
package core

import (
	"testing"
	"time"

	"github.com/af83/edwig/model"
)

func Test_EstimatedTimeTableBroadcaster_Create_Events(t *testing.T) {
	model.SetDefaultClock(model.NewFakeClock())

	referentials := NewMemoryReferentials()
	referential := referentials.New("Un Referential Plutot Cool")
	referential.model = model.NewMemoryModel()

	referential.model.SetBroadcastSMChan(referential.broacasterManager.GetStopMonitoringBroadcastEventChan())
	referential.broacasterManager.Start()
	defer referential.broacasterManager.Stop()

	partner := referential.Partners().New("Un Partner tout autant cool")
	partner.Settings["remote_objectid_kind"] = "internal"
	partner.ConnectorTypes = []string{TEST_ESTIMATED_TIMETABLE_SUBSCRIPTION_BROADCASTER}
	partner.RefreshConnectors()
	referential.Partners().Save(partner)

	connector, _ := partner.Connector(TEST_ESTIMATED_TIMETABLE_SUBSCRIPTION_BROADCASTER)

	line := referential.Model().Lines().New()
	line.Save()

	objectid := model.NewObjectID("internal", string(line.Id()))
	line.SetObjectID(objectid)

	reference := model.Reference{
		ObjectId: &objectid,
		Type:     "Line",
	}

	vj := referential.Model().VehicleJourneys().New()
	vj.LineId = line.Id()
	vj.Save()

	sv := referential.Model().StopVisits().New()
	sv.VehicleJourneyId = vj.Id()

	subs := partner.Subscriptions().New("EstimatedTimeTable")
	subs.Save()
	subs.CreateAddNewResource(reference)
	subs.SetExternalId("externalId")
	subs.Save()

	stopVisit := referential.Model().StopVisits().New()

	time.Sleep(5 * time.Millisecond) // Wait for the goRoutine to start ...
	stopVisit.Save()

	time.Sleep(5 * time.Millisecond) // Wait for the Broadcaster and Connector to finish their work
	if len(connector.(*TestETTSubscriptionBroadcaster).events) != 1 {
		t.Error("1 event should have been generated got: ", len(connector.(*TestETTSubscriptionBroadcaster).events))
	}
}


text:
package com.jameswolfeoliver.pigeon.Server.Endpoints.Contacts;

import com.jameswolfeoliver.pigeon.Database.SqlWrappers.ContactsWrapper;
import com.jameswolfeoliver.pigeon.Managers.ContactCacheManager;
import com.jameswolfeoliver.pigeon.Models.ClientResponses.Error;
import com.jameswolfeoliver.pigeon.Models.Contact;
import com.jameswolfeoliver.pigeon.Server.Endpoints.Endpoints;
import com.jameswolfeoliver.pigeon.Server.Endpoints.RestEndpoint;
import com.jameswolfeoliver.pigeon.Server.Sessions.SessionManager;
import com.jameswolfeoliver.pigeon.Utilities.PigeonApplication;

import org.nanohttpd.protocols.http.IHTTPSession;
import org.nanohttpd.protocols.http.response.Response;
import org.nanohttpd.protocols.http.response.Status;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;

public class ContactsEndpoint extends RestEndpoint {

    public ContactsEndpoint(SessionManager sessionManager) {
        super(sessionManager);
    }

    @Override
    protected Response onGet(IHTTPSession session) {
        final Matcher idMatcher = Endpoints.CONTACT_URI_PATTERN.matcher(session.getUri());
        final Map<String, List<String>> params = session.getParameters();
        if (idMatcher.find()) {
            return buildJsonResponse(onGetByIds(Collections.singletonList(Integer.parseInt(idMatcher.group(1)))), Status.OK);
        } else if (params != null && params.containsKey("id")) {
            final List<Integer> contactIds = new ArrayList<>();
            for (String id : params.get("id")) {
                try {
                    contactIds.add(Integer.parseInt(id));
                } catch (NumberFormatException e) {
                    return buildJsonError(Error.Codes.YOUR_FAULT, "Bad query", Status.BAD_REQUEST);
                }
            }
            return buildJsonResponse(onGetByIds(contactIds), Status.OK);
        } else if (params != null && params.containsKey("phoneNumber")) {
            final List<Long> contactNumbers = new ArrayList<>();
            for (String id : params.get("phoneNumber")) {
                try {
                    contactNumbers.add(Long.parseLong(id));
                } catch (NumberFormatException e) {
                    return buildJsonError(Error.Codes.YOUR_FAULT, "Bad query", Status.BAD_REQUEST);
                }
            }
            return buildJsonResponse(onGetNumbers(contactNumbers), Status.OK);
        } else if (params == null || params.isEmpty()) {
            return buildJsonResponse(PigeonApplication.getGson().toJson(ContactCacheManager
                    .getInstance().updateNow().getContacts()), Status.OK);
        }
        return buildJsonError(Error.Codes.YOUR_FAULT, "Unrecognized", Status.BAD_REQUEST);
    }

    private String onGetByIds(final List<Integer> contactIds) {
        final ContactsWrapper contactsWrapper = new ContactsWrapper();
        final Iterable<Contact> conversations = contactsWrapper.find(() -> contactsWrapper.selectByIds(contactIds))
                .toBlocking().toIterable();
        final List<Contact> contactList = new ArrayList<>();
        final Iterator<Contact> conversationIterator = conversations.iterator();
        while (conversationIterator.hasNext()) contactList.add(conversationIterator.next());
        return PigeonApplication.getGson().toJson(contactList);
    }

    private String onGetNumbers(final List<Long> phoneNumbers) {
        return PigeonApplication.getGson().toJson(ContactCacheManager.getInstance().updateNow().getContacts(phoneNumbers));
    }

    @Override
    protected Response onPost(IHTTPSession session) {
        // TODO implement create contact
        return buildJsonError(Error.Codes.MY_FAULT, "Not implemented", Status.NOT_IMPLEMENTED);
    }
}


text:
Display money format and its filthy currencies, for all money lovers out there.

## Installation

```
npm install money-currencies --save
```

## Usage

```
var MoneyCurrency = require('money-currencies');

mc = new MoneyCurrency('USD');
console.log(mc.moneyFormat(13)) // $13
console.log(mc.moneyWithCurrencyFormat(13)) // $13 USD
```

## Tests

`money-currencies` has been tested on various version of Node.js, including:

- 0.12
- 0.11
- 0.10
- iojs
- iojs-v1.0.4

```
npm test
```

## Contributing

Contributions to the project are welcome. Feel free to fork and improve.
I do my best accept pull requests in a timely manor,
especially when tests and updated docs are included.

## License

Copyright (c) 2015 Alireza Savand, contributors.

Released under the [MIT license](https://tldrlegal.com/license/mit-license).


text:
// Qt includes
#include <QDebug>
#include <QApplication>
#include <QTimer>

#if (QT_VERSION < 0x50000)
#include <QCleanlooksStyle>
#endif

// CTK includes
#include <ctkCheckableComboBox.h>

// STD includes
#include <cstdlib>
#include <iostream>

//-----------------------------------------------------------------------------
int ctkCheckableComboBoxTest1(int argc, char * argv [] )
{
  // QCleanlooksStyle is the only style that doesn't show the checkboxes by
  // default. Test it with it
#if (QT_VERSION < 0x50000)
  QApplication::setStyle(new QCleanlooksStyle);
#endif
  QApplication app(argc, argv);

  ctkCheckableComboBox comboBox;
  comboBox.addItem("toto");
  comboBox.addItem("tata");
  comboBox.addItem("titi");
  comboBox.addItem(comboBox.style()->standardIcon(QStyle::SP_FileIcon),"tutu");

  if (comboBox.checkedIndexes().count() != 0 ||
      comboBox.allChecked() ||
      !comboBox.noneChecked())
    {
    std::cerr << "ctkCheckableComboBox has wrong default values\n"
              << " count:" << comboBox.checkedIndexes().count()
              << " all:" << comboBox.allChecked()
              << " none:" << comboBox.noneChecked() << std::endl;
    return EXIT_FAILURE;
    }

  int row = 0;
  QModelIndex firstIndex = comboBox.model()->index(row,0);
  comboBox.setCheckState(firstIndex, Qt::Checked);

  if (comboBox.checkState(firstIndex) != Qt::Checked)
    {
    std::cerr << "ctkCheckableComboBox::setCheckedState failed\n"
              << static_cast<int>(comboBox.checkState(firstIndex))
              << std::endl;
    return EXIT_FAILURE;
    }

  if (comboBox.checkedIndexes().count() != 1 ||
      comboBox.allChecked() ||
      comboBox.noneChecked())
    {
    std::cerr << "ctkCheckableComboBox::setCheckedState(first) failed\n"
              << " count:" << comboBox.checkedIndexes().count()
              << " all:" << comboBox.allChecked()
              << " none:" << comboBox.noneChecked() << std::endl;
    return EXIT_FAILURE;
    }

  // Check all the items
  QModelIndex nextIndex = firstIndex;
  while( (nextIndex = nextIndex.sibling(++row, 0)).isValid())
    {
    comboBox.setCheckState(nextIndex, Qt::Checked);
    }

  if (comboBox.checkedIndexes().count() != 4 ||
      !comboBox.allChecked() ||
      comboBox.noneChecked())
    {
    std::cerr << "ctkCheckableComboBox::setCheckedState(all) failed\n"
              << " count:" << comboBox.checkedIndexes().count()
              << " all:" << comboBox.allChecked()
              << " none:" << comboBox.noneChecked() << std::endl;
    return EXIT_FAILURE;
    }

  comboBox.show();
  if (argc < 2 || QString(argv[1]) != "-I" )
    {
    QTimer::singleShot(200, &app, SLOT(quit()));
    }

  return app.exec();
}


text:
module.exports = (commandKeys, execCommand) => {
  // Generating tab:jump array
  const tabJump = [];
  for (let i = 1; i <= 9; i++) {
    // 9 is a special number because it means 'last'
    const label = i === 9 ? 'Last' : `${i}`;
    tabJump.push({
      label: label,
      accelerator: commandKeys[`tab:jump:${label.toLowerCase()}`]
    });
  }

  return {
    role: 'window',
    submenu: [
      {
        role: 'minimize',
        accelerator: commandKeys['window:minimize']
      },
      {
        type: 'separator'
      },
      {
        // It's the same thing as clicking the green traffc-light on macOS
        role: 'zoom',
        accelerator: commandKeys['window:zoom']
      },
      {
        label: 'Select Tab',
        submenu: [
          {
            label: 'Previous',
            accelerator: commandKeys['tab:prev'],
            click: (item, focusedWindow) => {
              execCommand('tab:prev', focusedWindow);
            }
          },
          {
            label: 'Next',
            accelerator: commandKeys['tab:next'],
            click: (item, focusedWindow) => {
              execCommand('tab:next', focusedWindow);
            }
          },
          {
            type: 'separator'
          },
          ...tabJump
        ]
      },
      {
        type: 'separator'
      },
      {
        label: 'Select Pane',
        submenu: [
          {
            label: 'Previous',
            accelerator: commandKeys['pane:prev'],
            click: (item, focusedWindow) => {
              execCommand('pane:prev', focusedWindow);
            }
          },
          {
            label: 'Next',
            accelerator: commandKeys['pane:next'],
            click: (item, focusedWindow) => {
              execCommand('pane:next', focusedWindow);
            }
          }
        ]
      },
      {
        type: 'separator'
      },
      {
        role: 'front'
      },
      {
        role: 'togglefullscreen',
        accelerator: commandKeys['window:toggleFullScreen']
      }
    ]
  };
};


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

namespace Application03
{
	static class Program
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main()
		{
			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			//try
			//{
				Application.Run(new StatGrapher());
			//}
			//catch(Exception e)
			//{
			//  MessageBox.Show(e.TargetSite.ToString() + "\n\n" + e.ToString());
			//}
		}
	}
}


text:
<?php

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

defined('MOODLE_INTERNAL') || die();

$string['downloadas'] = '下載表格上的資料成為';
$string['downloadcsv'] = '一個以英文逗點分隔數值的文字檔';
$string['downloadexcel'] = '一個Microsoft Execel試算表';
$string['downloadods'] = '一個OpenDoucument試算表(ODS)';
$string['downloadoptions'] = '選擇下載用選項';
$string['downloadtsv'] = '一個以tab鍵來分隔數值的文字檔';
$string['downloadxhtml'] = '一個未分頁的XHTM文件';


text: Welcome, {{user.username}}


text:
package com.badlogic.gdx.maps.tiled.renderers;

import static com.badlogic.gdx.graphics.g2d.Batch.*;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTile;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.tiles.AnimatedTiledMapTile;

public class HexagonalTiledMapRenderer extends BatchTiledMapRenderer {
	private boolean yDown = false;

	public boolean isYdown() {
		return yDown;
	}

	public void setYDown(boolean yDown) {
		this.yDown = yDown;
	}

	public HexagonalTiledMapRenderer (TiledMap map) {
		super(map);
	}

	public HexagonalTiledMapRenderer (TiledMap map, float unitScale) {
		super(map, unitScale);
	}

	public HexagonalTiledMapRenderer (TiledMap map, Batch batch) {
		super(map, batch);
	}

	public HexagonalTiledMapRenderer (TiledMap map, float unitScale, Batch batch) {
		super(map, unitScale, batch);
	}

	private float[] vertices = new float[20];

	@Override
	public void renderTileLayer(TiledMapTileLayer layer) {
		final Color batchColor = spriteBatch.getColor();
		final float color = Color.toFloatBits(batchColor.r, batchColor.g, batchColor.b, batchColor.a * layer.getOpacity());

		final int layerWidth = layer.getWidth();
		final int layerHeight = layer.getHeight();

		final float layerTileWidth = layer.getTileWidth() * unitScale;
		final float layerTileHeight = layer.getTileHeight() * unitScale;

		final float layerTileWidth25 = layerTileWidth * 0.25f;
		final float layerTileWidth75 = layerTileWidth * 0.75f;

		final float layerTileHeight50 = layerTileHeight * 0.50f;
		final float layerTileHeight150 = layerTileHeight * 1.50f;

		final int col1 = Math.max(0, (int) (((viewBounds.x - layerTileWidth25) / layerTileWidth75)));
		final int col2 = Math.min(layerWidth, (int) ((viewBounds.x + viewBounds.width + layerTileWidth75) / layerTileWidth75));

		final int row1 = Math.max(0, (int) ((viewBounds.y / layerTileHeight150)));
		final int row2 = Math.min(layerHeight, (int) ((viewBounds.y + viewBounds.height + layerTileHeight150) / layerTileHeight));

		final float[] vertices = this.vertices;

		for (int row = row1; row < row2; row++) {
			for (int col = col1; col < col2; col++) {
				float x = layerTileWidth75 * col;
				float y = (col % 2 == (yDown ? 0 : 1) ? 0 : layerTileHeight50) + (layerTileHeight * row);

				final TiledMapTileLayer.Cell cell = layer.getCell(col, row);
				if(cell == null) {
					x += layerTileWidth;
					continue;
				}
				final TiledMapTile tile = cell.getTile();
				if (tile != null) {
					if (tile instanceof AnimatedTiledMapTile) continue;

					final boolean flipX = cell.getFlipHorizontally();
					final boolean flipY = cell.getFlipVertically();
					final int rotations = cell.getRotation();

					TextureRegion region = tile.getTextureRegion();

					float x1 = x;
					float y1 = y;
					float x2 = x1 + region.getRegionWidth() * unitScale;
					float y2 = y1 + region.getRegionHeight() * unitScale;

					float u1 = region.getU();
					float v1 = region.getV2();
					float u2 = region.getU2();
					float v2 = region.getV();

					vertices[X1] = x1;
					vertices[Y1] = y1;
					vertices[C1] = color;
					vertices[U1] = u1;
					vertices[V1] = v1;

					vertices[X2] = x1;
					vertices[Y2] = y2;
					vertices[C2] = color;
					vertices[U2] = u1;
					vertices[V2] = v2;

					vertices[X3] = x2;
					vertices[Y3] = y2;
					vertices[C3] = color;
					vertices[U3] = u2;
					vertices[V3] = v2;

					vertices[X4] = x2;
					vertices[Y4] = y1;
					vertices[C4] = color;
					vertices[U4] = u2;
					vertices[V4] = v1;

					if (flipX) {
						float temp = vertices[U1];
						vertices[U1] = vertices[U3];
						vertices[U3] = temp;
						temp = vertices[U2];
						vertices[U2] = vertices[U4];
						vertices[U4] = temp;
					}
					if (flipY) {
						float temp = vertices[V1];
						vertices[V1] = vertices[V3];
						vertices[V3] = temp;
						temp = vertices[V2];
						vertices[V2] = vertices[V4];
						vertices[V4] = temp;
					}
					if (rotations == 2) {
						float tempU = vertices[U1];
						vertices[U1] = vertices[U3];
						vertices[U3] = tempU;
						tempU = vertices[U2];
						vertices[U2] = vertices[U4];
						vertices[U4] = tempU;
						float tempV = vertices[V1];
						vertices[V1] = vertices[V3];
						vertices[V3] = tempV;
						tempV = vertices[V2];
						vertices[V2] = vertices[V4];
						vertices[V4] = tempV;
						break;
					}
					spriteBatch.draw(region.getTexture(), vertices, 0, 20);
				}
			}
		}

	}

	@Override
	public void renderObject(MapObject object) {

	}
}


text:
var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure();

var testCase = require('../deps/nodeunit').testCase,
  debug = require('util').debug,
  inspect = require('util').inspect,
  nodeunit = require('../deps/nodeunit'),
  gleak = require('../tools/gleak'),
  Db = mongodb.Db,
  Cursor = mongodb.Cursor,
  Collection = mongodb.Collection,
  Server = mongodb.Server;

var MONGODB = 'integration_tests';
var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)});

// Define the tests, we want them to run as a nested test so we only clean up the
// db connection once
var tests = testCase({
  setUp: function(callback) {
    client.open(function(err, db_p) {
      if(numberOfTestsRun == Object.keys(tests).length) {
        // If first test drop the db
        client.dropDatabase(function(err, done) {
          callback();
        });
      } else {
        return callback();
      }
    });
  },

  tearDown: function(callback) {
    numberOfTestsRun = numberOfTestsRun - 1;
    // Drop the database and close it
    if(numberOfTestsRun <= 0) {

      // client.dropDatabase(function(err, done) {
        client.close();
        callback();
      // });
    } else {
      client.close();
      callback();
    }
  },

  shouldCorrectlyCallValidateCollection : function(test) {
    var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)});
    fs_client.bson_deserializer = client.bson_deserializer;
    fs_client.bson_serializer = client.bson_serializer;
    fs_client.pkFactory = client.pkFactory;

    fs_client.open(function(err, fs_client) {
      fs_client.dropDatabase(function(err, done) {
        fs_client.collection('test', function(err, collection) {
          collection.insert({'a':1}, {safe:true}, function(err, doc) {
            fs_client.admin(function(err, adminDb) {
              adminDb.addUser('admin', 'admin', function(err, result) {
                adminDb.authenticate('admin', 'admin', function(err, replies) {
                  adminDb.validateCollection('test', function(err, doc) {
                    // Pre 1.9.1 servers
                    if(doc.result != null) {
                      test.ok(doc.result != null);
                      test.ok(doc.result.match(/firstExtent/) != null);
                    } else {
                      test.ok(doc.firstExtent != null);
                    }

                    fs_client.close();
                    test.done();
                  });
                });
              });
            });
          });
        });
      });
    });
  },

  shouldCorrectlySetDefaultProfilingLevel : function(test) {
    var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)});
    fs_client.bson_deserializer = client.bson_deserializer;
    fs_client.bson_serializer = client.bson_serializer;
    fs_client.pkFactory = client.pkFactory;

    fs_client.open(function(err, fs_client) {
      fs_client.dropDatabase(function(err, done) {
        fs_client.collection('test', function(err, collection) {
          collection.insert({'a':1}, {safe:true}, function(err, doc) {
            fs_client.admin(function(err, adminDb) {
              adminDb.addUser('admin', 'admin', function(err, result) {
                adminDb.authenticate('admin', 'admin', function(err, replies) {
                  adminDb.profilingLevel(function(err, level) {
                    test.equal("off", level);

                    fs_client.close();
                    test.done();
                  });
                });
              });
            });
          });
        });
      });
    });
  },

  shouldCorrectlyChangeProfilingLevel : function(test) {
    var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)});
    fs_client.bson_deserializer = client.bson_deserializer;
    fs_client.bson_serializer = client.bson_serializer;
    fs_client.pkFactory = client.pkFactory;

    fs_client.open(function(err, fs_client) {
      fs_client.dropDatabase(function(err, done) {
        fs_client.collection('test', function(err, collection) {
          collection.insert({'a':1}, {safe:true}, function(err, doc) {
            fs_client.admin(function(err, adminDb) {
              adminDb.authenticate('admin', 'admin', function(err, replies) {
                adminDb.setProfilingLevel('slow_only', function(err, level) {
                  adminDb.profilingLevel(function(err, level) {
                    test.equal('slow_only', level);

                    adminDb.setProfilingLevel('off', function(err, level) {
                      adminDb.profilingLevel(function(err, level) {
                        test.equal('off', level);

                        adminDb.setProfilingLevel('all', function(err, level) {
                          adminDb.profilingLevel(function(err, level) {
                            test.equal('all', level);

                            adminDb.setProfilingLevel('medium', function(err, level) {
                              test.ok(err instanceof Error);
                              test.equal("Error: illegal profiling level value medium", err.message);

                              fs_client.close();
                              test.done();
                            });
                          })
                        });
                      })
                    });
                  })
                });
              });
            });
          });
        });
      });
    });
  },

  shouldCorrectlySetAndExtractProfilingInfo : function(test) {
    var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)});
    fs_client.bson_deserializer = client.bson_deserializer;
    fs_client.bson_serializer = client.bson_serializer;
    fs_client.pkFactory = client.pkFactory;

    fs_client.open(function(err, fs_client) {
      fs_client.dropDatabase(function(err, done) {
        fs_client.collection('test', function(err, collection) {
          collection.insert({'a':1}, {safe:true}, function(doc) {
            fs_client.admin(function(err, adminDb) {
              adminDb.authenticate('admin', 'admin', function(err, replies) {
                adminDb.setProfilingLevel('all', function(err, level) {
                  collection.find(function(err, cursor) {
                    cursor.toArray(function(err, items) {
                      adminDb.setProfilingLevel('off', function(err, level) {
                        adminDb.profilingInfo(function(err, infos) {
                          test.ok(infos.constructor == Array);
                          test.ok(infos.length >= 1);
                          test.ok(infos[0].ts.constructor == Date);
                          test.ok(infos[0].millis.constructor == Number);

                          fs_client.close();
                          test.done();
                        });
                      });
                    });
                  });
                });
              });
            });
          });
        });
      });
    });
  },

  // run this last
  noGlobalsLeaked : function(test) {
    var leaks = gleak.detectNew();
    test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
    test.done();
  }
})

// Stupid freaking workaround due to there being no way to run setup once for each suite
var numberOfTestsRun = Object.keys(tests).length;
// Assign out tests
module.exports = tests;


text:
<?xml version="1.0" encoding="UTF-8"?>
<billing_info href="http://api.test.host/v2/accounts/1/billing_info" type="credit_card">
  <account href="http://api.test.host/v2/accounts/1"/>
  <first_name>Verena</first_name>
  <last_name>Example</last_name>
  <company nil="nil"></company>
  <address1>123 Main St.</address1>
  <address2 nil="nil"></address2>
  <city>San Francisco</city>
  <state>CA</state>
  <zip>94105</zip>
  <country>US</country>
  <phone nil="nil"></phone>
  <vat_number>US1234567890</vat_number>
  <ip_address>127.0.0.1</ip_address>
  <ip_address_country>US</ip_address_country>
  <card_type>Visa</card_type>
  <year type="integer">2015</year>
  <month type="integer">11</month>
  <first_six>411111</first_six>
  <last_four>1111</last_four>
</billing_info>


text:
package io.lcs.framework.utils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URI;

/**
 * Created by lcs on 15-5-25.
 */
public class Image {
	private static final int IMAGE_SIZE = 400;

	/**
	 * 对图片进行处理,如果不是400*400的再进行放缩
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static BufferedImage getSearch(String url) throws IOException {
		BufferedImage img = ImageIO.read( URI.create(URLTool.prase(url)).toURL().openStream() );// toBufferedImage(Toolkit.getDefaultToolkit().getImage());
		int height = img.getHeight();
		int width = img.getWidth();

		if (width == IMAGE_SIZE && height == IMAGE_SIZE) return img;

		return resize(url);
	}

	private static BufferedImage resize ( String url ) throws IOException {
		BufferedImage img = toBufferedImage(Toolkit.getDefaultToolkit().getImage(URI.create(url).toURL()));
		int height = img.getHeight();
		int width = img.getWidth();

		if (width > height) {
			height = height * IMAGE_SIZE / width;
			width = IMAGE_SIZE;
		} else {
			width = width * IMAGE_SIZE / height;
			height = IMAGE_SIZE;
		}

		BufferedImage newImage = new BufferedImage(width, height, img.getType());
		Graphics g = newImage.getGraphics();
		g.drawImage(img, 0, 0, width, height, null);
		g.dispose();

	//	ImageIO.write(newImage, "JPG", new File("/tmp/newImage.jpg"));
		return newImage;

	}
	private static BufferedImage toBufferedImage(java.awt.Image image) {
		if (image instanceof BufferedImage) {
			return (BufferedImage) image;
		}

		// This code ensures that all the pixels in the image are loaded
		image = new ImageIcon(image).getImage();

		// Determine if the image has transparent pixels; for this method's
		// implementation, see e661 Determining If an Image Has Transparent Pixels
		//boolean hasAlpha = hasAlpha(image);

		// Create a buffered image with a format that's compatible with the screen
		BufferedImage bimage = null;
		GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
		try {
			// Determine the type of transparency of the new buffered image
			int transparency = Transparency.OPAQUE;
	       /* if (hasAlpha) {
                transparency = Transparency.BITMASK;
            }*/

			// Create the buffered image
			GraphicsDevice gs = ge.getDefaultScreenDevice();
			GraphicsConfiguration gc = gs.getDefaultConfiguration();
			bimage = gc.createCompatibleImage(
					image.getWidth(null), image.getHeight(null), transparency);
		} catch (HeadlessException e) {
			// The system does not have a screen
		}

		if (bimage == null) {
			// Create a buffered image using the default color model
			int type = BufferedImage.TYPE_INT_RGB;
			//int type = BufferedImage.TYPE_3BYTE_BGR;//by wang
            /*if (hasAlpha) {
                type = BufferedImage.TYPE_INT_ARGB;
            }*/
			bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
		}

		// Copy image to buffered image
		Graphics g = bimage.createGraphics();

		// Paint the image onto the buffered image
		g.drawImage(image, 0, 0, null);
		g.dispose();

		return bimage;
	}
}


text:
package com.diffplug.spotless;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

/**
 * Grabs a jar and its dependencies from maven,
 * and makes it easy to access the collection in
 * a classloader.
 *
 * Serializes the full state of the jar, so it can
 * catch changes in a SNAPSHOT version.
 */
public final class JarState implements Serializable {
	private static final long serialVersionUID = 1L;
	private static final Logger logger = Logger.getLogger(JarState.class.getName());

	@SuppressWarnings("unused")
	private final String mavenCoordinate;
	@SuppressWarnings("unused")
	private final FileSignature fileSignature;

	/*
	 * Transient because not needed to uniquely identify a JarState instance, and also because
	 * Gradle only needs this class to be Serializable so it can compare JarState instances for
	 * incremental builds.
	 */
	@SuppressFBWarnings("SE_TRANSIENT_FIELD_NOT_RESTORED")
	private final transient Set<File> jars;

	public JarState(String mavenCoordinate, FileSignature fileSignature, Set<File> jars) {
		this.mavenCoordinate = mavenCoordinate;
		this.fileSignature = fileSignature;
		this.jars = jars;
	}

	public static JarState from(String mavenCoordinate, Provisioner provisioner) throws IOException {
		Objects.requireNonNull(mavenCoordinate);
		Set<File> jars;
		try {
			jars = provisioner.provisionWithDependencies(mavenCoordinate);
			if (jars.isEmpty()) {
				throw new NoSuchElementException("Resolved to an empty result.");
			}
		} catch (Exception e) {
			logger.log(Level.SEVERE, "You probably need to add a repository containing the `" + mavenCoordinate + "` artifact to your buildscript, e.g.: repositories { mavenCentral() }", e);
			throw e;
		}
		FileSignature fileSignature = FileSignature.signAsSet(jars);
		return new JarState(mavenCoordinate, fileSignature, jars);
	}

	URL[] jarUrls() {
		return jars.stream().map(ThrowingEx.wrap(file -> file.toURI().toURL())).toArray(URL[]::new);
	}

	/**
	 * Returns a classloader containing only the jars in this JarState.
	 *
	 * The lifetime of the underlying cacheloader is controlled by {@link SpotlessCache}.
	 */
	public ClassLoader getClassLoader() {
		return SpotlessCache.instance().classloader(this);
	}
}


text:
<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::prefix('v1')->group(function (){
    //Route::resource('/', 'QualifierController');
    Route::get('/', 'QualifierController@index');
    Route::post('/', 'QualifierController@store');
    Route::get('/{id}', 'QualifierController@show');
    Route::put('/{id}', 'QualifierController@update');
    Route::delete('/{id}', 'QualifierController@destroy');
});


text:
package org.adligo.tests4j_4mockito;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;

/**
 * This class maps arguments/parameters to return values of type T.  There are
 * a variety of ways to do this;

 * A) With a default return value.

 * B) With a factory for return values.

 * C) With the backing delegate Map<ObjParams,T>.

 *

 * In all cases the value returned, should be
 * the same instance for subsequent invocations
 * of get for the same parameters/arguments so
 * that the arg map can be used for assertions.

 *

 *

 * {@code
 * MockMethod<String> mm = new MockMethod<String>(new ArgMap<String>(
 *    new I_ReturnFactory<String> {
 *      public String create(Object [] params) {
 *          return "11" + params[0];
 *      }
 * ));
 * List<String> mockList = mock(List.class);
 * when(mockList.get(anyInt()).then(mm);
 * assertEquals("111", mockList.get(1));
 * assertEquals("112", mockList.get(2));
 * assertEquals("1131", mockList.get(31));
 *

 * @author scott
 *
 * @param <T>
 */
public class ArgMap<T> implements Map<ObjParams, T>{
  public static final String OBJECT_ARRAY_CLASS_NAME = new Object[] {}.getClass().getName();

  private final Map<ObjParams, T> delegate_ = new HashMap<ObjParams, T>();
  private final T defaultValue_;
  private final I_ReturnFactory<T> factory_;
  private final boolean cacheResults_;

  public ArgMap() {
    defaultValue_ = null;
    factory_ = null;
    cacheResults_ = true;
  }

  public ArgMap(T defaultValue) {
    defaultValue_ = defaultValue;
    factory_ = null;
    cacheResults_ = true;
  }
  /**
   * this can be useful for storing instances,
   * to make sure they get passed to other methods later.
   * @param factory
   */
  public ArgMap(I_ReturnFactory<T> factory) {
    defaultValue_ = null;
    factory_ = factory;
    cacheResults_ = true;
  }

  public ArgMap(I_ReturnFactory<T> factory, boolean cacheResults) {
    defaultValue_ = null;
    factory_ = factory;
    cacheResults_ = cacheResults;
  }

  public ArgMap(T defaultValue, I_ReturnFactory<T> factory) {
    defaultValue_ = defaultValue;
    factory_ = factory;
    cacheResults_ = true;
  }

  public ArgMap(T defaultValue, I_ReturnFactory<T> factory, boolean cacheResults) {
    defaultValue_ = defaultValue;
    factory_ = factory;
    cacheResults_ = cacheResults;
  }

  public int size() {
    return delegate_.size();
  }

  public boolean isEmpty() {
    return delegate_.isEmpty();
  }

  public boolean containsKey(Object key) {
    return delegate_.containsKey(key);
  }

  public boolean containsValue(Object value) {
    return delegate_.containsValue(value);
  }

  public T get(Object key) {
    if (key != null) {
      if (OBJECT_ARRAY_CLASS_NAME.equals(key.getClass().getName())) {
        return get(new ObjParams((Object []) key));
      }
    }
    return delegate_.get(key);
  }

  public T get(ObjParams key) {

    T toRet = delegate_.get(key);

    if (toRet == null) {
      if (factory_ != null) {
        toRet = factory_.create(key.toArray());
        if (cacheResults_) {
          delegate_.put(key, toRet);
        }
      }
    }
    if (toRet == null) {
      return defaultValue_;
    }
    return toRet;
  }

  public T get(Object [] key) {
    return get(new ObjParams(key));
  }
  /**
   * note it's getVar to distinguish
   * between get(1)' and getVar(1);
   * @param key
   * @return
   */
  public T getVar(Object ... key) {
    return get(new ObjParams(key));
  }

  public T put(ObjParams key, T value) {
    return delegate_.put(key, value);
  }

  public T put(Object[] key, T value) {
    return delegate_.put(new ObjParams(key), value);
  }

  /**
   * Note: This method is backward from the regular
   * put methods so it can have the ... for variable
   * arguments.
   * @param value
   * @param key
   * @return
   */
  public T putVal(T value, Object ... key ) {
    return delegate_.put(new ObjParams(key), value);
  }

  public T remove(Object key) {
    return delegate_.remove(key);
  }

  public void putAll(Map<? extends ObjParams, ? extends T> m) {
    delegate_.putAll(m);
  }

  public void clear() {
    delegate_.clear();
  }

  public Set<ObjParams> keySet() {
    return delegate_.keySet();
  }

  public Collection<T> values() {
    return delegate_.values();
  }

  public Set<java.util.Map.Entry<ObjParams, T>> entrySet() {
    return delegate_.entrySet();
  }

  public boolean equals(Object o) {
    return delegate_.equals(o);
  }

  public int hashCode() {
    return delegate_.hashCode();
  }

  public T getOrDefault(Object key, T defaultValue) {
    return delegate_.getOrDefault(key, defaultValue);
  }

  public void forEach(BiConsumer<? super ObjParams, ? super T> action) {
    delegate_.forEach(action);
  }

  public void replaceAll(BiFunction<? super ObjParams, ? super T, ? extends T> function) {
    delegate_.replaceAll(function);
  }

  public T putIfAbsent(ObjParams key, T value) {
    return delegate_.putIfAbsent(key, value);
  }

  public boolean remove(Object key, Object value) {
    return delegate_.remove(key, value);
  }

  public boolean replace(ObjParams key, T oldValue, T newValue) {
    return delegate_.replace(key, oldValue, newValue);
  }

  public T replace(ObjParams key, T value) {
    return delegate_.replace(key, value);
  }

  public T computeIfAbsent(ObjParams key,
      Function<? super ObjParams, ? extends T> mappingFunction) {
    return delegate_.computeIfAbsent(key, mappingFunction);
  }

  public T computeIfPresent(ObjParams key,
      BiFunction<? super ObjParams, ? super T, ? extends T> remappingFunction) {
    return delegate_.computeIfPresent(key, remappingFunction);
  }

  public T compute(ObjParams key,
      BiFunction<? super ObjParams, ? super T, ? extends T> remappingFunction) {
    return delegate_.compute(key, remappingFunction);
  }

  public T merge(ObjParams key, T value,
      BiFunction<? super T, ? super T, ? extends T> remappingFunction) {
    return delegate_.merge(key, value, remappingFunction);
  }

}


text:
package me.alexrs.recyclerviewrenderers.viewholder;

import android.view.View;
import android.widget.TextView;

import butterknife.ButterKnife;
import butterknife.InjectView;
import me.alexrs.recyclerviewrenderers.demo.R;
import me.alexrs.recyclerviewrenderers.items.ItemBender;

/**
 * @author Alejandro Rodriguez <https://github.com/Alexrs95>
 */
public class ViewHolderBender extends RenderViewHolder<ItemBender> {

    @InjectView(R.id.title)
    TextView title;
    @InjectView(R.id.summary)
    TextView summary;

    public ViewHolderBender(View itemView) {
        super(itemView);
        ButterKnife.inject(this, itemView);
    }

    @Override
    public void onBindView(ItemBender renderable) {
        title.setText(renderable.getTitle());
        summary.setText(renderable.getSummary());
    }
}


text:
# Copyright 2010 Daniel James.
# Distributed under the Boost Software License, Version 1.0. (See accompanying
# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

"""Boostbook tests

Usage: python build_docs.py [--generate-gold]
"""

import difflib, getopt, os, re, sys
import lxml.ElementInclude
from lxml import etree
from collections import defaultdict

# Globals

def usage_and_exit():
    print __doc__
    sys.exit(2)

def main(argv):
    script_directory = os.path.dirname(sys.argv[0])
    boostbook_directory = os.path.join(script_directory, "../../xsl")

    try:
        opts, args = getopt.getopt(argv, "",
            ["generate-gold"])
        if(len(args)): usage_and_exit()
    except getopt.GetoptError:
        usage_and_exit()

    generate_gold = False

    for opt, arg in opts:
        if opt == '--generate-gold':
            generate_gold = True

    # Walk the test directory

    parser = etree.XMLParser()

    try:
        boostbook_xsl = etree.XSLT(
            etree.parse(os.path.join(boostbook_directory, "docbook.xsl"), parser)
        )
    except lxml.etree.XMLSyntaxError, error:
        print "Error parsing boostbook xsl:"
        print error
        sys.exit(1)

    for root, dirs, files in os.walk(os.path.join(script_directory, 'tests')):
        for filename in files:
            (base, ext) = os.path.splitext(filename)
            if (ext == '.xml'):
                src_path = os.path.join(root, filename)
                gold_path = os.path.join(root, base + '.gold')
                try:
                    doc_text = run_boostbook(parser, boostbook_xsl, src_path)
                except:
                    # TODO: Need better error reporting here:
                    print "Error running boostbook for " + src_path
                    continue

                if (generate_gold):
                    file = open(gold_path, 'w')
                    try:
                        file.write(doc_text)
                    finally: file.close()
                else:
                    file = open(gold_path, 'r')
                    try:
                        gold_text = file.read()
                    finally:
                        file.close()
                    compare_xml(src_path, doc_text, gold_text)

def run_boostbook(parser, boostbook_xsl, file):
    doc = boostbook_xsl(etree.parse(file, parser))
    normalize_boostbook_ids(doc)
    return etree.tostring(doc)

def normalize_boostbook_ids(doc):
    ids = {}
    id_bases = defaultdict(int)

    for node in doc.xpath("//*[starts-with(@id, 'id') or contains(@id, '_id')]"):
        id = node.get('id')

        if(id in ids):
            print 'Duplicate id: ' + id

        match = re.match("(.+_id|id)([mp]?\d+)((?:-bb)?)", id)
        if(match):
            # Truncate id name, as it sometimes has different lengths...
            match2 = re.match("(.*?)([^.]*?)(_?id)", match.group(1))
            base = match2.group(1) + match2.group(2)[:14] + match2.group(3)
            count = id_bases[base] + 1
            id_bases[base] = count
            ids[id] = base + str(count) + match.group(3)

    for node in doc.xpath("//*[@linkend or @id]"):
        x = node.get('linkend')
        if(x in ids): node.set('linkend', ids[x])
        x = node.get('id')
        if(x in ids): node.set('id', ids[x])

def compare_xml(file, doc_text, gold_text):
    # Had hoped to use xmldiff but it turned out to be a pain to install.
    # So instead just do a text diff.

    if (doc_text != gold_text):
        print "Error: " + file
        print
        sys.stdout.writelines(
            difflib.unified_diff(
                gold_text.splitlines(True),
                doc_text.splitlines(True)
            )
        )
        print
        print

if __name__ == "__main__":
    main(sys.argv[1:])


text:
namespace impala_udf {

// Utility class to help test UDFs.
class UdfTestHarness {
 public:
  // Create a test FunctionContext object. 'arg_types' should contain a TypeDesc for each
  // argument of the UDF not including the FunctionContext*. The caller is responsible
  // for calling delete on it. This context has additional debugging validation enabled.
  static FunctionContext* CreateTestContext(
      const std::vector<FunctionContext::TypeDesc>& arg_types);

  // Use with test contexts to test use of IsArgConstant() and GetConstantArg().
  // constant_args should contain an AnyVal* for each argument of the UDF not including
  // the FunctionContext*; constant_args[i] corresponds to the i-th argument.
  // Non-constant arguments should be set to NULL, and constant arguments should be set
  // to the constant value.
  //
  // The AnyVal* values are owned by the caller.
  //
  // Can only be called on contexts created by CreateTestContext().
  static void SetConstantArgs(
      FunctionContext* context, const std::vector<AnyVal*>& constant_args);

  // Test contexts should be closed in order to check for UDF memory leaks. Leaks cause
  // the error to be set on context.
  static void CloseContext(FunctionContext* context);

  // Template function to execute a UDF and validate the result. They should be
  // used like:
  // ValidateUdf(udf_fn, arg1, arg2, ..., expected_result);
  // Only functions with up to 8 arguments are supported
  //
  // For variable argument udfs, the variable arguments should be passed as
  // a std::vector:
  //   ValidateUdf(udf_fn, arg1, arg2, const vector<arg3>& args, expected_result);
  template<typename RET>
  static bool ValidateUdf(boost::function<RET(FunctionContext*)> fn,
      const RET& expected, UdfPrepare init_fn = NULL, UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types;
    boost::scoped_ptr<FunctionContext> context(CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get());
    RunCloseFn(close_fn, context.get());
    CloseContext(context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1>
  static bool ValidateUdf(boost::function<RET(FunctionContext*, const A1&)> fn,
      const A1& a1, const RET& expected, UdfPrepare init_fn = NULL,
      UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1>
  static bool ValidateUdf(boost::function<RET(FunctionContext*, int, const A1*)> fn,
      const std::vector<A1>& a1, const RET& expected, UdfPrepare init_fn = NULL,
      UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1.size(), &a1[0]);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1, typename A2>
  static bool ValidateUdf(
      boost::function<RET(FunctionContext*, const A1&, const A2&)> fn,
      const A1& a1, const A2& a2, const RET& expected, UdfPrepare init_fn = NULL,
      UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(UdfTestHarness::CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1, a2);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1, typename A2>
  static bool ValidateUdf(
      boost::function<RET(FunctionContext*, const A1&, int, const A2*)> fn,
      const A1& a1, const std::vector<A2>& a2, const RET& expected,
      UdfPrepare init_fn = NULL, UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(UdfTestHarness::CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1, a2.size(), &a2[0]);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1, typename A2, typename A3>
  static bool ValidateUdf(
      boost::function<RET(FunctionContext*, const A1&, const A2&, const A3&)> fn,
      const A1& a1, const A2& a2, const A3& a3, const RET& expected,
      UdfPrepare init_fn = NULL, UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(UdfTestHarness::CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1, a2, a3);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1, typename A2, typename A3>
  static bool ValidateUdf(
      boost::function<RET(FunctionContext*, const A1&, const A2&, int, const A3*)> fn,
      const A1& a1, const A2& a2, const std::vector<A3>& a3, const RET& expected,
      UdfPrepare init_fn = NULL, UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(UdfTestHarness::CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1, a2, a3.size(), &a3[0]);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1, typename A2, typename A3, typename A4>
  static bool ValidateUdf(
      boost::function<RET(FunctionContext*, const A1&, const A2&, const A3&,
          const A4&)> fn,
      const A1& a1, const A2& a2, const A3& a3, const A4& a4, const RET& expected,
      UdfPrepare init_fn = NULL, UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(UdfTestHarness::CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1, a2, a3, a4);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1, typename A2, typename A3, typename A4>
  static bool ValidateUdf(
      boost::function<RET(FunctionContext*, const A1&, const A2&, const A3&,
          int, const A4*)> fn,
      const A1& a1, const A2& a2, const A3& a3, const std::vector<A4>& a4,
      const RET& expected, UdfPrepare init_fn = NULL, UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(UdfTestHarness::CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1, a2, a3, a4.size(), &a4[0]);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1, typename A2, typename A3, typename A4,
      typename A5>
  static bool ValidateUdf(
      boost::function<RET(FunctionContext*, const A1&, const A2&, const A3&,
          const A4&, const A5&)> fn,
      const A1& a1, const A2& a2, const A3& a3, const A4& a4,const A5& a5,
      const RET& expected, UdfPrepare init_fn = NULL, UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(UdfTestHarness::CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1, a2, a3, a4, a5);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1, typename A2, typename A3, typename A4,
      typename A5, typename A6>
  static bool ValidateUdf(
      boost::function<RET(FunctionContext*, const A1&, const A2&, const A3&,
          const A4&, const A5&, const A6&)> fn,
      const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5,
      const A6& a6, const RET& expected, UdfPrepare init_fn = NULL,
      UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(UdfTestHarness::CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1, a2, a3, a4, a5, a6);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1, typename A2, typename A3, typename A4,
      typename A5, typename A6, typename A7>
  static bool ValidateUdf(
      boost::function<RET(FunctionContext*, const A1&, const A2&, const A3&,
          const A4&, const A5&, const A6&, const A7&)> fn,
      const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5,
      const A6& a6, const A7& a7, const RET& expected, UdfPrepare init_fn = NULL,
      UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(UdfTestHarness::CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1, a2, a3, a4, a5, a6, a7);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

  template<typename RET, typename A1, typename A2, typename A3, typename A4,
      typename A5, typename A6, typename A7, typename A8>
  static bool ValidateUdf(
      boost::function<RET(FunctionContext*, const A1&, const A2&, const A3&,
          const A4&, const A5&, const A6&, const A7&)> fn,
      const A1& a1, const A2& a2, const A3& a3, const A4& a4, const A5& a5,
      const A6& a6, const A7& a7, const A8& a8, const RET& expected,
      UdfPrepare init_fn = NULL, UdfClose close_fn = NULL,
      const std::vector<AnyVal*>& constant_args = std::vector<AnyVal*>()) {
    std::vector<FunctionContext::TypeDesc> types; // TODO
    boost::scoped_ptr<FunctionContext> context(UdfTestHarness::CreateTestContext(types));
    SetConstantArgs(context.get(), constant_args);
    if (!RunPrepareFn(init_fn, context.get())) return false;
    RET ret = fn(context.get(), a1, a2, a3, a4, a5, a6, a7, a8);
    RunCloseFn(close_fn, context.get());
    return Validate(context.get(), expected, ret);
  }

 private:
  static bool ValidateError(FunctionContext* context) {
    if (context->has_error()) {
      std::cerr << "Udf Failed: " << context->error_msg() << std::endl;
      return false;
    }
    return true;
  }

  template<typename RET>
  static bool Validate(FunctionContext* context, const RET& expected, const RET& actual) {
    bool valid = true;
    if (!context->has_error() && actual != expected) {
      std::cerr << "UDF did not return the correct result:" << std::endl
                << "  Expected: " << DebugString(expected) << std::endl
                << "  Actual: " << DebugString(actual) << std::endl;
      valid = false;
    }
    CloseContext(context);
    if (!ValidateError(context)) valid = false;
    return valid;
  }

  static bool RunPrepareFn(UdfPrepare prepare_fn, FunctionContext* context) {
    if (prepare_fn != NULL) {
      // TODO: FRAGMENT_LOCAL
      prepare_fn(context, FunctionContext::THREAD_LOCAL);
      if (!ValidateError(context)) return false;
    }
    return true;
  }

  static void RunCloseFn(UdfClose close_fn, FunctionContext* context) {
    if (close_fn != NULL) {
      // TODO: FRAGMENT_LOCAL
      close_fn(context, FunctionContext::THREAD_LOCAL);
    }
  }
};

}

#endif


text:
package net.ae97.notlet.server.crypto;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashGenerator {

    private static final MessageDigest hashGen;

    static {
        try {
            hashGen = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }

    private HashGenerator() {
    }

    public static byte[] hash(String msg) {
        synchronized (hashGen) {
            return hashGen.digest(msg.getBytes());
        }
    }

}