text:
#include "ConsumerRunningInfo.h"

namespace rmq
{

const std::string ConsumerRunningInfo::PROP_NAMESERVER_ADDR = "PROP_NAMESERVER_ADDR";
const std::string ConsumerRunningInfo::PROP_THREADPOOL_CORE_SIZE = "PROP_THREADPOOL_CORE_SIZE";
const std::string ConsumerRunningInfo::PROP_CONSUME_ORDERLY = "PROP_CONSUMEORDERLY";
const std::string ConsumerRunningInfo::PROP_CONSUME_TYPE = "PROP_CONSUME_TYPE";
const std::string ConsumerRunningInfo::PROP_CLIENT_VERSION = "PROP_CLIENT_VERSION";
const std::string ConsumerRunningInfo::PROP_CONSUMER_START_TIMESTAMP = "PROP_CONSUMER_START_TIMESTAMP";

ConsumerRunningInfo::ConsumerRunningInfo()
{
}

ConsumerRunningInfo::~ConsumerRunningInfo()
{
}

void ConsumerRunningInfo::encode(std::string& outData)
{
    std::stringstream ss;
    ss  << "{"
        << "}";
    outData = ss.str();
}

std::string ConsumerRunningInfo::formatString()
{
	std::string sb = "rocketmq-client4cpp not suppport this feature";

	/*
	// 1
	{
		sb.append("#Consumer Properties#\n");
		Iterator<Entry<Object, Object>> it = m_properties.entrySet().iterator();
		while (it.hasNext()) {
			Entry<Object, Object> next = it.next();
			String item =
					String.format("%-40s: %s\n", next.getKey().toString(), next.getValue().toString());
			sb.append(item);
		}
	}

	// 2
	{
		sb.append("\n\n#Consumer Subscription#\n");

		Iterator<SubscriptionData> it = m_subscriptionSet.iterator();
		int i = 0;
		while (it.hasNext()) {
			SubscriptionData next = it.next();
			String item = String.format("%03d Topic: %-40s ClassFilter: %-8s SubExpression: %s\n", //
				++i,//
				next.getTopic(),//
				next.isClassFilterMode(),//
				next.getSubString());

			sb.append(item);
		}
	}

	// 3
	{
		sb.append("\n\n#Consumer Offset#\n");
		sb.append(String.format("%-32s  %-32s  %-4s  %-20s\n",//
			"#Topic",//
			"#Broker Name",//
			"#QID",//
			"#Consumer Offset"//
		));

		Iterator<Entry<MessageQueue, ProcessQueueInfo>> it = m_mqTable.entrySet().iterator();
		while (it.hasNext()) {
			Entry<MessageQueue, ProcessQueueInfo> next = it.next();
			String item = String.format("%-32s  %-32s  %-4d  %-20d\n",//
				next.getKey().getTopic(),//
				next.getKey().getBrokerName(),//
				next.getKey().getQueueId(),//
				next.getValue().getCommitOffset());

			sb.append(item);
		}
	}

	// 4
	{
		sb.append("\n\n#Consumer MQ Detail#\n");
		sb.append(String.format("%-32s  %-32s  %-4s  %-20s\n",//
			"#Topic",//
			"#Broker Name",//
			"#QID",//
			"#ProcessQueueInfo"//
		));

		Iterator<Entry<MessageQueue, ProcessQueueInfo>> it = m_mqTable.entrySet().iterator();
		while (it.hasNext()) {
			Entry<MessageQueue, ProcessQueueInfo> next = it.next();
			String item = String.format("%-32s  %-32s  %-4d  %s\n",//
				next.getKey().getTopic(),//
				next.getKey().getBrokerName(),//
				next.getKey().getQueueId(),//
				next.getValue().toString());

			sb.append(item);
		}
	}

	// 5
	{
		sb.append("\n\n#Consumer RT&TPS#\n");
		sb.append(String.format("%-32s  %14s %14s %14s %14s %18s %25s\n",//
			"#Topic",//
			"#Pull RT",//
			"#Pull TPS",//
			"#Consume RT",//
			"#ConsumeOK TPS",//
			"#ConsumeFailed TPS",//
			"#ConsumeFailedMsgsInHour"//
		));

		Iterator<Entry<String, ConsumeStatus>> it = m_statusTable.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, ConsumeStatus> next = it.next();
			String item = String.format("%-32s  %14.2f %14.2f %14.2f %14.2f %18.2f %25d\n",//
				next.getKey(),//
				next.getValue().getPullRT(),//
				next.getValue().getPullTPS(),//
				next.getValue().getConsumeRT(),//
				next.getValue().getConsumeOKTPS(),//
				next.getValue().getConsumeFailedTPS(),//
				next.getValue().getConsumeFailedMsgs()//
				);

			sb.append(item);
		}
	}

	// 6
	if (m_jstack != null) {
		sb.append("\n\n#Consumer jstack#\n");
		sb.append(m_jstack);
	}
	*/

	return sb;
}

}


text:
<?php
include "lib_function.php";
$nama = $_POST['namamerk']; // Ambil data dari Form
$link = koneksi_db();
$sql = "INSERT INTO merk values(null,'$nama','T')";
$res = mysql_query($sql, $link); // Eksekusi SQL
if ($res) {
    $id_merk = mysql_insert_id($link);
    header("Location:../view_merek.php");
} else {
    ?>

Terjadi kesalahan dalam penyimpanan data merk baru. Silahkan diulang lagi.

<?php
}
?>

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System.Collections;

public class Enemy2Script : MonoBehaviour
{
    public GameObject laserEnemy;
	public GameObject particleOnHit;
    public int energy;
    public Vector3 velocity;
    public float verticalMovement;
    float time;
    public int timeToShoot;
    // Use this for initialization
    void Start()
    {
        StartCoroutine(Shoot());
    }

    // Update is called once per frame
    void Update()
    {
        transform.Translate(velocity * Time.deltaTime);
        transform.Translate(new Vector3(verticalMovement * Mathf.Cos(time), 0, 0));
        Vector2 screenPosition = Camera.main.WorldToScreenPoint(transform.position);
        time += Time.deltaTime;

        if (screenPosition.y < 0 || energy == 0)
        {
            destroyEnemy();
        }
    }

    public void destroyEnemy()
    {
        Destroy(this.gameObject);
    }

    public IEnumerator Shoot()
    {
        yield return new WaitForSeconds(timeToShoot);
        Instantiate(laserEnemy, transform.position + new Vector3(0, -1, 0), transform.rotation);
        StartCoroutine(Shoot());
    }

	void OnTriggerEnter2D(Collider2D other) {
		if(other.CompareTag("Laser"))
		{
			GameObject.Find("Main Camera").GetComponent<ScreenShake>().Shake(1f);
			Instantiate(particleOnHit, transform.position, transform.rotation);
			energy--;
			Destroy(other.gameObject);
		}
	}
}


text:
<?php

class ServiceTestController {
    private static $classes = NULL;

    public static $testExpires = 60;
    public static $initSql = NULL;

    public static function serviceTestPreset($class) {
        if (ServiceTestController::$classes === NULL) {
            ServiceTestController::$classes = array();
        }

        ServiceTestController::$classes[] = $class;
    }

    protected static function serviceNameFromPath($path) {
        $dir = dirname($path);
        $name = basename($path, 'Test.php');
        return $name . ':' . hash('crc32b', $dir);
    }

    public static function init() {
        $sqls = explode('/', preg_replace('/\s+/', ' ', file_get_contents(ServiceTestController::$initSql)));
        foreach ($sqls as $sql) {
            if ($sql != '' && $sql != ' ') {
                ActiveRecord\Connection::instance()->query($sql);
            }
        }

        foreach (ServiceTestController::$classes as $cls) {
            $name = self::serviceNameFromPath($cls);

            $c = ServiceTest::find('first', array('conditions' => array('name = ?', $name)));
            if (!$c) {
                $c = ServiceTest::create(array(
                    'name' => $name,
                    'path' => $cls
                ));

                ServiceTestStatus::create(array(
                        'service_test_id' => $c->id,
                        'run_date' => new ActiveRecord\DateTime('1970-01-01 00:00:00'),
                        'status' => ServiceTestStatus::STATUS_EXPIRED,
                        'response_time' => 0
                ));

            }
        }
    }

    public static function isOk($cnf = null) {
        if ($cnf == null) {
            return FALSE;
        }

        $stats = self::getCurrentStatus($cnf);

        foreach ($stats as $stat) {
            if ($stat->status != ServiceTestStatus::STATUS_OK) {
                return FALSE;
            }
        }

        return TRUE;
    }

    public static function getCurrentStatus($cnf = null) {
        if ($cnf == null) {
            return self::getCurrentStatusAll();
        }

        return self::getCurrentStatusByConfig(
            ConfigService::find('all', array('conditions' => array('name=?', $cnf))));
    }

    protected static function getCurrentStatusByConfig(array $cnf) {
        if ($cnf == null || count($cnf) < 1) {
            return array();
        }

        $id = array();
        foreach ($cnf as $c) {
            $id[] = $c->service_test_id;
        }
        $ids = implode(',', $id);

        $status = ServiceTestStatus::STATUS_EXPIRED;
        $dtime = new ActiveRecord\DateTime(
            date('c', time() - self::$testExpires));
        $expire = $dtime->format('db');

        $sql = <<<sql
select
  t.id
 ,t.service_test_id
 ,t.run_date
 ,case
  when run_date < '{$expire}'
  then '{$status}'
  else t.status
  end as status
 ,t.response_time
from
  `service_test_statuses` t
inner join
 (select
    s.service_test_id
   ,max(s.run_date) as last_run_date
  from
    service_test_statuses s
  where
    s.service_test_id in ({$ids})
  group by
    s.service_test_id) l
on
  t.service_test_id = l.service_test_id
  and t.run_date = l.last_run_date
sql
            ;

        return ServiceTestStatus::find_by_sql($sql);
    }

    protected static function getCurrentStatusAll() {
        $status = ServiceTestStatus::STATUS_EXPIRED;
        $dtime = new ActiveRecord\DateTime(
            date('c', time() - self::$testExpires));
        $expire = $dtime->format('db');

        $sql = <<<sql
select
  t.id
 ,t.service_test_id
 ,t.run_date
 ,case
  when run_date < '{$expire}'
  then '{$status}'
  else t.status
  end as status
 ,t.response_time
from
  `service_test_statuses` t
inner join
 (select
    service_test_id
   ,max(run_date) as last_run_date
  from
    service_test_statuses
  group by
    service_test_id) l
on
  t.service_test_id = l.service_test_id
  and t.run_date = l.last_run_date
sql
            ;

        return ServiceTestStatus::find_by_sql($sql);
    }

    protected static function getExpiredServices() {
        $dtime = new ActiveRecord\DateTime(
            date('c', time() - self::$testExpires));
        $expire = $dtime->format('db');

        return ServiceTest::find_by_sql(<<<SQL
select
  t.*
from
  `service_tests` t
inner join
 (select
    service_test_id
   ,max(run_date) as last_run_date
  from
    service_test_statuses
  group by
    service_test_id
  having
    last_run_date < '{$expire}') l
on
  t.id = l.service_test_id
SQL
);
    }

    public static function updateAll($force = false) {
        if ($force) {
            $tests = self::getExpiredServices();
        } else {
            $tests = ServiceTest::find('all');
        }

        foreach ($tests as $test) {
            self::runTest($test);
        }
    }

    public static function runTest(ServiceTest $test) {

        $suite = new PHPUnit_Framework_TestSuite();

        $suite->addTestFile($test->path);

        $result = $suite->run();

        $pass = $result->passed();

        $restime = -1;

        foreach($pass as $k => $v) {
            if (strpos($k, 'testResponseTime') > 0) {
                $restime = intval($v['result']['time']);
                $stat = $v['result']['degraded'] ? ServiceTestStatus::STATUS_DEGRADED : ServiceTestStatus::STATUS_OK;
            }
        }

        if ($result->failureCount() > 0) {
            $stat = ServiceTestStatus::STATUS_DOWN;
        }

        ServiceTestStatus::create(array(
            'service_test_id' => $test->id,
            'run_date' => new ActiveRecord\DateTime(),
            'status' => $stat,
            'response_time' => $restime
        ));
    }
}


text:
<?php
namespace Oro\Bundle\NavigationBundle\Title\TitleReader;

use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;

class ConfigReader extends Reader
{
    /**
     * @var array
     */
    private $configData = array();

    public function __construct(array $configData)
    {
        $this->configData = $configData;
    }

    /**
     * Get Route/Title information from bundle configs
     *
     * @param  array                                                                        $routes
     * @return array
     * @throws \Symfony\Component\Config\Definition\Exception\InvalidConfigurationException
     */
    public function getData(array $routes)
    {
        $data = array();

        foreach ($this->configData as $route => $title) {
            if (array_key_exists($route, $routes)) {
                $data[$route] = $title;
            } else {
                throw new InvalidConfigurationException(
                    sprintf('Title for route "%s" could not be saved. Route not found.', $route)
                );
            }
        }

        return $data;
    }
}


text:
var Count = require('../models/count');

module.exports.index = function (req, res, next) {
  Count.all(function (err, listCount) {
    res.render('index.jade',
        {imports: 'window.listCount = ' + JSON.stringify(listCount)});
  });
};

module.exports.public = function (req, res, next) {
  Count.find(req.params.id, function (err, count) {
    if (err !== null && err !== undefined) {
      console.error('Finding public url error');
      return next({status: 404});
    }
    if (count === null) {
      console.error('Bad public url recieve');
      return next({status: 404});
    }

    res.render('index_public.jade',
        {imports: 'window.count = ' + JSON.stringify(count)});
  });
};


text:
package com.orientechnologies.orient.core.db;

import java.util.List;
import java.util.Set;

import com.orientechnologies.orient.core.command.OCommandRequest;
import com.orientechnologies.orient.core.db.object.ODatabaseObject;
import com.orientechnologies.orient.core.db.record.ODatabaseRecord;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.dictionary.ODictionary;
import com.orientechnologies.orient.core.exception.OTransactionException;
import com.orientechnologies.orient.core.hook.ORecordHook;
import com.orientechnologies.orient.core.hook.ORecordHook.RESULT;
import com.orientechnologies.orient.core.hook.ORecordHook.TYPE;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.metadata.OMetadata;
import com.orientechnologies.orient.core.metadata.security.OSecurity;
import com.orientechnologies.orient.core.metadata.security.OUser;
import com.orientechnologies.orient.core.query.OQuery;
import com.orientechnologies.orient.core.storage.ORecordCallback;
import com.orientechnologies.orient.core.storage.OStorage;
import com.orientechnologies.orient.core.tx.OTransaction;
import com.orientechnologies.orient.core.tx.OTransaction.TXTYPE;

/**
 * Database interface that represents a complex database. It extends the base ODatabase interface adding all the higher-level APIs
 * to treats records. Entities can be implementations of ORecord class for ODatabaseRecord or any POJO for ODatabaseObject. The
 * behaviour of the datastore depends by the OStorage implementation used.
 *
 * @author Luca Garulli
 *
 * @see ODatabaseRecord
 * @see ODatabaseObject
 * @see OStorage
 * @param <T>
 */
public interface ODatabaseComplex<T extends Object> extends ODatabase, OUserObject2RecordHandler {
  public enum OPERATION_MODE {
    SYNCHRONOUS, ASYNCHRONOUS, ASYNCHRONOUS_NOANSWER
  }

  /**
   * Creates a new entity instance.
   *
   * @return The new instance.
   */
  public <RET extends Object> RET newInstance();

  /**
   * Returns the Dictionary manual index.
   *
   * @return ODictionary instance
   */
  public ODictionary<T> getDictionary();

  /**
   * Returns the current user logged into the database.
   *
   * @see OSecurity
   */
  public OUser getUser();

  /**
   * Loads the entity and return it.
   *
   * @param iObject
   *          The entity to load. If the entity was already loaded it will be reloaded and all the changes will be lost.
   * @return
   */
  public <RET extends T> RET load(T iObject);

  /**
   * Loads a record using a fetch plan.
   *
   * @param iDocument
   *          Record to load
   * @param iFetchPlan
   *          Fetch plan used
   * @return The record received
   */
  public <RET extends T> RET load(T iObject, String iFetchPlan);

  /**
   * Loads a record using a fetch plan.
   *
   * @param iDocument
   *          Record to load
   * @param iFetchPlan
   *          Fetch plan used
   * @param iIgnoreCache
   *          Ignore cache or use it
   * @return The record received
   */
  public <RET extends T> RET load(T iObject, String iFetchPlan, boolean iIgnoreCache);

  /**
   * Force the reloading of the entity.
   *
   * @param iObject
   *          The entity to load. If the entity was already loaded it will be reloaded and all the changes will be lost.
   * @param iFetchPlan
   *          Fetch plan used
   * @param iIgnoreCache
   *          Ignore cache or use it
   * @return The loaded entity
   */
  public <RET extends T> RET reload(final T iObject, String iFetchPlan, boolean iIgnoreCache);

  /**
   * Loads the entity by the Record ID.
   *
   * @param iRecordId
   *          The unique record id of the entity to load.
   * @return The loaded entity
   */
  public <RET extends T> RET load(ORID iRecordId);

  /**
   * Loads the entity by the Record ID using a fetch plan.
   *
   * @param iRecordId
   *          The unique record id of the entity to load.
   * @param iFetchPlan
   *          Fetch plan used
   * @return The loaded entity
   */
  public <RET extends T> RET load(ORID iRecordId, String iFetchPlan);

  /**
   * Loads the entity by the Record ID using a fetch plan and specifying if the cache must be ignored.
   *
   * @param iRecordId
   *          The unique record id of the entity to load.
   * @param iFetchPlan
   *          Fetch plan used
   * @param iIgnoreCache
   *          Ignore cache or use it
   * @return The loaded entity
   */
  public <RET extends T> RET load(ORID iRecordId, String iFetchPlan, boolean iIgnoreCache);

  /**
   * Saves an entity in synchronous mode. If the entity is not dirty, then the operation will be ignored. For custom entity
   * implementations assure to set the entity as dirty.
   *
   * @param iObject
   *          The entity to save
   * @return The saved entity.
   */
  public <RET extends T> RET save(T iObject);

  /**
   * Saves an entity specifying the mode. If the entity is not dirty, then the operation will be ignored. For custom entity
   * implementations assure to set the entity as dirty. If the cluster does not exist, an error will be thrown.
   *
   *
   * @param iObject
   *          The entity to save
   * @param iMode
   *          Mode of save: synchronous (default) or asynchronous
   * @param iForceCreate
   *          Flag that indicates that record should be created. If record with current rid already exists, exception is thrown
   * @param iCallback
   *          Callback to call once the save is made @return The saved entity.
   */
  public <RET extends T> RET save(T iObject, OPERATION_MODE iMode, boolean iForceCreate, ORecordCallback<? extends Number> iCallback);

  /**
   * Saves an entity in the specified cluster in synchronous mode. If the entity is not dirty, then the operation will be ignored.
   * For custom entity implementations assure to set the entity as dirty. If the cluster does not exist, an error will be thrown.
   *
   * @param iObject
   *          The entity to save
   * @param iClusterName
   *          Name of the cluster where to save
   * @return The saved entity.
   */
  public <RET extends T> RET save(T iObject, String iClusterName);

  /**
   * Saves an entity in the specified cluster specifying the mode. If the entity is not dirty, then the operation will be ignored.
   * For custom entity implementations assure to set the entity as dirty. If the cluster does not exist, an error will be thrown.
   *
   *
   * @param iObject
   *          The entity to save
   * @param iClusterName
   *          Name of the cluster where to save
   * @param iMode
   *          Mode of save: synchronous (default) or asynchronous
   * @param iForceCreate
   *          Flag that indicates that record should be created. If record with current rid already exists, exception is thrown
   * @param iCallback
   *          Callback to call once the save is made @return The saved entity.
   */
  public <RET extends T> RET save(T iObject, String iClusterName, OPERATION_MODE iMode, boolean iForceCreate,
      ORecordCallback<? extends Number> iCallback);

  /**
   * Deletes an entity from the database in synchronous mode.
   *
   * @param iObject
   *          The entity to delete.
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public ODatabaseComplex<T> delete(T iObject);

  /**
   * Deletes the entity with the received RID from the database.
   *
   * @param iRID
   *          The RecordID to delete.
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public ODatabaseComplex<T> delete(ORID iRID);

  /**
   * Deletes the entity with the received RID from the database.
   *
   * @param iRID
   *          The RecordID to delete.
   * @param iVersion
   *          for MVCC
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public ODatabaseComplex<T> delete(ORID iRID, int iVersion);

  /**
   * Return active transaction. Cannot be null. If no transaction is active, then a OTransactionNoTx instance is returned.
   *
   * @return OTransaction implementation
   */
  public OTransaction getTransaction();

  /**
   * Begins a new transaction. By default the type is OPTIMISTIC. If a previous transaction was started it will be rollbacked and
   * closed before to start a new one. A transaction once begun has to be closed by calling the {@link #commit()} or
   * {@link #rollback()}.
   *
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public ODatabaseComplex<T> begin();

  /**
   * Begins a new transaction specifying the transaction type. If a previous transaction was started it will be rollbacked and
   * closed before to start a new one. A transaction once begun has to be closed by calling the {@link #commit()} or
   * {@link #rollback()}.
   *
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public ODatabaseComplex<T> begin(TXTYPE iStatus);

  /**
   * Attaches a transaction as current.
   *
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public ODatabaseComplex<T> begin(OTransaction iTx) throws OTransactionException;

  /**
   * Commits the current transaction. The approach is all or nothing. All changes will be permanent following the storage type. If
   * the operation succeed all the entities changed inside the transaction context will be effectives. If the operation fails, all
   * the changed entities will be restored in the datastore. Memory instances are not guaranteed to being restored as well.
   *
   * @return
   */
  public ODatabaseComplex<T> commit() throws OTransactionException;

  /**
   * Aborts the current running transaction. All the pending changed entities will be restored in the datastore. Memory instances
   * are not guaranteed to being restored as well.
   *
   * @return
   */
  public ODatabaseComplex<T> rollback() throws OTransactionException;

  /**
   * Execute a query against the database.
   *
   * @param iCommand
   *          Query command
   * @param iArgs
   *          Optional parameters to bind to the query
   * @return List of POJOs
   */
  public <RET extends List<?>> RET query(final OQuery<?> iCommand, final Object... iArgs);

  /**
   * Execute a command against the database. A command can be a SQL statement or a Procedure. If the OStorage used is remote
   * (OStorageRemote) then the command will be executed remotely and the result returned back to the calling client.
   *
   * @param iCommand
   *          Command request to execute.
   * @return The same Command request received as parameter.
   * @see OStorageRemote
   */
  public <RET extends OCommandRequest> RET command(OCommandRequest iCommand);

  /**
   * Return the OMetadata instance. Cannot be null.
   *
   * @return The OMetadata instance.
   */
  public OMetadata getMetadata();

  /**
   * Returns the database owner. Used in wrapped instances to know the up level ODatabase instance.
   *
   * @return Returns the database owner.
   */
  public ODatabaseComplex<?> getDatabaseOwner();

  /**
   * Internal. Sets the database owner.
   */
  public ODatabaseComplex<?> setDatabaseOwner(ODatabaseComplex<?> iOwner);

  /**
   * Return the underlying database. Used in wrapper instances to know the down level ODatabase instance.
   *
   * @return The underlying ODatabase implementation.
   */
  public <DB extends ODatabase> DB getUnderlying();

  /**
   * Internal method. Don't call it directly unless you're building an internal component.
   */
  public void setInternal(ATTRIBUTES attribute, Object iValue);

  /**
   * Registers a hook to listen all events for Records.
   *
   * @param iHookImpl
   *          ORecordHook implementation
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public <DB extends ODatabaseComplex<?>> DB registerHook(ORecordHook iHookImpl);

  /**
   * Retrieves all the registered hooks.
   *
   * @return A not-null unmodifiable set of ORecordHook instances. If there are no hooks registered, the Set is empty.
   */
  public Set<ORecordHook> getHooks();

  /**
   * Unregisters a previously registered hook.
   *
   * @param iHookImpl
   *          ORecordHook implementation
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public <DB extends ODatabaseComplex<?>> DB unregisterHook(ORecordHook iHookImpl);

  /**
   * Invokes the callback on all the configured hooks.
   *
   * @param iObject
   *          The object passed change based on the Database implementation: records for {@link ODatabaseRecord} implementations and
   *          POJO for {@link ODatabaseObject} implementations.
   * @return True if the input record is changed, otherwise false
   */
  public RESULT callbackHooks(TYPE iType, OIdentifiable iObject);

  /**
   * Returns if the Multi Version Concurrency Control is enabled or not. If enabled the version of the record is checked before each
   * update and delete against the records.
   *
   * @return true if enabled, otherwise false
   * @see ODatabaseRecord#setMVCC(boolean)
   */
  public boolean isMVCC();

  /**
   * Enables or disables the Multi-Version Concurrency Control. If enabled the version of the record is checked before each update
   * and delete against the records.
   *
   * @param iValue
   * @see ODatabaseRecord#isMVCC()
   * @return The Database instance itself giving a "fluent interface". Useful to call multiple methods in chain.
   */
  public <DB extends ODatabaseComplex<?>> DB setMVCC(boolean iValue);

  public String getType();
}


text:
@interface LSPDropdownMenu()
@property (strong,nonatomic) UIImageView *containerView;
@end
@implementation LSPDropdownMenu

- (UIImageView *)containerView
{
    if (!_containerView) {
        _containerView = [[UIImageView alloc] init];

        _containerView.image = [UIImage imageNamed:@"popover_background"];
        [self addSubview:_containerView];

    }
    return _containerView;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

    }
    return self;
}

+ (instancetype)dropdownMenu
{
    return [[self alloc] init];
}

- (void)setContent:(UIView *)content
{
    _content = content;

    content.x = 10;
    content.y = 15;

    self.containerView.width = CGRectGetMaxX(content.frame) + 10;
    self.containerView.height = CGRectGetMaxY(content.frame)  + 10;
    [self.containerView addSubview:content];

}

- (void)showFrom:(UIView *)from
{
    UIWindow *window = [[UIApplication sharedApplication].windows lastObject];

    self.frame = window.bounds;

    [window addSubview:self];

    //转换坐标系
    CGRect newFrame = [from.superview convertRect:from.frame toView:window];

    self.containerView.centerX = CGRectGetMidX(newFrame);
    self.containerView.y = CGRectGetMaxY(newFrame);

}

- (void)setContentController:(UIViewController *)contentController
{
    _contentController = contentController;

    self.content = contentController.view;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self dismissDropdownMenu];
}

- (void)dismissDropdownMenu
{
    [self removeFromSuperview];
}
@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="urn:metadata.tooling.soap.sforce.com" fqn="TEST_SObjectGateway">
    <apiVersion>48.0</apiVersion>
    <status>Active</status>
</ApexClass>


text:
package fr.jcgay.notification.notifier.growl;

import com.google.code.jgntp.Gntp;
import com.google.code.jgntp.GntpApplicationInfo;
import com.google.code.jgntp.GntpClient;
import com.google.code.jgntp.GntpNotification;
import com.google.code.jgntp.GntpNotificationInfo;
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;

import java.util.concurrent.TimeUnit;

import static com.google.code.jgntp.GntpNotification.Priority.HIGH;
import static com.google.code.jgntp.GntpNotification.Priority.HIGHEST;
import static com.google.code.jgntp.GntpNotification.Priority.NORMAL;
import static org.slf4j.LoggerFactory.getLogger;

public class GrowlNotifier implements DiscoverableNotifier {

    private static final Logger LOGGER = getLogger(GrowlNotifier.class);

    private final Application application;
    private final GrowlConfiguration configuration;
    private final GntpSlf4jListener logListener;

    private GntpNotificationInfo gNotification;
    private GntpClient gClient;

    public GrowlNotifier(Application application, GrowlConfiguration configuration, GntpSlf4jListener logListener) {
        LOGGER.debug("Configuring Growl for application {}: {}.", application, configuration);
        this.application = application;
        this.configuration = configuration;
        this.logListener = logListener;
    }

    @Override
    public Notifier init() {
        if (isClientRegistered()) {
            return this;
        }

        GntpApplicationInfo gApplication = Gntp.appInfo(application.name()).build();
        gNotification = Gntp.notificationInfo(gApplication, application.id())
            .icon(application.icon().toImage())
            .build();
        Gntp clientBuilder = Gntp.client(gApplication)
            .onPort(configuration.port())
            .forHost(configuration.host())
            .withoutRetry()
            .listener(logListener);
        if (configuration.password() != null) {
            clientBuilder.withPassword(configuration.password());
        }
        gClient = clientBuilder.build();
        gClient.register();
        try {
            gClient.waitRegistration(1L, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        return this;
    }

    @Override
    public void send(Notification notification) {
        if (isClientRegistered()) {
            GntpNotification success = Gntp.notification(gNotification, notification.title())
                    .text(notification.message())
                    .icon(notification.icon().toImage())
                    .priority(toPriority(notification.level()))
                    .build();
            try {
                gClient.notify(success, 5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

    @Override
    public void close() {
        if (isClientRegistered()) {
            try {
                // Seems that the client can be shutdown without having processed all the notifications...
                TimeUnit.SECONDS.sleep(1);
                gClient.shutdown(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }

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

    @Override
    public boolean tryInit() {
        init();
        boolean hasSucceeded = isClientRegistered();
        if (!hasSucceeded) {
            try {
                gClient.shutdown(1, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        return hasSucceeded;
    }

    private static GntpNotification.Priority toPriority(Notification.Level level) {
        switch (level) {
            case INFO:
                return NORMAL;
            case WARNING:
                return HIGH;
            case ERROR:
                return HIGHEST;
            default:
                return NORMAL;
        }
    }

    private boolean isClientRegistered() {
        return gClient != null && gClient.isRegistered();
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(application, configuration, logListener);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        final GrowlNotifier other = (GrowlNotifier) obj;
        return Objects.equal(this.application, other.application)
            && Objects.equal(this.configuration, other.configuration)
            && Objects.equal(this.logListener, other.logListener);
    }

    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
            .add("application", application)
            .add("configuration", configuration)
            .add("logListener", logListener)
            .toString();
    }
}


text:
#include "cinder/gl/Texture.h"
#include "cinder/ImageIo.h"
#include "cinder/app/App.h"

#include "FileWatcher/FileWatcher.h"

#include <fstream>
#include <sstream>
#include <cassert>
#include <boost/filesystem/path.hpp>
#include <unordered_map>

/// loaded images collection
std::unordered_map<std::string, ci::gl::TextureRef> gCache;

namespace {
    class TextureWatch : public FW::FileWatchListener
    {
        ci::app::App * mApp;
    public:
        TextureWatch(ci::app::App * app) : mApp(app)
        { }

        virtual void handleFileAction(FW::WatchID watchid,
                                      const FW::String& dir,
                                      const FW::String& filename,
                                      FW::Action action) override
        {
            if(action != FW::Actions::Modified)
            {
                return;
            }

            // filename is:
            //  - filename.ext on Windows
            //  - absolutepath/filename.ext on MacOSX
            const auto file = boost::filesystem::path(filename).filename().string();
            auto found = gCache.find(file);
            if(found != gCache.end())
            {
                const auto asset = mApp->loadAsset(file);
                auto newTexture = ci::Surface(ci::loadImage(asset));
                found->second->update(newTexture);
            }
        }
    };
}

ci::gl::TextureRef loadTexture(ci::app::App * app,
                               const std::string & imageName)
{

    auto found = gCache.find(imageName);
    if(found == gCache.end())
    {
        const auto asset = app->loadAsset(imageName);
        auto tex = ci::gl::Texture::create(loadImage(asset));
        tex->setMagFilter(GL_NEAREST);
        found = gCache.insert(std::make_pair(imageName, tex)).first;

        // setup watcher
        static FW::FileWatcher * watcher = NULL;
        if(!watcher)
        {
            watcher = new FW::FileWatcher;
            const auto assetPath = asset->getFilePath().parent_path();
            watcher->addWatch(assetPath.string(), new TextureWatch(app));
        }
    }
    return found->second;
}

static void loadCell(Board::Cell & cell, std::istream & stream)
{
    std::string seq;
    stream >> seq;

    int layerCount = 0;
    bool hasEvent =  false;
    std::transform(seq.begin(), seq.end(),
                   seq.begin(),
                   [&layerCount, &hasEvent](char c) -> char {
                     if(c==':') {
                       hasEvent = true;
                       c = ' ';
                     } else if(c==',') {
                       if(hasEvent)  throw BadFormatException();
                       ++layerCount;
                       c = ' ';
                     }
                     return c;
                   });

    int ground = 0;
    int layer = 0;
    int trigger = 0;
    std::istringstream parse(seq);

    parse >> ground;
    if(layerCount)
    {
        parse >> layer;
    }
    if(hasEvent)
    {
        parse >> trigger;
    }

    if(stream.fail())
    {
        throw BadFormatException();
    }

    cell.setGroundId(std::abs(ground), ground<0);
    if(layer>0)
    {
        cell.setLayerId(layer);
    }
    if(trigger>0)
    {
        cell.setTriggerId(trigger);
    }
}

static EventManager::Event loadEvent(std::istream & stream)
{
    std::string eventName;
    stream >> eventName;

    std::function<void (ci::app::App *, Level &)> event;
    if(eventName == "setTrigger")
    {
        int posX, posY, newTriggerId;
        stream >> posX >> posY >> newTriggerId;
        const auto position = ci::Vec2i(posX, posY);
        return [position, newTriggerId](ci::app::App *app, Level &level)
        {
            ev::setTrigger(level.board, position, newTriggerId);
        };
    }
    else if(eventName == "removeTrigger")
    {
        int posX, posY;
        stream >> posX >> posY;
        const auto position = ci::Vec2i(posX, posY);
        return [position](ci::app::App *app, Level &level)
        {
            ev::removeTrigger(level.board, position);
        };
    }
    else if(eventName == "setGround")
    {
        int posX, posY, tileId;
        stream >> posX >> posY >> tileId;
        const auto position = ci::Vec2i(posX, posY);
        return [position, tileId](ci::app::App *app, Level &level)
        {
            ev::setGround(level.board, position, std::abs(tileId), tileId<0);
        };
    }
    else if(eventName == "setLayer")
    {
        int posX, posY, tileId;
        stream >> posX >> posY >> tileId;
        const auto position = ci::Vec2i(posX, posY);
        return [position, tileId](ci::app::App *app, Level &level)
        {
            ev::setLayer(level.board, position, tileId);
        };
    }
    else if(eventName == "removeLayer")
    {
        int posX, posY;
        stream >> posX >> posY;
        const auto position = ci::Vec2i(posX, posY);
        return [position](ci::app::App *app, Level &level)
        {
            ev::removeLayer(level.board, position);
        };
    }
    else if(eventName == "setPlayerTiles")
    {
        int tileStill, tileUp, tileRight, tileDown, tileLeft;
        stream >> tileStill >> tileUp >> tileRight >> tileDown >> tileLeft;
        ci::Vec4i movingTiles(tileUp, tileRight, tileDown, tileLeft);
        return [tileStill, movingTiles](ci::app::App *app, Level &level)
        {
            ev::setPlayerTiles(level.player, tileStill, movingTiles);
        };
    }
    else if(eventName == "loadLevel")
    {
        std::string levelName;
        stream >> levelName;
        return [levelName](ci::app::App *app, Level &level)
        {
            level.destroy(app);
            try {
                Level tmp(ev::loadLevel(app, levelName));
                level.source = app->loadAsset(levelName);
                // this erases the event manager, which holds data of this
                // event: can't do much after that call.
                level = std::move(tmp);
            }
            catch (BadFormatException &) {
                // do nothing
            }
            level.prepare(app);
        };
    }
    else if(eventName == "displayImage")
    {
        std::string imageName;
        float duration;
        stream >> imageName >> duration;
        return [imageName, duration](ci::app::App *app, Level &level)
        {
            ev::displayImage(app, level, imageName, duration);
        };
    }
    else if(eventName == "displayPrompt")
    {
        std::string imageName;
        stream >> imageName;
        return [imageName](ci::app::App *app, Level &level)
        {
            ev::displayPrompt(app, level, imageName);
        };
    }
    else if(eventName == "fadeInColor")
    {
        float duration = 0.f;
        stream >> duration;
        return [duration](ci::app::App *app, Level & level)
        {
            ev::fadeInColor(app, level, ci::Color::black(), duration);
        };
    }
    else if(eventName == "fadeOutColor")
    {
        float duration = 0.f;
        stream >> duration;
        return [duration](ci::app::App *app, Level & level)
        {
            ev::fadeOutColor(app, level, ci::Color::black(), duration);
        };
    }
    else if(eventName == "playSound")
    {
        std::string filename;
        stream >> filename;
        bool loop = false;
        stream >> loop;
        return [filename, loop](ci::app::App * app, Level & level)
        {
            ev::playSound(app, level, filename, loop);
        };
    }
    else if(eventName == "stopSound")
    {
        std::string filename;
        stream >> filename;
        return [filename](ci::app::App *, Level & level)
        {
            ev::stopSound(level, filename);
        };
    }
    else if(eventName == "fadeInSound")
    {
        std::string filename;
        float duration = 0.f;
        stream >> filename >> duration;
        return [filename, duration](ci::app::App *app, Level & level)
        {
            ev::fadeInSound(app, level, filename, duration);
        };
    }
    else if(eventName == "fadeOutSound")
    {
        std::string filename;
        float duration = 0.f;
        stream >> filename >> duration;
        return [filename, duration](ci::app::App *app, Level & level)
        {
            ev::fadeOutSound(app, level, filename, duration);
        };
    }
    else if(eventName == "wait")
    {
        float duration;
        stream >> duration;
        return [duration](ci::app::App *app, Level &level)
        {
            ev::wait(app, level, duration, false);
        };
    }
    else if(eventName == "modalWait")
    {
        float duration;
        stream >> duration;
        return [duration](ci::app::App *app, Level &level)
        {
            ev::wait(app, level, duration, true);
        };
    }
    return EventManager::Event();
}

static bool isComment(const std::string & line)
{
    return line.empty() || line[0] == '\r'
                        || line[0] == '#';
}

Level loadFrom(ci::app::App * app, ci::DataSourceRef input)
{
    assert(input->isFilePath());
    std::ifstream stream(input->getFilePath().native());
    std::string section, line;

    // ground
    std::getline(stream, section, '[');
    std::getline(stream, section, ']');
    if(section != "ground")
    {
        throw BadFormatException();
    }

    int width, height, viewSize, tileSize;
    stream >> width >> height >> viewSize >> tileSize;
    if(stream.fail() || width < 1 || height < 1)
    {
        throw BadFormatException();
    }

    Board terrain(width, height);
    // vs2010 does not support range based for loop
    // for(auto & cell : terrain)
    for(auto it=terrain.begin(), end=terrain.end(); it != end; ++it)
    {
        loadCell(*it, stream);
    }

    // player
    Actor actor(app->timeline());
    std::getline(stream, section, '[');
    std::getline(stream, section, ']');
    if(section != "player")
    {
        throw BadFormatException();
    }
    int x, y;
    stream >> x >> y;
    actor.setStartPosition(ci::Vec2i(x, y));
    int tileStill, tileUp, tileRight, tileDown, tileLeft;
    stream >> tileStill >> tileUp >> tileRight >> tileDown >> tileLeft;
    actor.setTileId(tileStill, DIR_NONE);
    actor.setTileId(tileUp, DIR_UP);
    actor.setTileId(tileRight, DIR_RIGHT);
    actor.setTileId(tileDown, DIR_DOWN);
    actor.setTileId(tileLeft, DIR_LEFT);

    // tiles
    Drawer drawer(app->timeline(), viewSize, tileSize);
    std::getline(stream, section, '[');
    std::getline(stream, section);
    if(section.compare(0, 6, "tiles]") != 0)
    {
        throw BadFormatException();
    }
    int tileId, tileHeight, tileLine, beginIndex, endIndex;
    std::string imageName;
    while(stream.peek() != '[')
    {
        std::getline(stream, line);
        if(isComment(line))
        {
            continue;
        }

        std::istringstream s(line);
        s >> tileId >> imageName >> tileHeight >> tileLine >> beginIndex;
        if(s.fail())
        {
            throw BadFormatException();
        }
        auto tex = loadTexture(app, imageName);
        s >> endIndex;
        if(s.fail())
        {
            drawer.setTile(tileId, tex, tileHeight, tileLine, beginIndex);
        }
        else
        {
            float duration = 2.f * MOVE_DURATION;
            s >> duration;
            drawer.setTile(tileId, tex, tileHeight,
                           tileLine, beginIndex, endIndex, duration);
        }
    }

    // triggers
    std::getline(stream, section, '[');
    std::getline(stream, section);
    if(section.compare(0, 9, "triggers]") != 0)
    {
        throw BadFormatException();
    }
    EventManager eventManager;
    while(!stream.eof())
    {
        std::getline(stream, line);
        if(isComment(line))
        {
            continue;
        }

        std::istringstream s(line);

        int triggerId;
        s >> triggerId;
        if(s.fail())
        {
            continue;
        }

        // look for a parenthesis (event list)
        while(s.peek() == ' ')
        {
            s.get();
        }
        if(s.peek() == '(')
        {
            s.get();  // skip '('
            std::queue<EventManager::Event> events;
            while(1)
            {
                const auto event = loadEvent(s);
                if(event)
                {
                    events.push(event);
                }
                std::getline(stream, line);
                if(line[0] == ')' || stream.eof())
                {
                    break;
                }
                if(isComment(line))
                {
                    continue;
                }
                std::istringstream other(line);
                s.swap(other);
            }
            const auto serialEvent = [events](ci::app::App *app, Level &level)
            {
                ev::serial(app, level, events);
            };
            eventManager.setEvent(triggerId, serialEvent);
        }
        else
        {
            const auto event = loadEvent(s);
            if(event)
            {
                eventManager.setEvent(triggerId, event);
            }
        }
    }

    Level result(std::move(terrain),
                 std::move(actor),
                 std::move(drawer),
                 std::move(eventManager));
    return result;
}


text:
var fs = require("fs");
var path = require("path");

function relative(loc) {
  return path.join(__dirname, "..", loc);
}

fs.writeFileSync(relative("browser.js"), fs.readFileSync(relative("dist/polyfill.min.js")));


text:
using log4net;

namespace TeachersDiary.Clients.Mvc
{
    public class LoggingConfig
    {
        public static void RegisterLog4Net()
        {
            GlobalContext.Properties["ApplicationId"] = "TeachersDiary.Clietns.Mvc";
        }
    }
}


text:
%% Shows the surface normal map as an image
% Input: Matrix of normals
function showNormalMap(normals)
    imshow((normals+1) / 2);
end


text:
// --------- This code has been automatically generated !!! 2017-01-16T16:52:09.259Z
"use strict";
require("requirish")._(module);
/**
 * @module opcua.address_space.types
 */
var assert = require("better-assert");
var util = require("util");
var _  = require("underscore");
var makeNodeId = require("lib/datamodel/nodeid").makeNodeId;
var schema_helpers =  require("lib/misc/factories_schema_helpers");
var extract_all_fields                       = schema_helpers.extract_all_fields;
var resolve_schema_field_types               = schema_helpers.resolve_schema_field_types;
var initialize_field                         = schema_helpers.initialize_field;
var initialize_field_array                   = schema_helpers.initialize_field_array;
var check_options_correctness_against_schema = schema_helpers.check_options_correctness_against_schema;
var _defaultTypeMap = require("lib/misc/factories_builtin_types")._defaultTypeMap;
var ec = require("lib/misc/encode_decode");
var encodeArray = ec.encodeArray;
var decodeArray = ec.decodeArray;
var makeExpandedNodeId = ec.makeExpandedNodeId;
var generate_new_id = require("lib/misc/factories").generate_new_id;
var _enumerations = require("lib/misc/factories_enumerations")._private._enumerations;
var schema = require("../schemas/CloseSessionResponse_schema").CloseSessionResponse_Schema;
var ResponseHeader = require("./_auto_generated_ResponseHeader").ResponseHeader;
var BaseUAObject = require("lib/misc/factories_baseobject").BaseUAObject;

/**
 * Closes a session with the server.
 *
 * @class CloseSessionResponse
 * @constructor
 * @extends BaseUAObject
 * @param  options {Object}
 * @param  [options.responseHeader] {ResponseHeader} A standard header included in all responses returned by servers.
 */
function CloseSessionResponse(options)
{
    options = options || {};
    /* istanbul ignore next */
    if (schema_helpers.doDebug) { check_options_correctness_against_schema(this,schema,options); }
    var self = this;
    assert(this instanceof BaseUAObject); //  ' keyword "new" is required for constructor call')
    resolve_schema_field_types(schema);

    BaseUAObject.call(this,options);

    /**
      * A standard header included in all responses returned by servers.
      * @property responseHeader
      * @type {ResponseHeader}
      */
    self.responseHeader =  new ResponseHeader( options.responseHeader);

   // Object.preventExtensions(self);
}
util.inherits(CloseSessionResponse,BaseUAObject);
CloseSessionResponse.prototype.encodingDefaultBinary = makeExpandedNodeId(476,0);
CloseSessionResponse.prototype.encodingDefaultXml = makeExpandedNodeId(475,0);
CloseSessionResponse.prototype._schema = schema;

/**
 * encode the object into a binary stream
 * @method encode
 *
 * @param stream {BinaryStream}
 */
CloseSessionResponse.prototype.encode = function(stream,options) {
    // call base class implementation first
    BaseUAObject.prototype.encode.call(this,stream,options);
   this.responseHeader.encode(stream,options);
};
/**
 * decode the object from a binary stream
 * @method decode
 *
 * @param stream {BinaryStream}
 * @param [option] {object}
 */
CloseSessionResponse.prototype.decode = function(stream,options) {
    // call base class implementation first
    BaseUAObject.prototype.decode.call(this,stream,options);
    this.responseHeader.decode(stream,options);
};
CloseSessionResponse.possibleFields = [
  "responseHeader"
];

exports.CloseSessionResponse = CloseSessionResponse;
var register_class_definition = require("lib/misc/factories_factories").register_class_definition;
register_class_definition("CloseSessionResponse",CloseSessionResponse);


text:
export function shortMessage(message) {
  return message.split("\n")[0];
}

export function shortCommit(commitish) {
  // Does this look like a git sha?
  if (commitish && commitish.length === 40 && !commitish.match(/[^a-f0-9]/i)) {
    return commitish.substring(0, 7);
  }

  return commitish;
}


text:
import unittest

from merlin.tests.fixtures.testproject.forms import *
from merlin.wizards.utils import *

class UtilsTestCase(unittest.TestCase):
    def test_init_with_no_params(self):
        state = WizardState()

        self.assertIsNone(state.steps)
        self.assertIsNone(state.current_step)
        self.assertIsNone(state.form_data)

    def test_init_with_params(self):
        step1 = Step('step1', ContactDetailsForm)
        step2 = Step('step2', UserDetailsForm)

        state = WizardState(steps=[step1, step2], current_step=step1,
            form_data={})

        self.assertListEqual(state.steps, [step1, step2])
        self.assertEqual(state.current_step, step1)
        self.assertDictEqual(state.form_data, {})

    def test_step_object_methods(self):
        step1 = Step('step1', ContactDetailsForm)
        step1_copy = Step('step1', UserDetailsForm)
        step2 = Step('step2', UserDetailsForm)

        self.assertRaises(ValueError, Step, 'step1', Step)

        self.assertTrue(step1 == step1_copy)
        self.assertFalse(step1 == step2)
        self.assertFalse(step1 == 'step1')
        self.assertTrue(step1 != step2)
        self.assertFalse(step1 != step1_copy)

        self.assertEquals(str(step1), 'step1')
        self.assertEquals(unicode(step1), u'step1')

        self.assertEquals('Step: %s' % repr(step1), 'Step: step1')

    def test_wizard_expansion(self):
        state = WizardState()

        if not hasattr(state, 'test_param'):
            state.test_param = 'Test'

        self.assertEquals(state.test_param, 'Test')

        state.test_param = 'Test 2'

        self.assertEquals(state.test_param, 'Test 2')

        state = WizardState()
        state.another_param = 'Another Test'

        if not hasattr(state, 'another_param'):
            self.fail('We should have the param')

        else:
            self.assertEquals(state.another_param, 'Another Test')


text:
__A phone number processing library for Coldfusion__

Build on top of the [libphonenumber library](https://github.com/googlei18n/libphonenumber) from Google, this library allows parsing, formatting, storing and validating international phone numbers.

# How to install

### Lucee 4

Download the latest version [here](https://github.com/jbvanzuylen/cf-libphonenumber/releases/download/v1.0.2/cf-libphonenumber-lucee4-ext.zip)

__Install as an extension__

* Connect to the Web Administration
* Go to `Extension > Application`
* Scroll down to the bottom of the page
* Click on `Browse` button in the `Upload new extension` section
* Select the ZIP file you have downloaded above
* Hit the `Upload` button and follow the instructions

__Manual installation__

* Unzip the file you have downloaded above
* Copy the `.jar` files from the `lib` folder to the `WEB-INF\lucee\lib` directory in your web root
* Copy the `.cfm` files from the `functions` folder to the `WEB-INF\lucee\library\function` directory in your web root
* Copy the `.cfc` file from the `components` folder to the `WEB-INF\lucee\components\libphonenumber` directory in your web root


text:
#pragma once

#include <pdal/pdal_internal.hpp>

#include <algorithm>
#include <string>
#include <cassert>
#include <cctype>
#include <stdexcept>
#include <cmath>
#include <fstream>
#include <istream>
#include <limits>
#include <cstring>
#include <sstream>
#include <vector>
#include <map>

#include <boost/numeric/conversion/cast.hpp>

namespace pdal
{

namespace Utils
{
    template<typename T>
    char *as_buffer(T& data)
        { return static_cast<char*>(static_cast<void*>(&data)); }

    template<typename T>
    char *as_buffer(T* data)
        { return static_cast<char*>(static_cast<void*>(data)); }

    template <typename C, typename T>
    bool check_stream_state(std::basic_ios<C, T>& srtm)
    {
        // Test stream state bits
        if (srtm.eof())
            throw std::out_of_range("end of file encountered");
        else if (srtm.fail())
            throw std::runtime_error("non-fatal I/O error occured");
        else if (srtm.bad())
            throw std::runtime_error("fatal I/O error occured");
        return true;
    }

    PDAL_DLL void random_seed(unsigned int seed);
    PDAL_DLL double random(double minimum, double maximum);
    PDAL_DLL double uniform(const double& minimum=0.0f,
        const double& maximum=1.0f, uint32_t seed=0);
    PDAL_DLL double normal(const double& mean=0.0f, const double& sigma=1.0f,
        uint32_t seed=0);

    // compares two values to within a given tolerance
    // the value |tolerance| is compared to |actual - expected|
    template<class T>
    bool compare_approx(const T& actual, const T& expected, const T& tolerance)
    {
        double diff = std::abs((double)actual - (double)expected);
        return diff <= std::abs((double) tolerance);
    }

    // compares two values to within the datatype's epsilon
    template<class T>
    bool compare_distance(const T& actual, const T& expected)
    {
        const T epsilon = std::numeric_limits<T>::epsilon();
        return compare_approx<T>(actual, expected, epsilon);
    }

    // From http://stackoverflow.com/questions/485525/round-for-float-in-c
    inline double sround(double r)
        { return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5); }

    inline std::vector<uint8_t>hex_string_to_binary(
        std::string const& source)
    {
        // Stolen from http://stackoverflow.com/questions/7363774/  ...
        //    c-converting-binary-data-to-a-hex-string-and-back
        static int nibbles[] =
            { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0,
              10, 11, 12, 13, 14, 15 };
        std::vector<unsigned char> retval;
        for (auto it = source.begin(); it < source.end(); it += 2) {
            unsigned char v = 0;
            if (::isxdigit(*it))
                v = (unsigned char)nibbles[::toupper(*it) - '0'] << 4;
            if (it + 1 < source.end() && ::isxdigit(*(it + 1)))
                v += (unsigned char)nibbles[::toupper(*(it + 1)) - '0'];
            retval.push_back(v);
        }
        return retval;
    }

    inline void binary_to_hex_stream(unsigned char* source,
        std::ostream& destination, int start, int end )
    {
        static char syms[] = "0123456789ABCDEF";
        for (int i = start; i != end; i++)
            destination << syms[((source[i] >> 4) & 0xf)] <<
                           syms[source[i] & 0xf];
    }

    inline std::string binary_to_hex_string(
        const std::vector<unsigned char>& source)
    {
        static char syms[] = "0123456789ABCDEF";
        std::stringstream ss;
        for (std::vector<unsigned char>::const_iterator it = source.begin();
                it != source.end(); it++)
            ss << syms[((*it >> 4) & 0xf)] << syms[*it & 0xf];

        return ss.str();
    }

    inline std::string tolower(const std::string& s)
    {
        std::string out;
        for (size_t i = 0; i < s.size(); ++i)
            out += (char)std::tolower(s[i]);
        return out;
    }

    inline std::string toupper(const std::string& s)
    {
        std::string out;
        for (size_t i = 0; i < s.size(); ++i)
            out += (char)std::toupper(s[i]);
        return out;
    }

    inline bool iequals(const std::string& s, const std::string& s2)
    {
        if (s.length() != s2.length())
            return false;
        for (size_t i = 0; i < s.length(); ++i)
            if (std::toupper(s[i]) != std::toupper(s2[i]))
                return false;
        return true;
    }

    inline bool startsWith(const std::string& s, const std::string& prefix)
    {
        if (prefix.size() > s.size())
            return false;
        return (strncmp(prefix.data(), s.data(), prefix.size()) == 0);
    }

    inline int cksum(char *buf, size_t size)
    {
        int i = 0;
        while (size--)
            i += *buf++;
        return i;
    }

    template<typename Target, typename Source>
    Target saturation_cast(Source const& src)
    {
        try
        {
            return boost::numeric_cast<Target>(src);
        }
        catch (boost::numeric::negative_overflow const&)
        {
            return std::numeric_limits<Target>::min();
        }
        catch (boost::numeric::positive_overflow const&)
        {
            return std::numeric_limits<Target>::max();
        }
    }

    PDAL_DLL void *registerPlugin(void *stageFactoryPtr,
        std::string const& filename, std::string const& registerMethodName,
        std::string const& versionMethodName);

    PDAL_DLL char *getenv(const char *env);
    PDAL_DLL std::string getenv(std::string const& name);
    PDAL_DLL int putenv(const char *env);

    // aid to operator>> parsers
    PDAL_DLL void eatwhitespace(std::istream& s);
    PDAL_DLL void trimLeading(std::string& s);
    PDAL_DLL void trimTrailing(std::string& s);
    inline void trim(std::string& s)
    {
        trimLeading(s);
        trimTrailing(s);
    }
    // if char found, eats it and returns true; otherwise, don't eat it and
    // then return false
    PDAL_DLL bool eatcharacter(std::istream& s, char x);
    PDAL_DLL uint32_t getStreamPrecision(double scale);
    PDAL_DLL void *getDLLSymbol(std::string const& library,
        std::string const& name);
    PDAL_DLL std::string base64_encode(const unsigned char *buf, size_t size);
    inline std::string base64_encode(std::vector<uint8_t> const& bytes)
        { return base64_encode(bytes.data(), bytes.size()); }
    PDAL_DLL std::vector<uint8_t>
    base64_decode(std::string const& input);

    PDAL_DLL FILE* portable_popen(const std::string& command,
        const std::string& mode);
    PDAL_DLL int portable_pclose(FILE* fp);
    PDAL_DLL int run_shell_command(const std::string& cmd, std::string& output);
    PDAL_DLL std::string replaceAll(std::string result,
        const std::string& replaceWhat, const std::string& replaceWithWhat);
    PDAL_DLL StringList wordWrap(std::string const& inputString,
        unsigned int lineLength);
    PDAL_DLL std::string escapeJSON(const std::string &s);
    PDAL_DLL std::string demangle(const std::string& s);
    PDAL_DLL int screenWidth();
    PDAL_DLL std::string escapeNonprinting(const std::string& s);
    PDAL_DLL std::string hexDump(const char *buf, size_t count);

    /// Split a string into substrings.  Characters matching the predicate are
    ///   discarded.
    /// \param[in] s  String to split.
    /// \param[in] p  Predicate returns true if a char in a string is a split
    ///   location.
    /// \return  Vector of substrings.
    template<typename PREDICATE>
    PDAL_DLL std::vector<std::string> split(const std::string& s, PREDICATE p)
    {
        std::vector<std::string> result;

        if (s.empty())
            return result;

        auto it = s.begin();
        decltype(it) endIt;
        do
        {
            endIt = std::find_if(it, s.end(), p);
            result.push_back(std::string(it, endIt));
            it = endIt + 1;
        } while (endIt != s.end());
        return result;
    }

    /// Split a string into substrings.  Characters matching the predicate are
    ///   discarded, as are empty strings otherwise produced by split().
    /// \param[in] s  String to split.
    /// \param[in] p  Predicate returns true if a char in a string is a split
    ///   location.
    /// \return  Vector of substrings.
    template<typename PREDICATE>
    PDAL_DLL std::vector<std::string> split2(const std::string& s, PREDICATE p)
    {
        std::vector<std::string> result;

        if (s.empty())
            return result;

        auto it = s.begin();
        decltype(it) endIt;
        do
        {
            endIt = std::find_if(it, s.end(), p);
            if (it != endIt)
                result.push_back(std::string(it, endIt));
            it = endIt + 1;
        } while (endIt != s.end());
        return result;
    }

    inline PDAL_DLL std::vector<std::string>
    split(const std::string& s, char tChar)
    {
        auto pred = [tChar](char c){ return(c == tChar); };
        return split(s, pred);
    }

    inline PDAL_DLL std::vector<std::string>
    split2(const std::string& s, char tChar)
    {
        auto pred = [tChar](char c){ return(c == tChar); };
        return split2(s, pred);
    }

    template<typename T>
    std::string typeidName()
        { return Utils::demangle(typeid(T).name()); }

    template<typename KEY, typename VALUE>
    bool contains(const std::map<KEY, VALUE>& c, const KEY& v)
        { return c.find(v) != c.end(); }

    template<typename COLLECTION, typename VALUE>
    bool contains(const COLLECTION& c, const VALUE& v)
        { return (std::find(c.begin(), c.end(), v) != c.end()); }

    struct RedirectStream
    {
        std::ofstream *m_out;
        std::streambuf *m_buf;
    };

    /// Redirect a stream to some file, by default /dev/null.
    /// \param[in] out   Stream to redirect.
    /// \param[in] file  Name of file where stream should be redirected.
    /// \return  Context for stream restoration (see restore()).
    inline RedirectStream redirect(std::ostream& out,
        const std::string& file = "/dev/null")
    {
        RedirectStream redir;

        redir.m_out = new std::ofstream(file);
        redir.m_buf = out.rdbuf();
        out.rdbuf(redir.m_out->rdbuf());
        return redir;
    }

    /// Restore a stream redirected with redirect().
    /// \param[in] out  Stream to be restored.
    /// \param[in] redir RedirectStream returned from corresponding
    /// redirect() call.
    inline void restore(std::ostream& out, RedirectStream redir)
    {
        out.rdbuf(redir.m_buf);
        redir.m_out->close();
    }

    //ABELL - This is certainly not as efficient as boost::numeric_cast, but
    //  has the advantage of not requiring an exception to indicate an error.
    //  We should investigate incorporating a version of boost::numeric_cast
    //  that avoids the exception for an error.
    // Determine whether a value of a given input type may be safely
    // statically casted to the given output type without over/underflow.  If
    // the output type is integral, inRange() will determine whether the
    // rounded input value, rather than truncated, may be safely converted.
    template<typename T_OUT>
    bool inRange(double in)
    {
        if (std::is_integral<T_OUT>::value)
        {
            in = sround(in);
        }

        return std::is_same<double, T_OUT>::value ||
           (in >= static_cast<double>(std::numeric_limits<T_OUT>::lowest()) &&
            in <= static_cast<double>(std::numeric_limits<T_OUT>::max()));
    }

    template<typename T_IN, typename T_OUT>
    bool inRange(T_IN in)
    {
        return std::is_same<T_IN, T_OUT>::value ||
            inRange<T_OUT>(static_cast<double>(in));
    }

    template<typename T_IN, typename T_OUT>
    bool numericCast(T_IN in, T_OUT& out)
    {
        if (std::is_same<T_IN, T_OUT>::value)
        {
            out = in;
            return true;
        }
        if (std::is_integral<T_OUT>::value)
            in = sround(in);
        if ((std::is_same<T_OUT, double>::value) ||
            (in <= static_cast<double>(std::numeric_limits<T_OUT>::max()) &&
             in >= static_cast<double>(std::numeric_limits<T_OUT>::lowest())))
        {
            out = in;
            return true;
        }
        return false;
    }
} // namespace Utils

} // namespace pdal


text:
require "vault"
require "add_vault_tokens/version"

module AddVaultTokens
  class << self
    # Connect if we haven't already.
    def connect
      return if @connected
      @connected = true
      Vault.address = ENV.fetch('VAULT_ADDR')
      Vault.token = ENV.fetch('VAULT_MASTER_TOKEN')
    end

    # Does our vault have a policy for app_name?
    def have_policy_for?(app_name)
      @policies ||= Vault.sys.policies
      @policies.include?(app_name)
    end

    # Renew our master token.  We do this in case it's getting old, in
    # which case we don't want to risk our generated tokens expiring early.
    def renew_master_token
      # TODO: Use renew_self as soon as it's available, so we don't need
      # the power to renew any arbitrary token.
      Vault.auth_token.renew(ENV.fetch('VAULT_MASTER_TOKEN'))
    end

    # Create a token for app_name with the appropriate security policy.
    def create_token_for(app_name)
      timestamp = Time.now.utc.strftime("%Y%m%d%H%M%S")
      display = "#{app_name}_#{timestamp}"
      Vault.auth_token.create(name: app_name,
                              ttl: '720h',
                              display_name: display,
                              policies: [app_name])
    end

    # Given a parsed `docker-compose.yml` file, return a new version with
    # appropriate vault-related environment variables injected.  If
    # specified, append `prefix` to each service name in the file before
    # looking up a policy.
    def add_tokens_to_apps(parsed_yaml, quiet: false, prefix: "")
      env = ENV.fetch('VAULT_ENV', nil)
      result = Marshal.load(Marshal.dump(parsed_yaml))
      result.each do |app_name, info|
        full_app_name = prefix + app_name
        if have_policy_for?(full_app_name)
          STDERR.puts("Issuing token for #{full_app_name}") unless quiet
          token = create_token_for(full_app_name)
          info['environment'] ||= {}
          info['environment']['VAULT_ADDR'] =
            ENV.fetch('CONTAINER_VAULT_ADDR', ENV.fetch('VAULT_ADDR'))
          info['environment']['VAULT_ENV'] = env if env
          info['environment']['VAULT_TOKEN'] = token.auth.client_token
        else
          STDERR.puts("WARNING: No policy for #{full_app_name}, so no token issued")
        end
      end
      result
    end
  end
end


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>Counting Letters — CS42</title>

    <link rel="stylesheet" href="../_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootstrap-3.0.0/css/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="../_static/video.css" type="text/css" />
    <link rel="stylesheet" href="../_static/poll.css" type="text/css" />
    <link rel="stylesheet" href="../_static/tabbedstuff.css" type="text/css" />
    <link rel="stylesheet" href="../_static/css/pytutor.css" type="text/css" />
    <link rel="stylesheet" href="../_static/css/basic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/codemirror.css" type="text/css" />
    <link rel="stylesheet" href="../_static/activecode.css" type="text/css" />
    <link rel="stylesheet" href="../_static/parsons.css" type="text/css" />
    <link rel="stylesheet" href="../_static/lib/prettify.css" type="text/css" />
    <link rel="stylesheet" href="../_static/jquery-ui-1.10.3.custom.min.css" type="text/css" />
    <link rel="stylesheet" href="../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../_static/user-highlights.css" type="text/css" />
    <link rel="stylesheet" href="../_static/runestone-custom-sphinx-bootstrap.css" type="text/css" />

    <link rel="top" title="CS42" href="../index.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />

      <button type='button' class='navbar-toggle' data-toggle="collapse" data-target=".navbar-ex1-collapse">

      </button>

        CS42

Table of Contents

Book Index

Scratch ActiveCode

              <form class="navbar-search" style="margin:10px;" action="../search.html" method="get">

                  <input type="text" class="form-control" name="q" placeholder="Search this book" />

                    <button class="btn btn-primary" style="margin:0;" type="submit">

                    </button>

                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>

Instructor's Page

Edit Profile

Change Password

Register

Login

Navigation Help

Help for Instructors

About Runestone

Report A Problem

  Page

Counting Letters

Simple Solution: Counting a Single Letter

General Solution: Counting All Letters

Counting Letters¶

Simple Solution: Counting a Single Letter¶

We have previously discussed the solution to the problem of counting the number of times a specific letter appears
in a string.  In the case below, that specific letter is “a”.

<textarea cols="50" rows="12" id="chp12_single_code" class="active_code", prefixcode="undefined" lang="python">
def countA(text):
    count = 0
    for c in text:
        if c == 'a':
            count = count + 1
    return count

print(countA("banana"))
</textarea>

 (chp12_single)

<button class='btn btn-success' id="chp12_single_runb" onclick="runit('chp12_single',this, undefined);">Run</button>

<canvas id="chp12_single_canvas" class="ac-canvas" height="400" width="400" style="border-style: solid; display: none; text-align: center"></canvas>

Of course, we could also solve this problem by using the <tt class="docutils literal">count</tt> method provided for strings.

def countA(text):

    return text.count("a")

General Solution: Counting All Letters¶

Now we will generalize the counting problem and consider how to count the number of times each letter appears in
a given string.  In order to do this we need to realize that writing a function that returns a single integer will no
longer work.  Instead we will need to return some kind of collection that holds the counts for each character.

Although there may be many possible ways to do this, we suggest a dictionary where the keys of the dictionary will be
the letters in the string and the associated values for each key will be the number of times that the letter
appeared.

What about a letter that does not appear in the string?  It will never be placed in the dictionary.  By assumption, any
key that is not in the dictionary has a count of 0.

If we call the function <tt class="docutils literal">countAll</tt>, then a call to <tt class="docutils literal">countAll</tt> would return the dictionary.  For example,

print(countAll("banana"))

would return the dictionary

{"a":3, "b":1, "n":2}

Here is a start to the development of the function.

Define the function to require one parameter, the string.

Create an empty dictionary of counts.

Iterate through the characters of the string, one character at a time.

       readers online now |  | Back to top

        2014 CS 61A, Contact: Sumukh Sridhara.


text:
import logging

logger = logging.getLogger(__name__)
logger.warning('DEPRECATED: pyface.grid, use pyface.ui.wx.grid instead.')

from pyface.ui.wx.grid.edit_image_renderer import *


text:
package org.basex.query.up.expr;

import static org.basex.query.QueryError.*;
import static org.basex.query.QueryText.*;
import static org.basex.util.Token.*;

import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.expr.constr.*;
import org.basex.query.iter.*;
import org.basex.query.up.*;
import org.basex.query.up.primitives.node.*;
import org.basex.query.util.list.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.seq.*;
import org.basex.query.value.type.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.hash.*;

/**
 * Replace expression.
 *
 * @author BaseX Team 2005-20, BSD License
 * @author Lukas Kircher
 */
public final class Replace extends Update {
  /** 'Value of' flag. */
  private final boolean value;

  /**
   * Constructor.
   * @param sc static context
   * @param info input info
   * @param trg target expression
   * @param src source expression
   * @param value replace value of
   */
  public Replace(final StaticContext sc, final InputInfo info, final Expr trg, final Expr src,
      final boolean value) {
    super(sc, info, trg, src);
    this.value = value;
  }

  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    final Constr c = new Constr(info, sc).add(qc, exprs[1]);
    if(c.errAtt != null) throw UPNOATTRPER_X.get(info, c.errAtt);
    if(c.duplAtt != null) throw UPATTDUPL_X.get(info, c.duplAtt);

    final Iter iter = exprs[0].iter(qc);
    final Item item = iter.next();
    // check target constraints
    if(item == null) throw UPSEQEMP_X.get(info, Util.className(this));
    final Type type = item.type;
    if(!(item instanceof ANode) || type == NodeType.DOC) throw UPTRGNODE_X.get(info, item);
    final Item item2 = iter.next();
    if(item2 != null) throw UPTRGSINGLE_X.get(info, ValueBuilder.concat(item, item2, qc));
    final ANode targ = (ANode) item;
    final Updates updates = qc.updates();
    final DBNode dbn = updates.determineDataRef(targ, qc);

    // replace node
    final ANodeList aList = c.atts;
    ANodeList list = c.children;
    if(value) {
      // replace value of node
      final byte[] txt = list.size() < 1 ? aList.size() < 1 ? EMPTY :
        aList.get(0).string() : list.get(0).string();
      // check validity of future comments or PIs
      if(type == NodeType.COM) FComm.parse(txt, info);
      if(type == NodeType.PI) FPI.parse(txt, info);

      updates.add(new ReplaceValue(dbn.pre(), dbn.data(), info, txt), qc);
    } else {
      final ANode par = targ.parent();
      if(par == null) throw UPNOPAR_X.get(info, targ);
      if(type == NodeType.ATT) {
        // replace attribute node
        if(!list.isEmpty()) throw UPWRATTR_X.get(info, list.get(0));
        list = checkNS(aList, par);
      } else {
        // replace non-attribute node
        if(!aList.isEmpty()) throw UPWRELM_X.get(info, targ);
      }
      // conforms to specification: insertion sequence may be empty
      updates.add(new ReplaceNode(dbn.pre(), dbn.data(), info, list), qc);
    }
    return Empty.VALUE;
  }

  @Override
  public Expr copy(final CompileContext cc, final IntObjMap<Var> vm) {
    return new Replace(sc, info, exprs[0].copy(cc, vm), exprs[1].copy(cc, vm), value);
  }

  @Override
  public boolean equals(final Object obj) {
    return this == obj || obj instanceof Replace && value == ((Replace) obj).value &&
        super.equals(obj);
  }

  @Override
  public String toString() {
    return REPLACE + (value ? ' ' + VALUEE + ' ' + OF : "") +
      ' ' + NODE + ' ' + exprs[0] + ' ' + WITH + ' ' + exprs[1];
  }
}


text:
Adversaries may create a local account to maintain access to victim systems. Local accounts are those configured by an organization for use by users, remote support, services, or for administration on a single system or service. With a sufficient level of access, the net user /add command can be used to create a local account. On macOS systems the dscl -create command can be used to create a local account.

Such accounts may be used to establish secondary credentialed access that do not require persistent remote access tools to be deployed on the system.

## Atomic Tests

- [Atomic Test #1 - Create a user account on a Linux system](#atomic-test-1---create-a-user-account-on-a-linux-system)

- [Atomic Test #2 - Create a user account on a MacOS system](#atomic-test-2---create-a-user-account-on-a-macos-system)

- [Atomic Test #3 - Create a new user in a command prompt](#atomic-test-3---create-a-new-user-in-a-command-prompt)

- [Atomic Test #4 - Create a new user in PowerShell](#atomic-test-4---create-a-new-user-in-powershell)

- [Atomic Test #5 - Create a new user in Linux with `root` UID and GID.](#atomic-test-5---create-a-new-user-in-linux-with-root-uid-and-gid)

- [Atomic Test #6 - Create a new Windows admin user](#atomic-test-6---create-a-new-windows-admin-user)

## Atomic Test #1 - Create a user account on a Linux system
Create a user via useradd

**Supported Platforms:** Linux

**auto_generated_guid:** 40d8eabd-e394-46f6-8785-b9bfa1d011d2

#### Inputs:
| Name | Description | Type | Default Value |
|------|-------------|------|---------------|
| username | Username of the user to create | String | evil_user|

#### Attack Commands: Run with `bash`!  Elevation Required (e.g. root or admin)

```bash
useradd -M -N -r -s /bin/bash -c evil_account #{username}
```

#### Cleanup Commands:
```bash
userdel #{username}
```

## Atomic Test #2 - Create a user account on a MacOS system
Creates a user on a MacOS system with dscl

**Supported Platforms:** macOS

**auto_generated_guid:** 01993ba5-1da3-4e15-a719-b690d4f0f0b2

#### Inputs:
| Name | Description | Type | Default Value |
|------|-------------|------|---------------|
| username | Username of the user to create | String | evil_user|
| realname | 'realname' to record when creating the user | String | Evil Account|

#### Attack Commands: Run with `bash`!  Elevation Required (e.g. root or admin)

```bash
dscl . -create /Users/#{username}
dscl . -create /Users/#{username} UserShell /bin/zsh
dscl . -create /Users/#{username} RealName "#{realname}"
dscl . -create /Users/#{username} UniqueID "1010"
dscl . -create /Users/#{username} PrimaryGroupID 80
dscl . -create /Users/#{username} NFSHomeDirectory /Users/#{username}
```

#### Cleanup Commands:
```bash
dscl . -delete /Users/#{username}
```

## Atomic Test #3 - Create a new user in a command prompt
Creates a new user in a command prompt. Upon execution, "The command completed successfully." will be displayed. To verify the
new account, run "net user" in powershell or CMD and observe that there is a new user named "T1136.001_CMD"

**Supported Platforms:** Windows

**auto_generated_guid:** 6657864e-0323-4206-9344-ac9cd7265a4f

#### Inputs:
| Name | Description | Type | Default Value |
|------|-------------|------|---------------|
| username | Username of the user to create | String | T1136.001_CMD|
| password | Password of the user to create | String | T1136.001_CMD!|

#### Attack Commands: Run with `command_prompt`!  Elevation Required (e.g. root or admin)

```cmd
net user /add "#{username}" "#{password}"
```

#### Cleanup Commands:
```cmd
net user /del "#{username}" >nul 2>&1
```

## Atomic Test #4 - Create a new user in PowerShell
Creates a new user in PowerShell. Upon execution, details about the new account will be displayed in the powershell session. To verify the
new account, run "net user" in powershell or CMD and observe that there is a new user named "T1136.001_PowerShell"

**Supported Platforms:** Windows

**auto_generated_guid:** bc8be0ac-475c-4fbf-9b1d-9fffd77afbde

#### Inputs:
| Name | Description | Type | Default Value |
|------|-------------|------|---------------|
| username | Username of the user to create | String | T1136.001_PowerShell|

#### Attack Commands: Run with `powershell`!  Elevation Required (e.g. root or admin)

```powershell
New-LocalUser -Name "#{username}" -NoPassword
```

#### Cleanup Commands:
```powershell
Remove-LocalUser -Name "#{username}" -ErrorAction Ignore
```

## Atomic Test #5 - Create a new user in Linux with `root` UID and GID.
Creates a new user in Linux and adds the user to the `root` group. This technique was used by adversaries during the Butter attack campaign.

**Supported Platforms:** Linux

**auto_generated_guid:** a1040a30-d28b-4eda-bd99-bb2861a4616c

#### Inputs:
| Name | Description | Type | Default Value |
|------|-------------|------|---------------|
| username | Username of the user to create | String | butter|
| password | Password of the user to create | String | BetterWithButter|

#### Attack Commands: Run with `bash`!  Elevation Required (e.g. root or admin)

```bash
useradd -g 0 -M -d /root -s /bin/bash #{username}
if [ $(cat /etc/os-release | grep -i 'Name="ubuntu"') ]; then echo "#{username}:#{password}" | sudo chpasswd; else echo "#{password}" | passwd --stdin #{username}; fi;
```

#### Cleanup Commands:
```bash
userdel #{username}
```

## Atomic Test #6 - Create a new Windows admin user
Creates a new admin user in a command prompt.

**Supported Platforms:** Windows

**auto_generated_guid:** fda74566-a604-4581-a4cc-fbbe21d66559

#### Inputs:
| Name | Description | Type | Default Value |
|------|-------------|------|---------------|
| username | Username of the user to create | String | T1136.001_Admin|
| password | Password of the user to create | String | T1136_pass|

#### Attack Commands: Run with `command_prompt`!  Elevation Required (e.g. root or admin)

```cmd
net user /add "#{username}" "#{password}"
net localgroup administrators "#{username}" /add
```

#### Cleanup Commands:
```cmd
net user /del "#{username}" >nul 2>&1
```


text:
import * as types from '../constants/actionTypes';

export const togglePencilEraserMode = () => ({
  type: types.TOGGLE_PENCIL_ERASER_MODE
});


text:
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { DataTableModule } from 'angular-2-data-table';

import { ContentComponent } from './content.component';

@NgModule({
    imports: [RouterModule,BrowserModule, FormsModule, DataTableModule],
    declarations: [ContentComponent],
    exports: [ContentComponent]
})

export class ContentModule { }


text:
echo "build start."

target=$1
if [ $# -ne 1 ]; then
 target=viola
fi

echo target: ${target}

rm -rf build/${target}
cd cmake/${target}
cmake .
make
make test
cd ..

echo "build finished."


text:
require 'builder'

module RailsAdmin
  module Config
    module Fields
      module Types
        class Select < RailsAdmin::Config::Fields::Association
          RailsAdmin::Config::Fields::Types.register(self)
          include RailsAdmin::Engine.routes.url_helpers

          register_instance_option :view_helper do
            :select
          end

          register_instance_option :pretty_value do
            v = bindings[:view]
            o = bindings[:object]
            value = o.send(name)
            collection = association.klass.order(associated_model_config.object_label_method).all
            v.select_tag(name, v.options_from_collection_for_select(collection, :id, associated_model_config.object_label_method, value.try(:id)),
                         onchange: "var $t = $(this); $t.before('<i class=\"fa fa-spinner fa-spin\"></i>'); $.ajax({type: 'POST', url: '#{select_path(model_name: @abstract_model, id: o.id, method: association.foreign_key)}' + '&value=' + $t.val(), data: {ajax:true}, success: function(r) { $t.prev().remove(); $t.animate({ boxShadow: '0px 0px 10px #33CC33' }, 300).animate({ boxShadow: '' }, 700) }, error: function(e) { alert(e.responseText); }}); return false;"
                        )
          end

          register_instance_option :export_value do
            value.inspect
          end

          # Accessor for field's help text displayed below input field.
          register_instance_option :help do
            ""
          end
        end
      end
    end
  end
end


text:
package src;

import java.sql.*;
/*
 * Coded by             : Jaswant Singh [joney_000]
 * Lang   				: Java
 * Concept 				: Multi threading and Synchronization.
 * Release Date         : 31/march/2015
 * Email 				: jaswantsinghyadav007@gmail.com
 *
 */
public class ConnectionProvider
{
    public  Connection connection;

  /*
   *  DB         : ultamail
   *  table      : Emailqueue
   *  username   : root (Modify according your preferecnce)
   *  password   : root
   */

    public  void initialize(){
		/*
                 *   This Class Uses For Making A Connection using jdbc.Driver
                 *
                 *   Initialize function make new Connection to DataBase
                 */
                try
		{

			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ultramail","root","root");
		}
		catch(ClassNotFoundException ex)    // Exception Handling
		{
			System.out.println("Driver class Not Found :: Invalid driver");
		}catch(SQLException ex)              // Exception Handling
		{
			System.out.println("Invalid sql:"+ex.getMessage().toUpperCase());
		}catch(Exception ex)
		{                                   //if EXCEPTION not caught in upper cases [The Default Handler]
			System.out.println("error:"+ex.getMessage().toUpperCase());
		}
        }
    public  Connection getConnection(){

        initialize();

        return connection;
    }
}


text:
class LitBool: public Literal {
private:
   bool value;
public:
   LitBool(char*);
   void print(int);
   virtual void emit(CodeGenerator*,ProcedureNode*);
   virtual string stype();
   virtual void setTopLevel();
};

#endif