text:
#!/bin/sh

# This file is part of the Symfony Standard Edition.
#
# (c) Fabien Potencier <fabien@symfony.com>
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.

if [ ! $1 ]; then
    echo "\033[37;41mYou must pass the build dir as an absolute path\033[0m"
    exit 1
fi

if [ ! $2 ]; then
    echo "\033[37;41mYou must pass the version to build\033[0m"
    exit 1
fi

DIR=$1
CURRENT=`php -r "echo realpath(dirname(\\$_SERVER['argv'][0]));"`

if [[ ! "$DIR" = /* ]]; then
     DIR="$CURRENT/$DIR"
fi

if [ ! -d $DIR ]; then
    echo "\033[37;41mThe build dir does not exist\033[0m"
    exit 1
fi

# avoid the creation of ._* files
export COPY_EXTENDED_ATTRIBUTES_DISABLE=true
export COPYFILE_DISABLE=true
export SENSIOLABS_FORCE_ACME_DEMO=true

# Temp dir
rm -rf /tmp/Symfony
mkdir /tmp/Symfony

# Create project
composer.phar create-project -n symfony/framework-standard-edition /tmp/Symfony $2

if [ 0 -ne $? ]; then
    echo "\033[37;41mVersion $2 does not exist\033[0m"
    exit 1
fi

cd /tmp/Symfony

# cleanup
sudo rm -rf app/cache/* app/logs/* .git*
chmod 777 app/cache app/logs
find . -name .DS_Store | xargs rm -rf -

VERSION=`grep ' VERSION ' vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Kernel.php | sed -E "s/.*'(.+)'.*/\1/g"`

# With vendors
cd /tmp/Symfony
TARGET=/tmp/Symfony/vendor

# Doctrine
cd $TARGET/doctrine/orm && rm -rf UPGRADE* build* bin tests tools lib/vendor
cd $TARGET/doctrine/dbal && rm -rf bin build* tests lib/vendor
cd $TARGET/doctrine/common && rm -rf build* tests lib/vendor
cd $TARGET/doctrine/doctrine-bundle && rm -rf Doctrine/Bundle/DoctrineBundle/Tests Doctrine/Bundle/DoctrineBundle/Resources/doc

# kriswallsmith
cd $TARGET/kriswallsmith/assetic && rm -rf CHANGELOG* phpunit.xml* tests docs

# Monolog
cd $TARGET/monolog/monolog && rm -rf README.markdown phpunit.xml* tests

# Sensio
cd $TARGET/sensio/distribution-bundle/Sensio/Bundle/DistributionBundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc
cd $TARGET/sensio/framework-extra-bundle/Sensio/Bundle/FrameworkExtraBundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc
cd $TARGET/sensio/generator-bundle/Sensio/Bundle/GeneratorBundle && rm -rf phpunit.xml* Tests CHANGELOG* Resources/doc

# Swiftmailer
cd $TARGET/swiftmailer/swiftmailer && rm -rf CHANGES README* build* docs notes test-suite tests create_pear_package.php package*

# Symfony
cd $TARGET/symfony/symfony && rm -rf README.md phpunit.xml* tests *.sh vendor
cd $TARGET/symfony/assetic-bundle/Symfony/Bundle/AsseticBundle && rm -rf Tests Resources/doc
cd $TARGET/symfony/swiftmailer-bundle/Symfony/Bundle/SwiftmailerBundle && rm -rf Tests Resources/doc
cd $TARGET/symfony/monolog-bundle/Symfony/Bundle/MonologBundle && rm -rf Tests Resources/doc

# Twig
cd $TARGET/twig/twig && rm -rf AUTHORS CHANGELOG README.markdown bin doc package.xml.tpl phpunit.xml* test
cd $TARGET/twig/extensions && rm -rf README doc phpunit.xml* test

# cleanup
find $TARGET -name .git | xargs rm -rf -
find $TARGET -name .gitignore | xargs rm -rf -
find $TARGET -name .gitmodules | xargs rm -rf -
find $TARGET -name .svn | xargs rm -rf -

cd /tmp
tar zcpf $DIR/Symfony_Standard_Vendors_$VERSION.tgz Symfony
sudo rm -f $DIR/Symfony_Standard_Vendors_$VERSION.zip
zip -rq $DIR/Symfony_Standard_Vendors_$VERSION.zip Symfony

# Without vendors
cd /tmp
rm -rf Symfony/vendor
tar zcpf $DIR/Symfony_Standard_$VERSION.tgz Symfony
sudo rm -f $DIR/Symfony_Standard_$VERSION.zip
zip -rq $DIR/Symfony_Standard_$VERSION.zip Symfony

redpajama_set_name: RedPajamaGithub


text:
package spark.timeseries

import com.coconut_palm_software.xscalawt.XScalaWT._
import com.coconut_palm_software.xscalawt.XScalaWT.Assignments._

import org.eclipse.swt.SWT
import org.eclipse.swt.widgets._
import org.eclipse.swt.layout._
import org.eclipse.swt.events._

object LoginBox {
  val modifyListener = new ModifyListener {
    def modifyText(e : ModifyEvent) = {
      println(e.widget.asInstanceOf[Text].getText)
    }
  }

  def main(args : Array[String]) : Unit = {
    var username : Text = null

    val window = shell("Please log in",

      // username/password group
      group("User information",
        layoutData = new GridData(SWT.FILL, SWT.CENTER, true, false),
        layout = new GridLayout(1, false),

        label("Username"),
        text (
          username=_,       // Save the username Text widget for later, say for data binding...
          layoutData = new GridData(SWT.FILL, SWT.CENTER, true, false),
          _.addModifyListener(modifyListener)    // or we could data bind right here if we want to...
        ),

        label(""),

        label("Password"),
        textPasswd (
          layoutData = new GridData(SWT.FILL, SWT.CENTER, true, false),
          _.addModifyListener(modifyListener)
        )
      ),

      // OK/Cancel buttons
      composite (
        layoutData = new GridData(SWT.CENTER, SWT.CENTER, false, false),
        layout = new GridLayout(2, true),

        button("OK",
          layoutData = new GridData(GridData.HORIZONTAL_ALIGN_FILL),
          onSelection { println("OK") }
        ),
        button("Cancel",
          layoutData = new GridData(GridData.HORIZONTAL_ALIGN_FILL),
          onSelection { println("Cancel") }
        )
      ),

      // Set a default shell size
      { window =>
        window.pack
        val size = window.getSize()
        window.setSize(250, size.y)
      }
    )
    runEventLoop(window)
  }
}


text:
var parser = require('khepri-parse').parse.parser;
var lexer = require('khepri-parse').lex.lexer;

var unparse = require('ecma-unparse').unparse;
var unparse_print = require('ecma-unparse').print;

var compile = require('../index').compile;

var testParser = function(input) {
    return eval(unparse_print.print(unparse.unparse(compile(parser.parseStream(lexer.lex(input))))));
};

exports.simple_unpack_args = function(test) {
    test.equal(
        testParser("(\\-args() -> args.length)(1, 2, 3);"),
        3);

    test.done();
};

exports.unpack_args_and_inner_pattern = function(test) {
    test.equal(
        testParser("(\\-args(x y z) -> args.length * (x + y * z))(1, 2, 3);"),
        21);

    test.done();
};


text:
.class public interface abstract Landroid/content/pm/IPackageInstallerCallback;
.super Ljava/lang/Object;
.source "IPackageInstallerCallback.java"

# interfaces
.implements Landroid/os/IInterface;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/content/pm/IPackageInstallerCallback$Stub;
    }
.end annotation

# virtual methods
.method public abstract onSessionActiveChanged(IZ)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract onSessionBadgingChanged(I)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract onSessionCreated(I)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract onSessionFinished(IZ)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method

.method public abstract onSessionProgressChanged(IF)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation
.end method


text:
{% load staticfiles %}

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>

About

Link

          Dropdown

Action

Another action

Something else here

Separated link

One more separated link

        {% if user.is_authenticated%}

Signed in as {{user}}

Logout ?

        {%else%}
          <button type="button" class="btn btn-default navbar-btn">Sign in</button>
        {%endif%}


text:
package asl.clienterobot;

public class DatagramCommands
{
	public static final byte ON				= 1;
	public static final byte OFF			= 0;
	public static final byte NOPARAM 		= 0;

	public static final byte STOP 			= 0;
	public static final byte MOVE_FORWARD 	= 1;
	public static final byte MOVE_BACKWARD 	= 2;
	public static final byte BEEP			= 3;
	public static final byte LED			= 4;
}


text:
package lab.s2jh.auth.service;

import java.util.Collection;
import java.util.Date;
import java.util.List;

import lab.s2jh.auth.dao.PrivilegeDao;
import lab.s2jh.auth.dao.RoleDao;
import lab.s2jh.auth.dao.UserDao;
import lab.s2jh.auth.dao.UserLogonLogDao;
import lab.s2jh.auth.dao.UserR2RoleDao;
import lab.s2jh.auth.entity.Privilege;
import lab.s2jh.auth.entity.Role;
import lab.s2jh.auth.entity.User;
import lab.s2jh.auth.entity.UserLogonLog;
import lab.s2jh.auth.entity.UserR2Role;
import lab.s2jh.core.dao.BaseDao;
import lab.s2jh.core.security.AclService;
import lab.s2jh.core.service.BaseService;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

@Service
@Transactional
public class UserService extends BaseService<User, String> {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PrivilegeDao privilegeDao;

    @Autowired
    private UserR2RoleDao userR2RoleDao;

    @Autowired
    private UserLogonLogDao userLogonLogDao;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired(required = false)
    private AclService aclService;

    @Override
    protected BaseDao<User, String> getEntityDao() {
        return userDao;
    }

    @Override
    protected void preInsert(User entity) {
        super.preInsert(entity);
        if (aclService != null) {
            entity.setAclType(aclService.aclCodeToType(entity.getAclCode()));
        }
        entity.setSignupTime(new Date());
    }

    @Override
    protected void preUpdate(User entity) {
        if (aclService != null) {
            entity.setAclType(aclService.aclCodeToType(entity.getAclCode()));
        }
        super.preUpdate(entity);
    }

    public User findByAclCodeAndSigninid(String aclCode, String signid) {
        if (StringUtils.isBlank(aclCode)) {
            List<User> users = userDao.findBySigninid(signid);
            if (CollectionUtils.isEmpty(users)) {
                return null;
            }
            Assert.isTrue(users.size() == 1);
            return users.get(0);
        }
        return userDao.findByAclCodeAndSigninid(aclCode, signid);
    }

    public User findByUid(String uid) {
        return userDao.findByUid(uid);
    }

    public long findCount() {
        return userDao.count();
    }

    /**
     * 用户注册
     *
     * @param rawPassword
     *            原始密码
     * @param user
     *            用户数据对象
     * @return
     */
    public User save(User user, String rawPassword) {
        if (user.isNew()) {
            user.setUid(RandomStringUtils.randomNumeric(10));
        }
        if (StringUtils.isNotBlank(rawPassword)) {
            user.setPassword(encodeUserPasswd(user, rawPassword));
        }
        return this.save(user);
    }

    public String encodeUserPasswd(User user, String rawPassword) {
        return passwordEncoder.encodePassword(rawPassword, user.getUid());
    }

    /**
     * 初始化系统用户设置
     * @param user
     * @param rawPassword
     * @return
     */
    public User initSetupUser(User user, String rawPassword) {
        long count = findCount();
        Assert.isTrue(count == 0);
        user.setInitSetupUser(true);
        save(user, rawPassword);
        Role role = roleDao.findByCode(Role.ROLE_ADMIN_CODE);
        if (role == null) {
            role = new Role();
            role.setCode(Role.ROLE_ADMIN_CODE);
            role.setTitle("预置系统管理员");
            role.setDescription("预置角色,不可删除");
            roleDao.save(role);
        }
        UserR2Role r2 = new UserR2Role();
        r2.setUser(user);
        r2.setRole(role);
        userR2RoleDao.save(r2);
        return user;
    }

    @Transactional(readOnly = true)
    public List<UserR2Role> findRelatedUserR2RolesForUser(String userId) {
        return userR2RoleDao.findByUser_Id(userId);
    }

    public void updateRelatedRoleR2s(String id, Collection<String> roleIds, R2OperationEnum op) {
        updateRelatedR2s(id, roleIds, "userR2Roles", "role", op);
    }

    @Transactional(readOnly = true)
    public List<Privilege> findRelatedPrivilegesForUser(String userId) {
        return privilegeDao.findPrivilegesForUser(userId);
    }

    @Async
    public void userLogonLog(UserLogonLog userLogonLog) {
        User user = userDao.findByUid(userLogonLog.getUserid());
        if (user.getLogonTimes() == null) {
            user.setLogonTimes(1L);
        } else {
            user.setLogonTimes(user.getLogonTimes() + 1L);
        }
        userLogonLog.setLogonTimes(user.getLogonTimes());
        user.setLastLogonIP(userLogonLog.getRemoteAddr());
        user.setLastLogonHost(userLogonLog.getRemoteHost());
        user.setLastLogonTime(userLogonLog.getLogonTime());
        userDao.save(user);
        userLogonLogDao.save(userLogonLog);
    }
}


text:
raise "Missing parameter 'CRED_PATH'. Please read docs at #{__FILE__}" \
  unless ENV.key?('CRED_PATH')
raise "Missing parameter 'PROJECT'. Please read docs at #{__FILE__}" \
  unless ENV.key?('PROJECT')

# For more information on the gauth_credential parameters and providers please
# refer to its detailed documentation at:
# https://github.com/GoogleCloudPlatform/chef-google-auth
gauth_credential 'mycred' do
  action :serviceaccount
  path ENV['CRED_PATH'] # e.g. '/path/to/my_account.json'
  scopes [
    'https://www.googleapis.com/auth/ndev.clouddns.readwrite'
  ]
end

gdns_managed_zone 'testzone-4-com' do
  action :create
  dns_name 'testzone-4.com.'
  description 'Test Example Zone'
  project ENV['PROJECT'] # ex: 'my-test-project'
  credential 'mycred'
end

gdns_resource_record_set 'www.testzone-4.com.' do
  action :create
  managed_zone 'testzone-4-com'
  type 'A'
  ttl 600
  target [
    '10.1.2.3',
    '40.5.6.7',
    '80.9.10.11'
  ]
  project ENV['PROJECT'] # ex: 'my-test-project'
  credential 'mycred'
end

gdns_resource_record_set 'sites.testzone-4.com.' do
  action :create
  managed_zone 'testzone-4-com'
  type 'CNAME'
  target ['www.testzone-4.com.']
  project ENV['PROJECT'] # ex: 'my-test-project'
  credential 'mycred'
end


text:
namespace NHInsights
{
    using System.Data;
    using System.Data.Common;
    using NHibernate.AdoNet;
    using NHibernate.Driver;
    using NHibernate.Engine.Query;
    using NHibernate.SqlTypes;
    using NHibernate.Util;
    using NHInsights.Infrastructure;

    public class OracleManagedDataClientDriver : ReflectionBasedDriver, IEmbeddedBatcherFactoryProvider
    {
        private const string driverAssemblyName = "Oracle.ManagedDataAccess";

		private const string connectionTypeName = "Oracle.ManagedDataAccess.Client.OracleConnection";

        private const string commandTypeName = "NHInsights.Infrastructure.InsightsDbCommand";

		private static readonly SqlType GuidSqlType = new SqlType(DbType.Binary, 16);

		private readonly System.Reflection.PropertyInfo oracleCommandBindByName;

		private readonly System.Reflection.PropertyInfo oracleDbType;

		private readonly object oracleDbTypeRefCursor;

		private readonly object oracleDbTypeXmlType;

		private readonly object oracleDbTypeBlob;

		///
		public override string NamedPrefix
		{
			get
			{
				return ":";
			}
		}

		///
		public override bool UseNamedPrefixInParameter
		{
			get
			{
				return true;
			}
		}

		///
		public override bool UseNamedPrefixInSql
		{
			get
			{
				return true;
			}
		}

		System.Type IEmbeddedBatcherFactoryProvider.BatcherFactoryClass
		{
			get
			{
				return typeof(OracleDataClientBatchingBatcherFactory);
			}
		}

		///
		/// Initializes a new instance of <see cref="T:NHibernate.Driver.OracleDataClientDriver" />.
		///
		/// <exception cref="T:NHibernate.HibernateException">
		/// Thrown when the <c>Oracle.ManagedDataAccess</c> assembly can not be loaded.
		/// </exception>
        public OracleManagedDataClientDriver()
            : base("Oracle.ManagedDataAccess.Client", "Oracle.ManagedDataAccess", "Oracle.ManagedDataAccess.Client.OracleConnection", "NHInsights.Infrastructure.InsightsDbCommand")
		{
            System.Type type = ReflectHelper.TypeFromAssembly("NHInsights.Infrastructure.InsightsDbCommand", "NHInsights", true);
			this.oracleCommandBindByName = type.GetProperty("BindByName");
			System.Type type2 = ReflectHelper.TypeFromAssembly("Oracle.ManagedDataAccess.Client.OracleParameter", "Oracle.ManagedDataAccess", true);
			this.oracleDbType = type2.GetProperty("OracleDbType");
			System.Type enumType = ReflectHelper.TypeFromAssembly("Oracle.ManagedDataAccess.Client.OracleDbType", "Oracle.ManagedDataAccess", true);
			this.oracleDbTypeRefCursor = System.Enum.Parse(enumType, "RefCursor");
			this.oracleDbTypeXmlType = System.Enum.Parse(enumType, "XmlType");
			this.oracleDbTypeBlob = System.Enum.Parse(enumType, "Blob");
		}

		/// <remarks>
		/// This adds logic to ensure that a DbType.Boolean parameter is not created since
		/// ODP.NET doesn't support it.
		/// </remarks>
		protected override void InitializeParameter(IDbDataParameter dbParam, string name, SqlType sqlType)
		{
			DbType dbType = sqlType.DbType;
			switch (dbType)
			{
			case DbType.Binary:
				this.InitializeParameter(dbParam, name, this.oracleDbTypeBlob);
				return;
			case DbType.Byte:
				break;
			case DbType.Boolean:
				base.InitializeParameter(dbParam, name, SqlTypeFactory.Int16);
				return;
			default:
				if (dbType == DbType.Guid)
				{
                    base.InitializeParameter(dbParam, name, OracleManagedDataClientDriver.GuidSqlType);
					return;
				}
				if (dbType == DbType.Xml)
				{
					this.InitializeParameter(dbParam, name, this.oracleDbTypeXmlType);
					return;
				}
				break;
			}
			base.InitializeParameter(dbParam, name, sqlType);
		}

		private void InitializeParameter(IDbDataParameter dbParam, string name, object sqlType)
		{
			dbParam.ParameterName = base.FormatNameForParameter(name);
			this.oracleDbType.SetValue(dbParam, sqlType, null);
		}

		protected override void OnBeforePrepare(IDbCommand command)
		{
			base.OnBeforePrepare(command);
			this.oracleCommandBindByName.SetValue(command, true, null);
			CallableParser.Detail detail = CallableParser.Parse(command.CommandText);
			if (!detail.IsCallable)
			{
				return;
			}
			command.CommandType = CommandType.StoredProcedure;
			command.CommandText = detail.FunctionName;
			this.oracleCommandBindByName.SetValue(command, false, null);
			IDbDataParameter dbDataParameter = command.CreateParameter();
			this.oracleDbType.SetValue(dbDataParameter, this.oracleDbTypeRefCursor, null);
			dbDataParameter.Direction = (detail.HasReturn ? ParameterDirection.ReturnValue : ParameterDirection.Output);
			command.Parameters.Insert(0, dbDataParameter);
		}

        public override IDbCommand CreateCommand()
        {
            var command = base.CreateCommand();

            command = new InsightsDbCommand((DbCommand)command, (DbConnection)command.Connection) as IDbCommand;

            return command;
        }
    }
}


text:
package org.apache.geronimo.testsuite.deployment.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class testServlet extends HttpServlet {
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

    		out.println("");
            out.println("");
            out.println("<title>urlBinding-test</title>");
            out.println("");
            out.println("");
            out.println("
hello urlbinding
");
            Context c = new InitialContext();
    		if(c==null || c.equals(null)){
    			out.println("Context is null.");
    		}
    		out.println("
"+c.lookup("jca:/org.apache.geronimo.testsuite/url-binding-tests/URLBinding/URLBindingA")+"
");
    		out.println("");
            out.println("");

        }catch(NamingException e){
        	e.printStackTrace();
        }finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
}


text:
class AdminCartDetailController {
    constructor($state, $log) {
        this.$state = $state;
        this.$log = $log;

        this.$log.log('este es el controllador de cart detail admin')
        /*
        this.labels = ["Total Efectivo", "Total Mixto", "Total Tarjeta"];
        this.data = [
            this.cart.totalPayments.totalEfectivo,
            this.cart.totalPayments.totalMixto,
            this.cart.totalPayments.totalTarjeta
        ];*/
    }

}

export default AdminCartDetailController


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/refresh"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="5dp"
    tools:context="cn.devifish.readme.view.module.bookshelf.BookshelfFragment">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_bookshelf"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        style="@style/Main_Page_Padding" />

</android.support.v4.widget.SwipeRefreshLayout>


text:
import { uniqBy } from 'lodash';

import { Labels } from '@grafana/data';
import { Matcher, MatcherOperator } from 'app/plugins/datasource/alertmanager/types';
import { Alert } from 'app/types/unified-alerting';

import { MatcherFieldValue } from '../types/silence-form';

import { parseMatcher } from './alertmanager';

// Parses a list of entries like like "['foo=bar', 'baz=~bad*']" into SilenceMatcher[]
export function parseQueryParamMatchers(matcherPairs: string[]): Matcher[] {
  const parsedMatchers = matcherPairs.filter((x) => !!x.trim()).map((x) => parseMatcher(x.trim()));

  // Due to migration, old alert rules might have a duplicated alertname label
  // To handle that case want to filter out duplicates and make sure there are only unique labels
  return uniqBy(parsedMatchers, (matcher) => matcher.name);
}

export const getMatcherQueryParams = (labels: Labels) => {
  const validMatcherLabels = Object.entries(labels).filter(
    ([labelKey]) => !(labelKey.startsWith('__') && labelKey.endsWith('__'))
  );

  const matcherUrlParams = new URLSearchParams();
  validMatcherLabels.forEach(([labelKey, labelValue]) =>
    matcherUrlParams.append('matcher', `${labelKey}=${labelValue}`)
  );

  return matcherUrlParams;
};

interface MatchedInstance {
  id: string;
  data: {
    matchedInstance: Alert;
  };
}

export const findAlertInstancesWithMatchers = (
  instances: Alert[],
  matchers: MatcherFieldValue[]
): MatchedInstance[] => {
  const anchorRegex = (regexpString: string): RegExp => {
    // Silence matchers are always fully anchored in the Alertmanager: https://github.com/prometheus/alertmanager/pull/748
    if (!regexpString.startsWith('^')) {
      regexpString = '^' + regexpString;
    }
    if (!regexpString.endsWith('$')) {
      regexpString = regexpString + '$';
    }
    return new RegExp(regexpString);
  };

  const matchesInstance = (instance: Alert, matcher: MatcherFieldValue) => {
    return Object.entries(instance.labels).some(([key, value]) => {
      if (!matcher.name || !matcher.value) {
        return false;
      }
      if (matcher.name !== key) {
        return false;
      }
      switch (matcher.operator) {
        case MatcherOperator.equal:
          return matcher.value === value;
        case MatcherOperator.notEqual:
          return matcher.value !== value;
        case MatcherOperator.regex:
          const regex = anchorRegex(matcher.value);
          return regex.test(value);
        case MatcherOperator.notRegex:
          const negregex = anchorRegex(matcher.value);
          return !negregex.test(value);
        default:
          return false;
      }
    });
  };

  const filteredInstances = instances.filter((instance) => {
    return matchers.every((matcher) => matchesInstance(instance, matcher));
  });
  const mappedInstances = filteredInstances.map((instance) => ({
    id: `${instance.activeAt}-${instance.value}`,
    data: { matchedInstance: instance },
  }));

  return mappedInstances;
};


text:
package catuml.mac.cocoa;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class NSAlertTest {

    @Test
    public void testMessageTextProperty() {
        String testMessage = "Test Message";
        var alert = new NSAlert();
        alert.setMessageText(NSString.valueOf(testMessage));

        assertEquals(testMessage, alert.getMessageText().toString());
    }
}


text:
const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');

const TalendHTML = require('@talend/html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const extractCSS = new ExtractTextPlugin({ filename: '[name]-[hash].css' });

const APP_CONF = require('./app.conf');
const LICENSE_BANNER = require('./license');
const SASS_DATA = require('./sass.conf');
const CHUNKS_ORDER = ['vendor', 'style', 'app'];

const INDEX_TEMPLATE_PATH = path.resolve(__dirname, '../src/index.html');
const STYLE_PATH = path.resolve(__dirname, '../src/app/index.scss');
const VENDOR_PATH = path.resolve(__dirname, '../src/vendor.js');

const AppLoader = require('@talend/react-components/lib/AppLoader/constant').default;

const isTestMode = process.env.NODE_ENV === 'test';

function getCommonStyleLoaders(enableModules) {
	let cssOptions = {};
	if (enableModules) {
		cssOptions = {
			sourceMap: true,
			modules: true,
			importLoaders: 1,
			localIdentName: '[name]__[local]___[hash:base64:5]',
		};
	}
	return [
		{ loader: 'css-loader', options: cssOptions },
		{
			loader: 'postcss-loader',
			options: { sourceMap: true, plugins: () => [autoprefixer({ browsers: ['last 2 versions'] })] },
		},
		{ loader: 'resolve-url-loader' },
	];
}

function getSassLoaders(enableModules) {
	return getCommonStyleLoaders(enableModules)
		.concat({
			loader: 'sass-loader',
			options: { sourceMap: true, data: SASS_DATA },
		});
}

const config = {
	entry: {
		vendor: [
			'babel-polyfill',
			VENDOR_PATH,
		],
		style: STYLE_PATH,
		app: ['babel-polyfill', 'whatwg-fetch', './src/app/index-module.js'],
	},
	output: {
		path: `${__dirname}/../build`,
		publicPath: '/',
		filename: '[name]-[hash].js',
	},
	module: {
		loaders: [
			{
				test: /\.js$/,
				exclude: /node_modules/,
				use: [
					{ loader: 'ng-annotate-loader' },
					{ loader: 'babel-loader' },
				],
			},
			{
				test: /\.css$/,
				use: isTestMode ? { loader: 'null-loader' } : extractCSS.extract(getCommonStyleLoaders()),
				exclude: /@talend/,
			},
			{
				test: /\.scss$/,
				use: isTestMode ? { loader: 'null-loader' } : extractCSS.extract(getSassLoaders()),
				exclude: /@talend/,
			},
			// css modules local scope
			{
				test: /\.scss$/,
				use: isTestMode ? { loader: 'null-loader' } : extractCSS.extract(getSassLoaders(true)),
				include: /@talend/,
			},
			{
				test: /\.html$/,
				use: [
					{ loader: 'ngtemplate-loader' },
					{ loader: 'html-loader' },
				],
				exclude: INDEX_TEMPLATE_PATH,
			},
			{
				test: /\.(png|jpg|jpeg|gif)$/,
				loader: isTestMode ? 'null-loader' : 'url-loader',
				options: { mimetype: 'image/png' },
			},
			{
				test: /\.woff(2)?(\?v=\d+\.\d+\.\d+)?$/,
				loader: isTestMode ? 'null-loader' : 'url-loader',
				options: {
					name: '/assets/fonts/[name].[ext]',
					limit: 50000,
					mimetype: 'application/font-woff',
				},
			},
			{
				test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
				loader: isTestMode ? 'null-loader' : 'url-loader',
				options: { name: '/assets/fonts/[name].[ext]', limit: 10000, mimetype: 'image/svg+xml' },
			},
		],
	},
	resolve: {
		symlinks: false,
	},
	plugins: [
		extractCSS,
		new webpack.ProvidePlugin({
			$: 'jquery',
			jQuery: 'jquery',
			jquery: 'jquery',
			'window.jQuery': 'jquery',
			moment: 'moment',
		}),
		new webpack.LoaderOptionsPlugin({
			minimize: true,
		}),
	],
	node: {
		fs: 'empty',
	},
};

if (!isTestMode) {
	config.plugins = config.plugins.concat([
		CopyWebpackPlugin([
			{ from: 'src/assets/images', to: 'assets/images' },
			{ from: 'src/assets/config/config.json', to: 'assets/config' },
		]),
		new HtmlWebpackPlugin({
			filename: './index.html',
			template: INDEX_TEMPLATE_PATH,
			title: APP_CONF.title,
			rootElement: APP_CONF.rootElement,
			rootModule: APP_CONF.rootModule,
			inject: 'body',
			loader: AppLoader.APP_LOADER,
			// ensure loding order vendor/style/app
			chunksSortMode: (a, b) => {
				const aOrder = CHUNKS_ORDER.indexOf(a.names[0]);
				const bOrder = CHUNKS_ORDER.indexOf(b.names[0]);
				if (aOrder > bOrder) {
					return 1;
				}
				if (aOrder < bOrder) {
					return -1;
				}
				return 0;
			},
		}),
		new TalendHTML({
			loadCSSAsync: true,
			appLoaderIcon: APP_CONF.icon,
		}),
		new webpack.BannerPlugin({
			banner: LICENSE_BANNER,
		}),
	]);
}

module.exports = config;


text:
@interface XVimMark : NSObject
@property NSUInteger line;
@property NSUInteger column;
@property(strong) NSString* document;

- (id)initWithLine:(NSUInteger)line column:(NSUInteger)col document:(NSString*)doc;
- (id)initWithMark:(XVimMark*)mark;
- (void)setMark:(XVimMark*)mark;
+ (id)markWithLine:(NSUInteger)line column:(NSUInteger)col document:(NSString*)doc;
+ (id)markWithMark:(XVimMark*)mark;
@end

#define XVimMakeMark(line, col, doc) [[XVimMark alloc] initWithLine:line column:col document:doc]


text:
require('../../../modules/esnext.string.replace-all');

var parent = require('../../../actual/string/virtual/replace-all');

module.exports = parent;


text:
#pragma once
#include <vector>
#include "gns/polynomial.h"

namespace gns {
/**
 * @brief
 *
 * @tparam Base
 */
template <int Base>
class IrreduciblePolynomialGenerator {
 public:
  /**
   * @brief
   *
   */
  IrreduciblePolynomialGenerator();
  /**
   * @brief Read irreducible polynomials from a file or input stream.
   *  The file contains lines of integers converting from polynomial to integer.
   *  The sequence of integers should be in inceasing order.
   *  The last of the integer is set to seed_.
   *
   * @param inputStream
   */
  explicit IrreduciblePolynomialGenerator(std::istream& inputStream);
  /**
   * @brief
   *
   * @param
   */
  explicit IrreduciblePolynomialGenerator(const bool use_prepared_irreducibles);
  /**
   * @brief Find num irreducible polyonmials from degree 1.
   *
   * @param num number of irreducible polynomials generated.
   *
   * @return
   */
  const std::vector<GaloisFieldPolynomial<Base>>& operator()(const size_t num);
  /**
   * @brief Save irreducible polynomials to output stream.
   * Each irreducible polynomial writes in each line.
   *
   * @param output
   * @param delimiter default value is empty.
   */
  void Save(std::ostream& output, const std::string delimiter = "") const;

 private:
  /**
   * @brief
   *
   * @param num
   *
   * @return
   */
  GaloisFieldPolynomial<Base> ConvertToPolynomial(size_t num) const;
  /**
   * @brief This function assumes that seed_ is equal to integer
   * which is converted from irreducibles_.back().
   * seed_ is updated to integer which is converted from
   * the returns value.
   *
   * @return an irreducible polynomial after the seed_.
   * The order is defined by the Base adic expansion mapping.
   */
  GaloisFieldPolynomial<Base> FindIrreduciblePolynomial();
  /**
   * @brief Get prepared irreducible polynomials.
   * Currently up to 20,000 irreducible polynomials are supported.
   *
   * @return
   */
  std::vector<GaloisFieldPolynomial<Base>> GetPreparedIrreducibles(
      const bool use_prepared_irreducibles) const;

 private:
  /**
   * @brief seed_ must be equal to integer of irreducible_.back().
   */
  size_t seed_;
  /**
   * @brief irreducibles_ must contains all irreducible polynomials of which
   * integer is less than seed_.
   */
  std::vector<GaloisFieldPolynomial<Base>> irreducibles_;
};
/**
 * @brief
 *
 * @tparam Base
 *
 * @return Pre calcualted irreducible polynomials over Base as a list of int.
 */
template <int Base>
std::vector<int> GetPreparedIrreduciblesData();
/**
 * @brief
 *
 * @tparam Base
 * @param str_data
 *
 * @return
 */
template <int Base>
GaloisFieldPolynomial<Base> MakeGaloisFieldPolynomial(const char* str_data);
}  // namespace gns


text:
#pragma once

#include <arch/ops.h>
#include <arch/x86.h>
#include <stdbool.h>

#define SPIN_LOCK_INITIAL_VALUE (0)

typedef unsigned long spin_lock_t;

typedef x86_flags_t spin_lock_saved_state_t;
typedef uint spin_lock_save_flags_t;

/* simple implementation of spinlocks for no smp support */
static inline void arch_spin_lock_init(spin_lock_t *lock) {
    *lock = SPIN_LOCK_INITIAL_VALUE;
}

static inline bool arch_spin_lock_held(spin_lock_t *lock) {
    return *lock != 0;
}

static inline void arch_spin_lock(spin_lock_t *lock) {
    *lock = 1;
}

static inline int arch_spin_trylock(spin_lock_t *lock) {
    return 0;
}

static inline void arch_spin_unlock(spin_lock_t *lock) {
    *lock = 0;
}

/* flags are unused on x86 */
#define ARCH_DEFAULT_SPIN_LOCK_FLAG_INTERRUPTS  0

static inline void
arch_interrupt_save(spin_lock_saved_state_t *statep, spin_lock_save_flags_t flags) {
    *statep = x86_save_flags();
    arch_disable_ints();
}

static inline void
arch_interrupt_restore(spin_lock_saved_state_t old_state, spin_lock_save_flags_t flags) {
    x86_restore_flags(old_state);
}


text:
package cloudfoundry;

import java.io.IOException;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;

import eu.cloud4soa.adapter.rest.response.model.Database;

/**
 * Utility class to handle VCAP_SERVICES env var.
 *
 * Usage mode:
 *
 * vcapstr = System.getenv("VCAP_SERVICES")
 * vcapRootNode = VcapServicesReader.parse(vcapstr)
 * credentials = VcapServicesReader.fillDatabase(vcapRootNode, "mysql-db")
 *
 * VCAP_SERVICES sample:
 *
 * {
 *   "mysql-5.1": [
 *       {
 *           "name": "dbtest2",
 *           "label": "mysql-5.1",
 *           "plan": "free",
 *           "tags": [
 *               "relational",
 *               "mysql-5.1",
 *               "mysql"
 *           ],
 *           "credentials": {
 *               "name": "d7c123396c2d04f0f91ca0fca2ed29ba6",
 *               "hostname": "192.168.252.4",
 *               "host": "192.168.252.4",
 *               "port": 3306,
 *               "user": "uQbdX9gaMX3Yu",
 *               "username": "uQbdX9gaMX3Yu",
 *               "password": "pdhYKBiaSuwVP"
 *           }
 *       },
 *       {
 *           "name": "dbtest",
 *           "label": "mysql-5.1",
 *           "plan": "free",
 *           "tags": [
 *               "relational",
 *               "mysql-5.1",
 *               "mysql"
 *           ],
 *           "credentials": {
 *               "name": "d616cbe71ba2b4b9e92c75c875a12f6bb",
 *               "hostname": "192.168.252.4",
 *               "host": "192.168.252.4",
 *               "port": 3306,
 *               "user": "uoXw2hnx0LGXP",
 *               "username": "uoXw2hnx0LGXP",
 *               "password": "pchJlDzkUnHMV"
 *           }
 *       }
 *   ]
 * }
 *
 * @author roman.sosa
 *
 */
public class VcapServicesReader {

	static ObjectMapper mapper = new ObjectMapper();

	/**
	 * Parses a json string into a JsonNode. This node is the rootNode for
	 * the rest of methods.
	 *
	 * @param json json string.
	 * @return The root JsonNode
	 * @throws JsonProcessingException
	 * @throws IOException
	 */
	public static JsonNode parse(String json) throws JsonProcessingException, IOException {

		JsonNode result = mapper.readTree(json);
		return result;
	}

	/**
	 * Returns the JsonNode corresponding a given service name.
	 */
	public static JsonNode findBindedService(JsonNode rootNode, String serviceName) {

		/*
		 * iterate over services
		 */
		for (JsonNode service : rootNode) {
			/*
			 * iterate over binded services
			 */
			for (JsonNode binded : service) {
				String name = binded.path("name").getValueAsText();
				if (serviceName.equals(name)) {
					return binded;
				}
			}
		}
		return null;
	}

	/**
	 * Fill the Database object corresponding a given service name.
	 */
	public static Database fillDatabase(JsonNode rootNode, String serviceName) {

		JsonNode binded = findBindedService(rootNode, serviceName);
		if (binded == null) {
			return null;
		}
		JsonNode credentials = binded.path("credentials");

		String dbname = credentials.path("name").getTextValue();
		String hostname = credentials.path("hostname").getTextValue();
		int port = credentials.path("port").getValueAsInt();
		String username = credentials.path("username").getTextValue();
		String password = credentials.path("password").getTextValue();

		Database result = new Database();
		result.setDatabaseName(dbname);
		result.setHost(hostname);
		result.setPort(String.valueOf(port));
		result.setUserName(username);
		result.setPassword(password);

		return result;

	}
}


text:
using System.Threading.Tasks;
using Typewriter.Core.Data;
using Typewriter.Core.Models;

namespace Typewriter.Delivery.Services
{
    public interface IDeliveryService
    {
        Task<ITypewriterEntity> Find(FindRequest request);
        Task<PagedResponse<ITypewriterEntity>> Query(QueryRequest request);
    }
}


text:
import _ from 'lodash'
import faker from 'faker'
import React from 'react'
import { Accordion } from 'semantic-ui-react'

const panels = _.times(3, () => ({
  title: faker.lorem.sentence(),
  content: faker.lorem.paragraphs(),
}))

const AccordionExampleStyled = () => (
  <Accordion panels={panels} styled />
)

export default AccordionExampleStyled


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.05.23 at 02:47:00 PM EDT
//

package oasis.names.tc.xacml._3_0.core.schema.wd_17;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for AttributeDesignatorType complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="AttributeDesignatorType">
 *   <complexContent>
 *     <extension base="{urn:oasis:names:tc:xacml:3.0:core:schema:wd-17}ExpressionType">
 *       <attribute name="Category" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
 *       <attribute name="AttributeId" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
 *       <attribute name="DataType" use="required" type="{http://www.w3.org/2001/XMLSchema}anyURI" />
 *       <attribute name="Issuer" type="{http://www.w3.org/2001/XMLSchema}string" />
 *       <attribute name="MustBePresent" use="required" type="{http://www.w3.org/2001/XMLSchema}boolean" />
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "AttributeDesignatorType")
public class AttributeDesignatorType
    extends ExpressionType
{

    @XmlAttribute(name = "Category", required = true)
    @XmlSchemaType(name = "anyURI")
    protected String category;
    @XmlAttribute(name = "AttributeId", required = true)
    @XmlSchemaType(name = "anyURI")
    protected String attributeId;
    @XmlAttribute(name = "DataType", required = true)
    @XmlSchemaType(name = "anyURI")
    protected String dataType;
    @XmlAttribute(name = "Issuer")
    protected String issuer;
    @XmlAttribute(name = "MustBePresent", required = true)
    protected boolean mustBePresent;

    /**
     * Gets the value of the category property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getCategory() {
        return category;
    }

    /**
     * Sets the value of the category property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setCategory(String value) {
        this.category = value;
    }

    /**
     * Gets the value of the attributeId property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getAttributeId() {
        return attributeId;
    }

    /**
     * Sets the value of the attributeId property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setAttributeId(String value) {
        this.attributeId = value;
    }

    /**
     * Gets the value of the dataType property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDataType() {
        return dataType;
    }

    /**
     * Sets the value of the dataType property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDataType(String value) {
        this.dataType = value;
    }

    /**
     * Gets the value of the issuer property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getIssuer() {
        return issuer;
    }

    /**
     * Sets the value of the issuer property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setIssuer(String value) {
        this.issuer = value;
    }

    /**
     * Gets the value of the mustBePresent property.
     *
     */
    public boolean isMustBePresent() {
        return mustBePresent;
    }

    /**
     * Sets the value of the mustBePresent property.
     *
     */
    public void setMustBePresent(boolean value) {
        this.mustBePresent = value;
    }

}


text:
package com.creativityloop.android.temperocapixaba.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.transition.Visibility;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import com.creativityloop.android.temperocapixaba.R;
import com.creativityloop.android.temperocapixaba.activity.FinalizarPedidoActivity;
import com.creativityloop.android.temperocapixaba.database.PedidoLab;
import com.creativityloop.android.temperocapixaba.database.PratoLab;
import com.creativityloop.android.temperocapixaba.model.ItemPedido;
import com.creativityloop.android.temperocapixaba.model.Pedido;

import java.util.ArrayList;
import java.util.List;

public class ResumoPedidoFragment extends Fragment {

    private static final int REQUEST_PEDIDO = 1;
    private static final String ARG_PEDIDO_ID = "pedido_id";
    private static final String ARG_IS_DETALHES = "is_detalhes";

    private long mPedidoId;
    private boolean mIsDetalhes;
    private Pedido mPedido;
    private List<ItemPedido> mItensPedido;

    // UI
    private ListView mResumoPedido;
    private Button mConfirmarPedido;

    public static ResumoPedidoFragment newInstance(long pedidoId, boolean isDetalhes) {
        Bundle args = new Bundle();
        args.putSerializable(ARG_PEDIDO_ID, pedidoId);
        args.putSerializable(ARG_IS_DETALHES, isDetalhes);

        ResumoPedidoFragment fragment = new ResumoPedidoFragment();
        fragment.setArguments(args);
        return fragment;
    }

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

        mPedidoId = (long) getArguments().getSerializable(ARG_PEDIDO_ID);
        mPedido = PedidoLab.get(getActivity()).getPedido(mPedidoId);
        if(mPedido == null) {
            mPedido = PedidoLab.get(getActivity()).getPedidoByIdExterno(mPedidoId);
        }
        mItensPedido = new ArrayList<>();

        for(ItemPedido itemPedido : mPedido.getItensPedido()) {
            ItemPedido itemPedidoToCopy = new ItemPedido();
            itemPedidoToCopy.setQuantidadePequena(itemPedido.getQuantidadePequena());
            itemPedidoToCopy.setQuantidadeGrande(itemPedido.getQuantidadeGrande());
            itemPedidoToCopy.setPrato(PratoLab.get(getActivity()).getPrato(itemPedido.getPratoId()));
            mItensPedido.add(itemPedidoToCopy);
        }

        mIsDetalhes = (boolean) getArguments().getSerializable(ARG_IS_DETALHES);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_resumo_pedido, container, false);

        mResumoPedido = (ListView) v.findViewById(R.id.resumo_pedido_list_view);
        mResumoPedido.setAdapter(new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, mItensPedido.toArray(new ItemPedido[mItensPedido.size()])));

        mConfirmarPedido = (Button) v.findViewById(R.id.confirmar_pedido_button);

        if(mIsDetalhes) {
            mConfirmarPedido.setVisibility(View.INVISIBLE);
        } else {
            mConfirmarPedido.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = FinalizarPedidoActivity.newIntent(getActivity(), mPedidoId);
                    startActivityForResult(intent, REQUEST_PEDIDO);
                }
            });
        }

        return v;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode != Activity.RESULT_OK) {
            return;
        }

        if(requestCode == REQUEST_PEDIDO) {
            if(data == null) {
                return;
            }

            mPedidoId = FinalizarPedidoActivity.getPedidoId(data);
        }
    }
}


text:
package org.wso2.andes.server.logging.actors;

import org.wso2.andes.server.logging.LogActor;
import org.wso2.andes.server.logging.LogSubject;
import org.wso2.andes.server.logging.RootMessageLogger;

public class GenericActor extends AbstractActor
{

    private static RootMessageLogger _defaultMessageLogger;

    private LogSubject _logSubject;

    public static RootMessageLogger getDefaultMessageLogger()
    {
        return _defaultMessageLogger;
    }

    public static void setDefaultMessageLogger(RootMessageLogger defaultMessageLogger)
    {
        _defaultMessageLogger = defaultMessageLogger;
    }

    public GenericActor(LogSubject logSubject, RootMessageLogger rootLogger)
    {
        super(rootLogger);
        _logSubject = logSubject;
    }

    public String getLogMessage()
    {
        return _logSubject.toLogString();
    }

    public static LogActor getInstance(final String logMessage, RootMessageLogger rootLogger)
    {
        return new GenericActor(new LogSubject()
        {
            public String toLogString()
            {
                return logMessage;
            }

        }, rootLogger);
    }

    public static LogActor getInstance(final String subjectMessage)
    {
        return new GenericActor(new LogSubject()
        {
            public String toLogString()
            {
                return "[" + subjectMessage + "] ";
            }

        }, _defaultMessageLogger);
    }

    public static LogActor getInstance(LogSubject logSubject)
    {
        return new GenericActor(logSubject, _defaultMessageLogger);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2013 Matthew Precious

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="6dip" >

    <ImageView
        android:id="@+id/packageIcon"
        android:layout_width="48dip"
        android:layout_height="48dip"
        android:contentDescription="@string/package_picker_icon_description" />

    <TextView
        android:id="@+id/packageName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="6dip"
        android:layout_toRightOf="@id/packageIcon"
        android:gravity="center_vertical"
        android:minHeight="?android:attr/listPreferredItemHeight"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textIsSelectable="false" />

</RelativeLayout>


text:
import os, popen2, time
from datetime import datetime
from optparse import make_option

from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from django.conf import settings
from django.contrib.sites.models import Site

# Based on: http://code.google.com/p/django-backup/
# Based on: http://www.djangosnippets.org/snippets/823/
# Based on: http://www.yashh.com/blog/2008/sep/05/django-database-backup-view/
class Command(BaseCommand):
    option_list = BaseCommand.option_list + (
        make_option('--email', '-m', default=None, dest='email',
            help='Sends email with attached dump file'),
        make_option('--compress', '-c', action='store_true', default=False, dest='compress',
            help='Compress SQL dump file using GZ'),
        make_option('--directory', '-d', action='append', default=[], dest='directories',
            help='Include Directories'),
        make_option('--zipencrypt', '-z', action='store_true', default=False,
            dest='zipencrypt', help='Compress and encrypt SQL dump file using zip'),
        make_option('--backup_docs', '-b', action='store_true', default=False,
            dest='backup_docs', help='Backup your docs directory alongside the DB dump.'),

    )
    help = "Backup database. Only Mysql, Postgresql and Sqlite engines are implemented"

    def _time_suffix(self):
        return time.strftime('%Y%m%d-%H%M%S')

    def handle(self, *args, **options):
        self.email = options.get('email')
        self.compress = options.get('compress')
        self.directories = options.get('directories')
        self.zipencrypt = options.get('zipencrypt')
        self.backup_docs = options.get('backup_docs')
        self.current_site = Site.objects.get_current()
        self.encrypt_password = "ENTER PASSWORD HERE"

        from django.db import connection
        from django.conf import settings

        try:
            self.engine = settings.DATABASE_ENGINE
            self.db = settings.DATABASE_NAME
            self.user = settings.DATABASE_USER
            self.passwd = settings.DATABASE_PASSWORD
            self.host = settings.DATABASE_HOST
            self.port = settings.DATABASE_PORT
        except:
            #Support for changed database format
            self.engine = settings.DATABASES['default']['ENGINE']
            self.db = settings.DATABASES['default']['NAME']
            self.user = settings.DATABASES['default']['USER']
            self.passwd = settings.DATABASES['default']['PASSWORD']
            self.host = settings.DATABASES['default']['HOST']
            self.port = settings.DATABASES['default']['PORT']

        self.media_directory = settings.MEDIA_ROOT

        backup_dir = 'backups'
        if self.backup_docs:
            backup_dir = "backups/%s" % self._time_suffix()

        if not os.path.exists(backup_dir):
            os.makedirs(backup_dir)

        outfile = os.path.join(backup_dir, 'backup_%s.sql' % self._time_suffix())

        #Backup documents?
        if self.backup_docs:
            print "Backing up documents directory to %s from %s" % (backup_dir,self.media_directory)
            dir_outfile = os.path.join(backup_dir, 'media_backup.tar.gz')
            self.compress_dir(self.media_directory, dir_outfile)

        # Doing backup
        if self.engine == 'mysql':
            print 'Doing Mysql backup to database %s into %s' % (self.db, outfile)
            self.do_mysql_backup(outfile)
        elif self.engine in ('postgresql_psycopg2', 'postgresql'):
            print 'Doing Postgresql backup to database %s into %s' % (self.db, outfile)
            self.do_postgresql_backup(outfile)
        elif 'sqlite3' in self.engine:
            print 'Doing sqlite backup to database %s into %s' % (self.db, outfile)
            self.do_sqlite_backup(outfile)
        else:
            raise CommandError('Backup in %s engine not implemented' % self.engine)

        # Compressing backup
        if self.compress:
            compressed_outfile = outfile + '.gz'
            print 'Compressing backup file %s to %s' % (outfile, compressed_outfile)
            self.do_compress(outfile, compressed_outfile)
            outfile = compressed_outfile

        #Zip & Encrypting backup
        if self.zipencrypt:
            zip_encrypted_outfile = outfile + ".zip"
            print 'Ziping and Encrypting backup file %s to %s' % (outfile, zip_encrypted_outfile)
            self.do_encrypt(outfile, zip_encrypted_outfile)
            outfile = zip_encrypted_outfile

        # Backuping directoris
        dir_outfiles = []
        for directory in self.directories:
            dir_outfile = os.path.join(backup_dir, '%s_%s.tar.gz' % (os.path.basename(directory), self._time_suffix()))
            dir_outfiles.append(dir_outfile)
            print("Compressing '%s' to '%s'" % (directory, dir_outfile))
            self.compress_dir(directory, dir_outfile)

        # Sending mail with backups
        if self.email:
            print "Sending e-mail with backups to '%s'" % self.email
            self.sendmail(settings.SERVER_EMAIL, [self.email], dir_outfiles + [outfile])

    def compress_dir(self, directory, outfile):
        os.system('tar -czf %s %s' % (outfile, directory))

    def sendmail(self, address_from, addresses_to, attachements):
        subject = "Your DB-backup for %s %s" % (datetime.now().strftime("%d %b %Y"), self.current_site)
        body = "Timestamp of the backup is " + datetime.now().strftime("%d %b %Y")

        email = EmailMessage(subject, body, address_from, addresses_to)
        email.content_subtype = 'html'
        for attachement in attachements:
            email.attach_file(attachement)
        email.send()

    def do_compress(self, infile, outfile):
        os.system('gzip --stdout %s > %s' % (infile, outfile))
        os.system('rm %s' % infile)

    def do_encrypt(self, infile, outfile):
        os.system('zip -P %s %s %s' % (self.encrypt_password, outfile, infile))
        os.system('rm %s' % infile)

        #os.system('gpg --yes --passphrase %s -c %s' % (self.encrypt_password, infile))
        #os.system('rm %s' % infile)

    def do_sqlite_backup(self, outfile):
        os.system('cp %s %s' % (self.db,outfile))

    def do_mysql_backup(self, outfile):
        args = []
        if self.user:
            args += ["--user=%s" % self.user]
        if self.passwd:
            args += ["--password=%s" % self.passwd]
        if self.host:
            args += ["--host=%s" % self.host]
        if self.port:
            args += ["--port=%s" % self.port]
        args += [self.db]

        os.system('mysqldump %s > %s' % (' '.join(args), outfile))

    def do_postgresql_backup(self, outfile):
        args = []
        if self.user:
            args += ["--username=%s" % self.user]
        if self.passwd:
            args += ["--password"]
        if self.host:
            args += ["--host=%s" % self.host]
        if self.port:
            args += ["--port=%s" % self.port]
        if self.db:
            args += [self.db]
        pipe = popen2.Popen4('pg_dump %s > %s' % (' '.join(args), outfile))
        if self.passwd:
            pipe.tochild.write('%s\n' % self.passwd)
            pipe.tochild.close()


text:
package com.palmg.core.main.vertx;

import java.util.List;

import com.palmg.utility.async.Msg;

import io.vertx.core.eventbus.Message;

public class DefaultMsgImpl<T> implements Msg<T> {

	Message<T> vertxMsg;

	Msg<T> setvertxMsg(Message<T> vertxMsg){
		this.vertxMsg = vertxMsg;
		return this;
	}

	@Override
	public List<String> getHeader(String name) {
		vertxMsg.headers().getAll(name);
		return null;
	}

	@Override
	public String getAddress() {
		return vertxMsg.address();
	}

	@Override
	public T getMessage() {
		return vertxMsg.body();
	}

	@Override
	public void reply(Object msg) {
		vertxMsg.reply(msg);
	}

	@Override
	public void fail(String errMsg) {
		vertxMsg.fail(-1, errMsg);
	}
}


text:
WebInspector.ApplicationCacheItemsView = function(treeElement, appcacheDomain)
{
    WebInspector.View.call(this);

    this.element.addStyleClass("storage-view");
    this.element.addStyleClass("table");

    // FIXME: Delete Button semantics are not yet defined.
    // FIXME: Needs better tooltip. (Localized)
    this.deleteButton = new WebInspector.StatusBarButton(WebInspector.UIString("Delete"), "delete-storage-status-bar-item");
    this.deleteButton.visible = false;
    this.deleteButton.addEventListener("click", this._deleteButtonClicked.bind(this), false);

    // FIXME: Refresh Button semantics are not yet defined.
    // FIXME: Needs better tooltip. (Localized)
    this.refreshButton = new WebInspector.StatusBarButton(WebInspector.UIString("Refresh"), "refresh-storage-status-bar-item");
    this.refreshButton.addEventListener("click", this._refreshButtonClicked.bind(this), false);

    if (Preferences.onlineDetectionEnabled) {
        this.connectivityIcon = document.createElement("img");
        this.connectivityIcon.className = "storage-application-cache-connectivity-icon";
        this.connectivityIcon.src = "";
        this.connectivityMessage = document.createElement("span");
        this.connectivityMessage.className = "storage-application-cache-connectivity";
        this.connectivityMessage.textContent = "";
    }

    this.divider = document.createElement("span");
    this.divider.className = "status-bar-item status-bar-divider";

    this.statusIcon = document.createElement("img");
    this.statusIcon.className = "storage-application-cache-status-icon";
    this.statusIcon.src = "";
    this.statusMessage = document.createElement("span");
    this.statusMessage.className = "storage-application-cache-status";
    this.statusMessage.textContent = "";

    this._treeElement = treeElement;
    this._appcacheDomain = appcacheDomain;

    this._emptyMsgElement = document.createElement("div");
    this._emptyMsgElement.className = "storage-empty-view";
    this._emptyMsgElement.textContent = WebInspector.UIString("No Application Cache information available.");
    this.element.appendChild(this._emptyMsgElement);

    this.updateStatus(applicationCache.UNCACHED);
}

WebInspector.ApplicationCacheItemsView.prototype = {
    get statusBarItems()
    {
        if (Preferences.onlineDetectionEnabled) {
            return [
                this.refreshButton.element, this.deleteButton.element,
                this.connectivityIcon, this.connectivityMessage, this.divider,
                this.statusIcon, this.statusMessage
            ];
        } else {
            return [
                this.refreshButton.element, this.deleteButton.element, this.divider,
                this.statusIcon, this.statusMessage
            ];
        }
    },

    show: function(parentElement)
    {
        WebInspector.View.prototype.show.call(this, parentElement);
        this.updateNetworkState(navigator.onLine);
        this._update();
    },

    hide: function()
    {
        WebInspector.View.prototype.hide.call(this);
        this.deleteButton.visible = false;
    },

    updateStatus: function(status)
    {
        var statusInformation = {};
        statusInformation[applicationCache.UNCACHED]    = { src: "Images/warningOrangeDot.png", text: "UNCACHED"    };
        statusInformation[applicationCache.IDLE]        = { src: "Images/warningOrangeDot.png", text: "IDLE"        };
        statusInformation[applicationCache.CHECKING]    = { src: "Images/successGreenDot.png",  text: "CHECKING"    };
        statusInformation[applicationCache.DOWNLOADING] = { src: "Images/successGreenDot.png",  text: "DOWNLOADING" };
        statusInformation[applicationCache.UPDATEREADY] = { src: "Images/successGreenDot.png",  text: "UPDATEREADY" };
        statusInformation[applicationCache.OBSOLETE]    = { src: "Images/errorRedDot.png",      text: "OBSOLETE"    };

        var info = statusInformation[status];
        if (!info) {
            console.error("Unknown Application Cache Status was Not Handled: %d", status);
            return;
        }

        this.statusIcon.src = info.src;
        this.statusMessage.textContent = info.text;
    },

    updateNetworkState: function(isNowOnline)
    {
        if (Preferences.onlineDetectionEnabled) {
            if (isNowOnline) {
                this.connectivityIcon.src = "Images/successGreenDot.png";
                this.connectivityMessage.textContent = WebInspector.UIString("Online");
            } else {
                this.connectivityIcon.src = "Images/errorRedDot.png";
                this.connectivityMessage.textContent = WebInspector.UIString("Offline");
            }
        }
    },

    _update: function()
    {
        WebInspector.ApplicationCache.getApplicationCachesAsync(this._updateCallback.bind(this));
    },

    _updateCallback: function(applicationCaches)
    {
        // FIXME: applicationCaches is just one cache.
        // FIXME: are these variables needed anywhere else?
        this._manifest = applicationCaches.manifest;
        this._creationTime = applicationCaches.creationTime;
        this._updateTime = applicationCaches.updateTime;
        this._size = applicationCaches.size;
        this._resources = applicationCaches.resources;
        var lastPathComponent = applicationCaches.lastPathComponent;

        if (!this._manifest) {
            this._emptyMsgElement.removeStyleClass("hidden");
            this.deleteButton.visible = false;
            if (this._dataGrid)
                this._dataGrid.element.addStyleClass("hidden");
            return;
        }

        if (!this._dataGrid)
            this._createDataGrid();

        this._populateDataGrid();
        this._dataGrid.autoSizeColumns(20, 80);
        this._dataGrid.element.removeStyleClass("hidden");
        this._emptyMsgElement.addStyleClass("hidden");
        this.deleteButton.visible = true;

        var totalSizeString = Number.bytesToString(this._size, WebInspector.UIString);
        this._treeElement.subtitle = WebInspector.UIString("%s (%s)", lastPathComponent, totalSizeString);

        // FIXME: For Chrome, put creationTime and updateTime somewhere.
        // NOTE: localizedString has not yet been added.
        // WebInspector.UIString("(%s) Created: %s Updated: %s", this._size, this._creationTime, this._updateTime);
    },

    _createDataGrid: function()
    {
        var columns = { 0: {}, 1: {}, 2: {} };
        columns[0].title = WebInspector.UIString("Resource");
        columns[0].sort = "ascending";
        columns[0].sortable = true;
        columns[1].title = WebInspector.UIString("Type");
        columns[1].sortable = true;
        columns[2].title = WebInspector.UIString("Size");
        columns[2].aligned = "right";
        columns[2].sortable = true;
        this._dataGrid = new WebInspector.DataGrid(columns);
        this.element.appendChild(this._dataGrid.element);
        this._dataGrid.addEventListener("sorting changed", this._populateDataGrid, this);
        this._dataGrid.updateWidths();
    },

    _populateDataGrid: function()
    {
        var selectedResource = this._dataGrid.selectedNode ? this._dataGrid.selectedNode.resource : null;
        var sortDirection = this._dataGrid.sortOrder === "ascending" ? 1 : -1;

        function numberCompare(field, resource1, resource2)
        {
            return sortDirection * (resource1[field] - resource2[field]);
        }
        function localeCompare(field, resource1, resource2)
        {
             return sortDirection * (resource1[field] + "").localeCompare(resource2[field] + "")
        }

        var comparator;
        switch (parseInt(this._dataGrid.sortColumnIdentifier)) {
            case 0: comparator = localeCompare.bind(this, "name"); break;
            case 1: comparator = localeCompare.bind(this, "type"); break;
            case 2: comparator = numberCompare.bind(this, "size"); break;
            default: localeCompare.bind(this, "resource"); // FIXME: comparator = ?
        }

        this._resources.sort(comparator);
        this._dataGrid.removeChildren();

        var nodeToSelect;
        for (var i = 0; i < this._resources.length; ++i) {
            var data = {};
            var resource = this._resources[i];
            data[0] = resource.name;
            data[1] = resource.type;
            data[2] = Number.bytesToString(resource.size, WebInspector.UIString);
            var node = new WebInspector.DataGridNode(data);
            node.resource = resource;
            node.selectable = true;
            this._dataGrid.appendChild(node);
            if (resource === selectedResource) {
                nodeToSelect = node;
                nodeToSelect.selected = true;
            }
        }

        if (!nodeToSelect)
            this._dataGrid.children[0].selected = true;
    },

    resize: function()
    {
        if (this._dataGrid)
            this._dataGrid.updateWidths();
    },

    _deleteButtonClicked: function(event)
    {
        if (!this._dataGrid || !this._dataGrid.selectedNode)
            return;

        // FIXME: Delete Button semantics are not yet defined. (Delete a single, or all?)
        this._deleteCallback(this._dataGrid.selectedNode);
    },

    _deleteCallback: function(node)
    {
        // FIXME: Should we delete a single (selected) resource or all resources?
        // InspectorBackend.deleteCachedResource(...)
        // this._update();
    },

    _refreshButtonClicked: function(event)
    {
        // FIXME: Is this a refresh button or a re-fetch manifest button?
        // this._update();
    }
}

WebInspector.ApplicationCacheItemsView.prototype.__proto__ = WebInspector.View.prototype;


text:
Rails.application.routes.draw do
  # The priority is based upon order of creation: first created -> highest priority.
  # See how all your routes lay out with "rake routes".

  scope 'api' do
    mount_devise_token_auth_for 'User', at: 'auth'

    get 'config/:model'  => 'config#show'
    get 'lookups/:model' => 'config#lookups'
    get 'schema/:model'  => 'config#schema'

    resources :users do
      post 'send_confirmation_instructions', on: :collection
      post 'lock', on: :member
      post 'unlock', on: :member
      post 'reset_password', on: :member
      post 'change_password', on: :member
      post 'bulk_upload', on: :member
    end
    resources :roles
    resources :apartment_buildings
    resources :apartments
    resources :guests
    resources :apartment_bookings

    # Reports
    get 'reports/:action'  => 'reports#:action', :defaults => {
      :format => :html
    }, :constraints => {
      :format => /(html|csv|pdf)/
    }
  end

  # You can have the root of your site routed with "root"
  # root 'welcome#index'

  # Example of regular route:
  #   get 'products/:id' => 'catalog#view'

  # Example of named route that can be invoked with purchase_url(id: product.id)
  #   get 'products/:id/purchase' => 'catalog#purchase', as: :purchase

  # Example resource route (maps HTTP verbs to controller actions automatically):
  #   resources :products

  # Example resource route with options:
  #   resources :products do
  #     member do
  #       get 'short'
  #       post 'toggle'
  #     end
  #
  #     collection do
  #       get 'sold'
  #     end
  #   end

  # Example resource route with sub-resources:
  #   resources :products do
  #     resources :comments, :sales
  #     resource :seller
  #   end

  # Example resource route with more complex sub-resources:
  #   resources :products do
  #     resources :comments
  #     resources :sales do
  #       get 'recent', on: :collection
  #     end
  #   end

  # Example resource route with concerns:
  #   concern :toggleable do
  #     post 'toggle'
  #   end
  #   resources :posts, concerns: :toggleable
  #   resources :photos, concerns: :toggleable

  # Example resource route within a namespace:
  #   namespace :admin do
  #     # Directs /admin/products/* to Admin::ProductsController
  #     # (app/controllers/admin/products_controller.rb)
  #     resources :products
  #   end
end


text:
#import <UIKit/UIKit.h>
#import "ZUUIRevealController.h"

@interface RevealController : ZUUIRevealController <ZUUIRevealControllerDelegate>

@end


text:
describe("fizzBuzz", function () {

});