text:
FROM debian:stable

MAINTAINER Alex Witherspoon <alex@alexwitherspoon.com>

# Commands to Stage OS
RUN echo "Installing Base Utilties" && \
    bash -c "apt-get update -qq" && \
    bash -c "apt-get install -qq --force-yes python sudo curl cron git" && \
    bash -c "echo 'root:clean-slack' | chpasswd" && \
    bash -c "apt-get autoremove -qq --force-yes" && \
    bash -c "apt-get clean -qq --force-yes" && \
    echo "Base Utilities Installed" && \
    echo "...."

RUN echo "Installing clean-slack app" && \
    bash -c "git clone https://github.com/alexwitherspoon/clean-slack.git /opt/clean-slack" && \
    bash -c "crontab /opt/clean-slack/clean-slack.cron" && \
    bash -c "chmod +x /opt/clean-slack/clean-slack.py" && \
    bash -c "touch /var/log/clean-slack.log" && \
    echo "clean-slack app" && \
    echo "...."

# Commands to Run App
CMD bash -c "cron" && \
bash -c "sleep 1d"


text:
<?php

$_test_dir = realpath(dirname(__FILE__).'/..');
require_once($_test_dir.'/../lib/vendor/lime/lime.php');
require_once($_test_dir.'/../lib/util/sfToolkit.class.php');

define('DS', DIRECTORY_SEPARATOR);

class sf_test_project
{
  public $php_cli = null;
  public $tmp_dir = null;
  public $t = null;
  public $current_dir = null;

  public function initialize($t)
  {
    $this->t = $t;

    $this->tmp_dir = sys_get_temp_dir().DS.'sf_test_project';

    if (is_dir($this->tmp_dir))
    {
      $this->clearTmpDir();
      rmdir($this->tmp_dir);
    }

    mkdir($this->tmp_dir, 0777);

    $this->current_dir = getcwd();
    chdir($this->tmp_dir);

    $this->php_cli = sfToolkit::getPhpCli();
  }

  public function shutdown()
  {
    $this->clearTmpDir();
    rmdir($this->tmp_dir);
    chdir($this->current_dir);
  }

  protected function clearTmpDir()
  {
    require_once(dirname(__FILE__).'/../../lib/util/sfToolkit.class.php');
    sfToolkit::clearDirectory($this->tmp_dir);
  }

  public function execute_command($cmd, $awaited_return=0)
  {
    chdir($this->tmp_dir);
    $symfony = file_exists('symfony') ? 'symfony' : dirname(__FILE__).'/../../data/bin/symfony';

    ob_start();
    passthru(sprintf('%s "%s" %s 2>&1', $this->php_cli, $symfony, $cmd), $return);
    $content = ob_get_clean();
    $this->t->cmp_ok($return, '==', $awaited_return, sprintf('"symfony %s" returns awaited value (%d)', $cmd, $awaited_return));

    return $content;
  }

  public function get_fixture_content($file)
  {
    return str_replace("\r\n", "\n", file_get_contents(dirname(__FILE__).'/fixtures/'.$file));
  }
}

$plan = 39;
$t = new lime_test($plan);

if (!extension_loaded('SQLite') && !extension_loaded('pdo_SQLite'))
{
  $t->skip('You need SQLite to run these tests', $plan);

  return;
}

$c = new sf_test_project();
$c->initialize($t);

// generate:*
$content = $c->execute_command('generate:project myproject --orm=Propel');
$t->ok(file_exists($c->tmp_dir.DS.'symfony'), '"generate:project" installs the symfony CLI in root project directory');

$content = $c->execute_command('generate:app frontend');
$t->ok(is_dir($c->tmp_dir.DS.'apps'.DS.'frontend'), '"generate:app" creates a "frontend" directory under "apps" directory');
$t->like(file_get_contents($c->tmp_dir.'/apps/frontend/config/settings.yml'), '/escaping_strategy: +true/', '"generate:app" switches escaping_strategy "on" by default');
$t->like(file_get_contents($c->tmp_dir.'/apps/frontend/config/settings.yml'), '/csrf_secret: +\w+/', '"generate:app" generates a csrf_token by default');

$content = $c->execute_command('generate:app backend --escaping-strategy=false --csrf-secret=false');
$t->like(file_get_contents($c->tmp_dir.'/apps/backend/config/settings.yml'), '/escaping_strategy: +false/', '"generate:app" switches escaping_strategy "false"');
$t->like(file_get_contents($c->tmp_dir.'/apps/backend/config/settings.yml'), '/csrf_secret: +false/', '"generate:app" switches csrf_token to "false"');

// failing
$content = $c->execute_command('generate:module wrongapp foo', 1);

$content = $c->execute_command('generate:module frontend foo');
$t->ok(is_dir($c->tmp_dir.DS.'apps'.DS.'frontend'.DS.'modules'.DS.'foo'), '"generate:module" creates a "foo" directory under "modules" directory');

copy(dirname(__FILE__).'/fixtures/propel/schema.yml', $c->tmp_dir.DS.'config'.DS.'schema.yml');
copy(dirname(__FILE__).'/fixtures/propel/databases.yml', $c->tmp_dir.DS.'config'.DS.'databases.yml');
copy(dirname(__FILE__).'/fixtures/propel/propel.ini', $c->tmp_dir.DS.'config'.DS.'propel.ini');
copy(dirname(__FILE__).'/fixtures/factories.yml', $c->tmp_dir.DS.'apps'.DS.'frontend'.DS.'config'.DS.'factories.yml');

// update propel configuration paths
file_put_contents($c->tmp_dir.DS.'config'.DS.'propel.ini', str_replace('%SF_ROOT_DIR%', $c->tmp_dir, str_replace('%SF_DATA_DIR%', $c->tmp_dir.'/data', file_get_contents($c->tmp_dir.DS.'config'.DS.'propel.ini'))));

// propel:*
$content = $c->execute_command('propel:build-sql');
$t->ok(file_exists($c->tmp_dir.DS.'data'.DS.'sql'.DS.'lib.model.schema.sql'), '"propel:build-sql" creates a "schema.sql" file under "data/sql" directory');

$content = $c->execute_command('propel:build-model');
$t->ok(file_exists($c->tmp_dir.DS.'lib'.DS.'model'.DS.'Article.php'), '"propel:build-model" creates model classes under "lib/model" directory');

copy(dirname(__FILE__).'/fixtures/propel/Category.php', $c->tmp_dir.DS.'lib'.DS.'model'.DS.'Category.php');

$content = $c->execute_command('propel:build-form');
$t->ok(file_exists($c->tmp_dir.DS.'lib'.DS.'form'.DS.DS.'BaseFormPropel.class.php'), '"propel:build-form" creates form classes under "lib/form" directory');

$c->execute_command('propel:insert-sql --no-confirmation');
$t->ok(file_exists($c->tmp_dir.DS.'data'.DS.'database.sqlite'), '"propel:insert-sql" creates tables in the database');

$c->execute_command('propel:build-all --no-confirmation');

$content = $c->execute_command('propel:generate-module --generate-in-cache frontend articleInitCrud Article');
$t->ok(file_exists($c->tmp_dir.DS.'apps'.DS.'frontend'.DS.'modules'.DS.'articleInitCrud'.DS.'config'.DS.'generator.yml'), '"propel:generate-module" initializes a CRUD module');

$content = $c->execute_command('propel:generate-admin frontend Article --module=articleInitAdmin');
$t->ok(file_exists($c->tmp_dir.DS.'apps'.DS.'frontend'.DS.'modules'.DS.'articleInitAdmin'.DS.'config'.DS.'generator.yml'), '"propel:generate-admin" initializes an admin generator module');

// test:*
$content = $c->execute_command('test:functional frontend articleInitCrudActions');
$t->is($content, $c->get_fixture_content('test/functional/result.txt'), '"test:functional" can launch a particular functional test');

$content = $c->execute_command('test:functional frontend', 1);
$t->is($content, $c->get_fixture_content('test/functional/result-harness.txt'), '"test:functional" can launch all functional tests');

copy(dirname(__FILE__).'/fixtures/test/unit/testTest.php', $c->tmp_dir.DS.'test'.DS.'unit'.DS.'testTest.php');

$content = $c->execute_command('test:unit test');
$t->is($content, $c->get_fixture_content('/test/unit/result.txt'), '"test:unit" can launch a particular unit test');

$content = $c->execute_command('test:unit');
$t->is($content, $c->get_fixture_content('test/unit/result-harness.txt'), '"test:unit" can launch all unit tests');

$content = $c->execute_command('test:all', 1);
$t->is($content, $c->get_fixture_content('test/result-harness.txt'), '"test:all" launches all unit and functional tests');

$content = $c->execute_command('cache:clear');

// Test task autoloading
mkdir($c->tmp_dir.DS.'lib'.DS.'task');
copy(dirname(__FILE__).'/fixtures/task/aTask.class.php', $c->tmp_dir.DS.'lib'.DS.'task'.DS.'aTask.class.php');
copy(dirname(__FILE__).'/fixtures/task/zTask.class.php', $c->tmp_dir.DS.'lib'.DS.'task'.DS.'zTask.class.php');
mkdir($pluginDir = $c->tmp_dir.DS.'plugins'.DS.'myFooPlugin'.DS.'lib'.DS.'task', 0777, true);
copy(dirname(__FILE__).'/fixtures/task/myPluginTask.class.php', $pluginDir.DS.'myPluginTask.class.php');
file_put_contents(
  $projectConfigurationFile = $c->tmp_dir.DS.'config'.DS.'ProjectConfiguration.class.php',
  str_replace(
    '$this->enablePlugins(\'sfPropelPlugin\')',
    '$this->enablePlugins(array(\'myFooPlugin\', \'sfPropelPlugin\'))',
    file_get_contents($projectConfigurationFile)
  )
);

$c->execute_command('a:run');
$c->execute_command('z:run');
$c->execute_command('p:run');

$c->shutdown();

redpajama_set_name: RedPajamaGithub


text:
#ifndef __ESPCONN_H__
#define __ESPCONN_H__

#include "lwip/ip_addr.h"

typedef sint8 err_t;

typedef void *espconn_handle;
typedef void (* espconn_connect_callback)(void *arg);
typedef void (* espconn_reconnect_callback)(void *arg, sint8 err);

/* Definitions for error constants. */

#define ESPCONN_OK          0    /* No error, everything OK. */
#define ESPCONN_MEM        -1    /* Out of memory error.     */
#define ESPCONN_TIMEOUT    -3    /* Timeout.                 */
#define ESPCONN_RTE        -4    /* Routing problem.         */
#define ESPCONN_INPROGRESS  -5    /* Operation in progress    */
#define ESPCONN_MAXNUM		-7	 /* Total number exceeds the set maximum*/

#define ESPCONN_ABRT       -8    /* Connection aborted.      */
#define ESPCONN_RST        -9    /* Connection reset.        */
#define ESPCONN_CLSD       -10   /* Connection closed.       */
#define ESPCONN_CONN       -11   /* Not connected.           */

#define ESPCONN_ARG        -12   /* Illegal argument.        */
#define ESPCONN_IF		   -14	 /* UDP send error			 */
#define ESPCONN_ISCONN     -15   /* Already connected.       */

#define ESPCONN_HANDSHAKE  -28   /* ssl handshake failed	 */
#define ESPCONN_SSL_INVALID_DATA  -61   /* ssl application invalid	 */

/** Protocol family and type of the espconn */
enum espconn_type {
    ESPCONN_INVALID    = 0,
    /* ESPCONN_TCP Group */
    ESPCONN_TCP        = 0x10,
    /* ESPCONN_UDP Group */
    ESPCONN_UDP        = 0x20,
};

/** Current state of the espconn. Non-TCP espconn are always in state ESPCONN_NONE! */
enum espconn_state {
    ESPCONN_NONE,
    ESPCONN_WAIT,
    ESPCONN_LISTEN,
    ESPCONN_CONNECT,
    ESPCONN_WRITE,
    ESPCONN_READ,
    ESPCONN_CLOSE
};

typedef struct _esp_tcp {
    int remote_port;
    int local_port;
    uint8 local_ip[4];
    uint8 remote_ip[4];
    espconn_connect_callback connect_callback;
    espconn_reconnect_callback reconnect_callback;
    espconn_connect_callback disconnect_callback;
	espconn_connect_callback write_finish_fn;
} esp_tcp;

typedef struct _esp_udp {
    int remote_port;
    int local_port;
    uint8 local_ip[4];
	uint8 remote_ip[4];
} esp_udp;

typedef struct _remot_info{
	enum espconn_state state;
	int remote_port;
	uint8 remote_ip[4];
}remot_info;

/** A callback prototype to inform about events for a espconn */
typedef void (* espconn_recv_callback)(void *arg, char *pdata, unsigned short len);
typedef void (* espconn_sent_callback)(void *arg);

/** A espconn descriptor */
struct espconn {
    /** type of the espconn (TCP, UDP) */
    enum espconn_type type;
    /** current state of the espconn */
    enum espconn_state state;
    union {
        esp_tcp *tcp;
        esp_udp *udp;
    } proto;
    /** A callback function that is informed about events for this espconn */
    espconn_recv_callback recv_callback;
    espconn_sent_callback sent_callback;
    uint8 link_cnt;
    void *reverse;
};

enum espconn_option{
	ESPCONN_START = 0x00,
	ESPCONN_REUSEADDR = 0x01,
	ESPCONN_NODELAY = 0x02,
	ESPCONN_COPY = 0x04,
	ESPCONN_KEEPALIVE = 0x08,
	ESPCONN_END
};

enum espconn_level{
	ESPCONN_KEEPIDLE,
	ESPCONN_KEEPINTVL,
	ESPCONN_KEEPCNT
};

enum {
	ESPCONN_IDLE = 0,
	ESPCONN_CLIENT,
	ESPCONN_SERVER,
	ESPCONN_BOTH,
	ESPCONN_MAX
};

struct espconn_packet{
	uint16 sent_length;		/* sent length successful*/
	uint16 snd_buf_size;	/* Available buffer size for sending  */
	uint16 snd_queuelen;	/* Available buffer space for sending */
	uint16 total_queuelen;	/* total Available buffer space for sending */
	uint32 packseqno;		/* seqno to be sent */
	uint32 packseq_nxt;		/* seqno expected */
	uint32 packnum;
};

struct mdns_info {
	char *host_name;
	char *server_name;
	uint16 server_port;
	unsigned long ipAddr;
	char *txt_data[10];
};
/******************************************************************************
 * FunctionName : espconn_connect
 * Description  : The function given as the connect
 * Parameters   : espconn -- the espconn used to listen the connection
 * Returns      : none
*******************************************************************************/

sint8 espconn_connect(struct espconn *espconn);

/******************************************************************************
 * FunctionName : espconn_disconnect
 * Description  : disconnect with host
 * Parameters   : espconn -- the espconn used to disconnect the connection
 * Returns      : none
*******************************************************************************/

sint8 espconn_disconnect(struct espconn *espconn);

/******************************************************************************
 * FunctionName : espconn_delete
 * Description  : disconnect with host
 * Parameters   : espconn -- the espconn used to disconnect the connection
 * Returns      : none
*******************************************************************************/

sint8 espconn_delete(struct espconn *espconn);

/******************************************************************************
 * FunctionName : espconn_accept
 * Description  : The function given as the listen
 * Parameters   : espconn -- the espconn used to listen the connection
 * Returns      : none
*******************************************************************************/

sint8 espconn_accept(struct espconn *espconn);

/******************************************************************************
 * FunctionName : espconn_create
 * Description  : sent data for client or server
 * Parameters   : espconn -- espconn to the data transmission
 * Returns      : result
*******************************************************************************/

sint8 espconn_create(struct espconn *espconn);

/******************************************************************************
 * FunctionName : espconn_tcp_get_max_con
 * Description  : get the number of simulatenously active TCP connections
 * Parameters   : none
 * Returns      : none
*******************************************************************************/

uint8 espconn_tcp_get_max_con(void);

/******************************************************************************
 * FunctionName : espconn_tcp_set_max_con
 * Description  : set the number of simulatenously active TCP connections
 * Parameters   : num -- total number
 * Returns      : none
*******************************************************************************/

sint8 espconn_tcp_set_max_con(uint8 num);

/******************************************************************************
 * FunctionName : espconn_tcp_get_max_con_allow
 * Description  : get the count of simulatenously active connections on the server
 * Parameters   : espconn -- espconn to get the count
 * Returns      : result
*******************************************************************************/

sint8 espconn_tcp_get_max_con_allow(struct espconn *espconn);

/******************************************************************************
 * FunctionName : espconn_tcp_set_max_con_allow
 * Description  : set the count of simulatenously active connections on the server
 * Parameters   : espconn -- espconn to set the count
 * 				  num -- support the connection number
 * Returns      : result
*******************************************************************************/

sint8 espconn_tcp_set_max_con_allow(struct espconn *espconn, uint8 num);

/******************************************************************************
 * FunctionName : espconn_regist_time
 * Description  : used to specify the time that should be called when don't recv data
 * Parameters   : espconn -- the espconn used to the connection
 * 				  interval -- the timer when don't recv data
 * Returns      : none
*******************************************************************************/

sint8 espconn_regist_time(struct espconn *espconn, uint32 interval, uint8 type_flag);

/******************************************************************************
 * FunctionName : espconn_get_connection_info
 * Description  : used to specify the function that should be called when disconnect
 * Parameters   : espconn -- espconn to set the err callback
 *                discon_cb -- err callback function to call when err
 * Returns      : none
*******************************************************************************/

sint8 espconn_get_connection_info(struct espconn *pespconn, remot_info **pcon_info, uint8 typeflags);

/******************************************************************************
 * FunctionName : espconn_get_packet_info
 * Description  : get the packet info with host
 * Parameters   : espconn -- the espconn used to disconnect the connection
 * 				  infoarg -- the packet info
 * Returns      : the errur code
*******************************************************************************/

sint8 espconn_get_packet_info(struct espconn *espconn, struct espconn_packet* infoarg);

/******************************************************************************
 * FunctionName : espconn_regist_sentcb
 * Description  : Used to specify the function that should be called when data
 *                has been successfully delivered to the remote host.
 * Parameters   : struct espconn *espconn -- espconn to set the sent callback
 *                espconn_sent_callback sent_cb -- sent callback function to
 *                call for this espconn when data is successfully sent
 * Returns      : none
*******************************************************************************/

sint8 espconn_regist_sentcb(struct espconn *espconn, espconn_sent_callback sent_cb);

/******************************************************************************
 * FunctionName : espconn_regist_sentcb
 * Description  : Used to specify the function that should be called when data
 *                has been successfully delivered to the remote host.
 * Parameters   : espconn -- espconn to set the sent callback
 *                sent_cb -- sent callback function to call for this espconn
 *                when data is successfully sent
 * Returns      : none
*******************************************************************************/

sint8 espconn_regist_write_finish(struct espconn *espconn, espconn_connect_callback write_finish_fn);

/******************************************************************************
 * FunctionName : espconn_send
 * Description  : sent data for client or server
 * Parameters   : espconn -- espconn to set for client or server
 *                psent -- data to send
 *                length -- length of data to send
 * Returns      : none
*******************************************************************************/

sint8 espconn_send(struct espconn *espconn, uint8 *psent, uint16 length);

/******************************************************************************
 * FunctionName : espconn_sent
 * Description  : sent data for client or server
 * Parameters   : espconn -- espconn to set for client or server
 *                psent -- data to send
 *                length -- length of data to send
 * Returns      : none
*******************************************************************************/

sint8 espconn_sent(struct espconn *espconn, uint8 *psent, uint16 length);

/******************************************************************************
 * FunctionName : espconn_sendto
 * Description  : send data for UDP
 * Parameters   : espconn -- espconn to set for UDP
 *                psent -- data to send
 *                length -- length of data to send
 * Returns      : error
*******************************************************************************/

sint16 espconn_sendto(struct espconn *espconn, uint8 *psent, uint16 length);

/******************************************************************************
 * FunctionName : espconn_regist_connectcb
 * Description  : used to specify the function that should be called when
 *                connects to host.
 * Parameters   : espconn -- espconn to set the connect callback
 *                connect_cb -- connected callback function to call when connected
 * Returns      : none
*******************************************************************************/

sint8 espconn_regist_connectcb(struct espconn *espconn, espconn_connect_callback connect_cb);

/******************************************************************************
 * FunctionName : espconn_regist_recvcb
 * Description  : used to specify the function that should be called when recv
 *                data from host.
 * Parameters   : espconn -- espconn to set the recv callback
 *                recv_cb -- recv callback function to call when recv data
 * Returns      : none
*******************************************************************************/

sint8 espconn_regist_recvcb(struct espconn *espconn, espconn_recv_callback recv_cb);

/******************************************************************************
 * FunctionName : espconn_regist_reconcb
 * Description  : used to specify the function that should be called when connection
 *                because of err disconnect.
 * Parameters   : espconn -- espconn to set the err callback
 *                recon_cb -- err callback function to call when err
 * Returns      : none
*******************************************************************************/

sint8 espconn_regist_reconcb(struct espconn *espconn, espconn_reconnect_callback recon_cb);

/******************************************************************************
 * FunctionName : espconn_regist_disconcb
 * Description  : used to specify the function that should be called when disconnect
 * Parameters   : espconn -- espconn to set the err callback
 *                discon_cb -- err callback function to call when err
 * Returns      : none
*******************************************************************************/

sint8 espconn_regist_disconcb(struct espconn *espconn, espconn_connect_callback discon_cb);

/******************************************************************************
 * FunctionName : espconn_port
 * Description  : access port value for client so that we don't end up bouncing
 *                all connections at the same time .
 * Parameters   : none
 * Returns      : access port value
*******************************************************************************/

uint32 espconn_port(void);

/******************************************************************************
 * FunctionName : espconn_set_opt
 * Description  : access port value for client so that we don't end up bouncing
 *                all connections at the same time .
 * Parameters   : none
 * Returns      : access port value
*******************************************************************************/

sint8 espconn_set_opt(struct espconn *espconn, uint8 opt);

/******************************************************************************
 * FunctionName : espconn_clear_opt
 * Description  : clear the option for connections so that we don't end up bouncing
 *                all connections at the same time .
 * Parameters   : espconn -- the espconn used to set the connection
 * 				  opt -- the option for clear
 * Returns      : the result
*******************************************************************************/

sint8 espconn_clear_opt(struct espconn *espconn, uint8 opt);

/******************************************************************************
 * FunctionName : espconn_set_keepalive
 * Description  : access level value for connection so that we set the value for
 * 				  keep alive
 * Parameters   : espconn -- the espconn used to set the connection
 * 				  level -- the connection's level
 * 				  value -- the value of time(s)
 * Returns      : access port value
*******************************************************************************/

sint8 espconn_set_keepalive(struct espconn *espconn, uint8 level, void* optarg);

/******************************************************************************
 * FunctionName : espconn_get_keepalive
 * Description  : access level value for connection so that we get the value for
 * 				  keep alive
 * Parameters   : espconn -- the espconn used to get the connection
 * 				  level -- the connection's level
 * Returns      : access keep alive value
*******************************************************************************/

sint8 espconn_get_keepalive(struct espconn *espconn, uint8 level, void *optarg);

/******************************************************************************
 * TypedefName : dns_found_callback
 * Description : Callback which is invoked when a hostname is found.
 * Parameters  : name -- pointer to the name that was looked up.
 *               ipaddr -- pointer to an ip_addr_t containing the IP address of
 *               the hostname, or NULL if the name could not be found (or on any
 *               other error).
 *               callback_arg -- a user-specified callback argument passed to
 *               dns_gethostbyname
*******************************************************************************/

typedef void (*dns_found_callback)(const char *name, ip_addr_t *ipaddr, void *callback_arg);

/******************************************************************************
 * FunctionName : espconn_gethostbyname
 * Description  : Resolve a hostname (string) into an IP address.
 * Parameters   : pespconn -- espconn to resolve a hostname
 *                hostname -- the hostname that is to be queried
 *                addr -- pointer to a ip_addr_t where to store the address if
 *                it is already cached in the dns_table (only valid if ESPCONN_OK
 *                is returned!)
 *                found -- a callback function to be called on success, failure
 *                or timeout (only if ERR_INPROGRESS is returned!)
 * Returns      : err_t return code
 *                - ESPCONN_OK if hostname is a valid IP address string or the host
 *                  name is already in the local names table.
 *                - ESPCONN_INPROGRESS enqueue a request to be sent to the DNS server
 *                  for resolution if no errors are present.
 *                - ESPCONN_ARG: dns client not initialized or invalid hostname
*******************************************************************************/

err_t espconn_gethostbyname(struct espconn *pespconn, const char *hostname, ip_addr_t *addr, dns_found_callback found);

/******************************************************************************
 * FunctionName : espconn_encry_connect
 * Description  : The function given as connection
 * Parameters   : espconn -- the espconn used to connect with the host
 * Returns      : none
*******************************************************************************/

sint8 espconn_secure_connect(struct espconn *espconn);

/******************************************************************************
 * FunctionName : espconn_encry_disconnect
 * Description  : The function given as the disconnection
 * Parameters   : espconn -- the espconn used to disconnect with the host
 * Returns      : none
*******************************************************************************/

sint8 espconn_secure_disconnect(struct espconn *espconn);

/******************************************************************************
 * FunctionName : espconn_secure_send
 * Description  : sent data for client or server
 * Parameters   : espconn -- espconn to set for client or server
 * 				  psent -- data to send
 *                length -- length of data to send
 * Returns      : none
*******************************************************************************/

sint8 espconn_secure_send(struct espconn *espconn, uint8 *psent, uint16 length);

/******************************************************************************
 * FunctionName : espconn_encry_sent
 * Description  : sent data for client or server
 * Parameters   : espconn -- espconn to set for client or server
 * 				  psent -- data to send
 *                length -- length of data to send
 * Returns      : none
*******************************************************************************/

sint8 espconn_secure_sent(struct espconn *espconn, uint8 *psent, uint16 length);

/******************************************************************************
 * FunctionName : espconn_secure_set_size
 * Description  : set the buffer size for client or server
 * Parameters   : level -- set for client or server
 * 				  1: client,2:server,3:client and server
 * 				  size -- buffer size
 * Returns      : true or false
*******************************************************************************/

bool espconn_secure_set_size(uint8 level, uint16 size);

/******************************************************************************
 * FunctionName : espconn_secure_get_size
 * Description  : get buffer size for client or server
 * Parameters   : level -- set for client or server
 *				  1: client,2:server,3:client and server
 * Returns      : buffer size for client or server
*******************************************************************************/

sint16 espconn_secure_get_size(uint8 level);

/******************************************************************************
 * FunctionName : espconn_secure_ca_enable
 * Description  : enable the certificate authenticate and set the flash sector
 * 				  as client or server
 * Parameters   : level -- set for client or server
 *				  1: client,2:server,3:client and server
 *				  flash_sector -- flash sector for save certificate
 * Returns      : result true or false
*******************************************************************************/

bool espconn_secure_ca_enable(uint8 level, uint8 flash_sector );

/******************************************************************************
 * FunctionName : espconn_secure_ca_disable
 * Description  : disable the certificate authenticate  as client or server
 * Parameters   : level -- set for client or server
 *				  1: client,2:server,3:client and server
 * Returns      : result true or false
*******************************************************************************/

bool espconn_secure_ca_disable(uint8 level);

/******************************************************************************
 * FunctionName : espconn_secure_cert_req_enable
 * Description  : enable the client certificate authenticate and set the flash sector
 * 				  as client or server
 * Parameters   : level -- set for client or server
 *				  1: client,2:server,3:client and server
 *				  flash_sector -- flash sector for save certificate
 * Returns      : result true or false
*******************************************************************************/

bool espconn_secure_cert_req_enable(uint8 level, uint8 flash_sector );

/******************************************************************************
 * FunctionName : espconn_secure_ca_disable
 * Description  : disable the client certificate authenticate  as client or server
 * Parameters   : level -- set for client or server
 *				  1: client,2:server,3:client and server
 * Returns      : result true or false
*******************************************************************************/

bool espconn_secure_cert_req_disable(uint8 level);

/******************************************************************************
 * FunctionName : espconn_secure_set_default_certificate
 * Description  : Load the certificates in memory depending on compile-time
 * 				  and user options.
 * Parameters   : certificate -- Load the certificate
 *				  length -- Load the certificate length
 * Returns      : result true or false
*******************************************************************************/

bool espconn_secure_set_default_certificate(const uint8* certificate, uint16 length);

/******************************************************************************
 * FunctionName : espconn_secure_set_default_private_key
 * Description  : Load the key in memory depending on compile-time
 * 				  and user options.
 * Parameters   : private_key -- Load the key
 *				  length -- Load the key length
 * Returns      : result true or false
*******************************************************************************/

bool espconn_secure_set_default_private_key(const uint8* private_key, uint16 length);

/******************************************************************************
 * FunctionName : espconn_secure_accept
 * Description  : The function given as the listen
 * Parameters   : espconn -- the espconn used to listen the connection
 * Returns      : none
*******************************************************************************/

sint8 espconn_secure_accept(struct espconn *espconn);

/******************************************************************************
 * FunctionName : espconn_igmp_join
 * Description  : join a multicast group
 * Parameters   : host_ip -- the ip address of udp server
 * 				  multicast_ip -- multicast ip given by user
 * Returns      : none
*******************************************************************************/
sint8 espconn_igmp_join(ip_addr_t *host_ip, ip_addr_t *multicast_ip);

/******************************************************************************
 * FunctionName : espconn_igmp_leave
 * Description  : leave a multicast group
 * Parameters   : host_ip -- the ip address of udp server
 * 				  multicast_ip -- multicast ip given by user
 * Returns      : none
*******************************************************************************/
sint8 espconn_igmp_leave(ip_addr_t *host_ip, ip_addr_t *multicast_ip);

/******************************************************************************
 * FunctionName : espconn_recv_hold
 * Description  : hold tcp receive
 * Parameters   : espconn -- espconn to hold
 * Returns      : none
*******************************************************************************/
sint8 espconn_recv_hold(struct espconn *pespconn);

/******************************************************************************
 * FunctionName : espconn_recv_unhold
 * Description  : unhold tcp receive
 * Parameters   : espconn -- espconn to unhold
 * Returns      : none
*******************************************************************************/
sint8 espconn_recv_unhold(struct espconn *pespconn);

/******************************************************************************
 * FunctionName : espconn_mdns_init
 * Description  : register a device with mdns
 * Parameters   : ipAddr -- the ip address of device
 * 				  hostname -- the hostname of device
 * Returns      : none
*******************************************************************************/

void espconn_mdns_init(struct mdns_info *info);
/******************************************************************************
 * FunctionName : espconn_mdns_close
 * Description  : close a device with mdns
 * Parameters   : a
 * Returns      : none
*******************************************************************************/

void espconn_mdns_close(void);
/******************************************************************************
 * FunctionName : espconn_mdns_server_register
 * Description  : register a device with mdns
 * Parameters   : a
 * Returns      : none
*******************************************************************************/
void espconn_mdns_server_register(void);

/******************************************************************************
 * FunctionName : espconn_mdns_server_unregister
 * Description  : unregister a device with mdns
 * Parameters   : a
 * Returns      : none
*******************************************************************************/
void espconn_mdns_server_unregister(void);

/******************************************************************************
 * FunctionName : espconn_mdns_get_servername
 * Description  : get server name of device with mdns
 * Parameters   : a
 * Returns      : none
*******************************************************************************/

char* espconn_mdns_get_servername(void);
/******************************************************************************
 * FunctionName : espconn_mdns_set_servername
 * Description  : set server name of device with mdns
 * Parameters   : a
 * Returns      : none
*******************************************************************************/
void espconn_mdns_set_servername(const char *name);

/******************************************************************************
 * FunctionName : espconn_mdns_set_hostname
 * Description  : set host name of device with mdns
 * Parameters   : a
 * Returns      : none
*******************************************************************************/
void espconn_mdns_set_hostname(char *name);

/******************************************************************************
 * FunctionName : espconn_mdns_get_hostname
 * Description  : get host name of device with mdns
 * Parameters   : a
 * Returns      : none
*******************************************************************************/
char* espconn_mdns_get_hostname(void);

/******************************************************************************
 * FunctionName : espconn_mdns_disable
 * Description  : disable a device with mdns
 * Parameters   : a
 * Returns      : none
*******************************************************************************/
void espconn_mdns_disable(void);

/******************************************************************************
 * FunctionName : espconn_mdns_enable
 * Description  : disable a device with mdns
 * Parameters   : a
 * Returns      : none
*******************************************************************************/
void espconn_mdns_enable(void);
/******************************************************************************
 * FunctionName : espconn_dns_setserver
 * Description  : Initialize one of the DNS servers.
 * Parameters   : numdns -- the index of the DNS server to set must
 * 				  be < DNS_MAX_SERVERS = 2
 * 			      dnsserver -- IP address of the DNS server to set
 *  Returns     : none
*******************************************************************************/
void espconn_dns_setserver(char numdns, ip_addr_t *dnsserver);

#endif


text:
package co.jirm.core.sql;

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

import java.util.Calendar;

import org.junit.Before;
import org.junit.Test;

import co.jirm.core.util.ResourceUtils;

import com.google.common.base.Stopwatch;
import com.google.common.collect.ImmutableList;

public class PlainSqlTest {

	@Before
	public void setUp() throws Exception {}

	@Test
	public void testBasic() throws Exception {

		PlainSql sql = PlainSql.fromResource(getClass(), "select-test-bean.sql")
				.bind("name", "Adam")
				.bind("limit", 1);
		System.out.println(sql.toString());
		assertEquals(ImmutableList.<Object>of("Adam", 1), sql.mergedParameters());
		assertEquals(
				"SELECT * from test_bean\n" +
				"WHERE stringProp like ? \n" +
				"LIMIT ? ", sql.getSql());
	}

	@Test
	public void testNameParameters() throws Exception {
		PlainSql sql = PlainSql.parse(ResourceUtils.getClasspathResourceAsString(getClass(), "search-recruiting-name.sql"));
		sql.with("1", "2", "3", "4");
		assertEquals(ImmutableList.<Object>of("1","2","3", "4"), sql.mergedParameters());
		sql = PlainSql.parse(ResourceUtils.getClasspathResourceAsString(getClass(), "search-recruiting-name.sql"));
		sql
			.bind("now", "1")
			.bind("limit", "10")
			.bind("offset", "100");
		assertEquals(ImmutableList.<Object>of("1","1","10", "100"), sql.mergedParameters());
	}

	@Test
	public void testPerformance() throws Exception {
		Stopwatch sw = new Stopwatch().start();
		String sql = ResourceUtils.getClasspathResourceAsString(getClass(), "search-recruiting-name.sql");
		for (int i = 0; i < 300000; i++) {
			PlainSql.parse(sql);
		}

		assertTrue("Should be faster",sw.stop().elapsedMillis() < 5000);
	}

	@Test
	public void testPerformanceFromClasspath() throws Exception {
		Stopwatch sw = new Stopwatch().start();
		for (int i = 0; i < 300000; i++) {
			PlainSql.fromResource(getClass(), "search-recruiting-name.sql");
		}

		assertTrue("Should be faster",sw.stop().elapsedMillis() < 5000);
	}

	@Test
	public void testApos() throws Exception {
		PlainSql sql = PlainSql.fromResource(getClass(), "select-test-bean.sql");
		String result = sql
				.bind("name", "Adam")
				.bind("limit", 1).getSql();
		assertEquals(
				"SELECT * from test_bean\n" +
				"WHERE stringProp like ? \n" +
				"LIMIT ? ", result);
	}

	@Test
	public void testPartial() throws Exception {
		PlainSql sql = PlainSql.fromResource(getClass(), "partial-test.sql#other")
				.with(Calendar.getInstance())
				.with(1)
				.with(2);

		String actual = sql.getSql();
		assertEquals("SELECT\n" +
				"c.id, c.name, c.tags, c.category, c.description, \n" +
				"c.division, c.experience_level as \"experienceLevel\", \n" +
				"c.locations, c.type, c.parent_id as \"parentId\", \n" +
				"g.latitude as \"latitude\", g.longitude as \"longitude\"\n" +
				"FROM campaign c\n" +
				"LEFT OUTER JOIN \n" +
				"	(SELECT DISTINCT cg.campaign, geo.latitude, geo.longitude from campaign_geo cg\n" +
				"	INNER JOIN geo geo on geo.id = cg.geo \n" +
				"	WHERE geo.latitude IS NOT NULL AND geo.longitude IS NOT NULL AND cg.createts < ? \n" +
				"	) g on g.campaign = c.id\n" +
				"ORDER BY c.createts ASC, c.id, g.latitude, g.longitude\n" +
				"LIMIT ? \n" +
				"OFFSET ? ", actual);
	}
}


text:
package org.xbib.io.compress.xz;

/**
 * Thrown when the input data is not in the XZ format.
 */
public class XZFormatException extends XZIOException {
    private static final long serialVersionUID = 3L;

    /**
     * Creates a new exception with the default error detail message.
     */
    public XZFormatException() {
        super("Input is not in the XZ format");
    }
}


text:
layout: page
title: Martha Horne's 57th Birthday
date: 2016-05-24
author: Rebecca Meyers
tags: weekly links, java
status: published
summary: Aliquam tempus blandit nibh. Fusce vehicula nulla eget.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 05/12/2016
  endDate: 05/15/2016
  ctyhocn: EVVINHX
  groupCode: MH5B
published: true
---
Vivamus a quam neque. Suspendisse sed fringilla nibh. Pellentesque tempor tellus quis nisi pretium, sagittis congue felis venenatis. Maecenas ornare nibh a erat suscipit molestie. Nullam augue mauris, pretium sit amet molestie sit amet, fringilla sit amet elit. Aenean venenatis sapien ut nunc varius, a condimentum diam lacinia. Etiam in tellus sapien. Suspendisse potenti. In porta dui a tincidunt aliquam. Vestibulum et enim dapibus, vestibulum felis sed, lacinia ante.
Pellentesque tincidunt augue non laoreet sollicitudin. Pellentesque eleifend congue dolor nec porta. Aenean in dui vehicula, rutrum felis in, viverra metus. Donec laoreet augue quis nulla condimentum sagittis. Nunc at mattis justo. Proin euismod risus pretium ipsum pulvinar, euismod ornare dolor pellentesque. Sed volutpat bibendum lectus et cursus. Donec vehicula auctor ex nec tincidunt. Ut at magna mi. Aenean dignissim augue hendrerit dictum ullamcorper. Aenean vel dolor ipsum. Lorem ipsum dolor sit amet, consectetur adipiscing elit.

* In lacinia tellus vitae lorem mollis, id sodales sem laoreet.

Etiam eu arcu sem. Etiam urna risus, mattis non condimentum sit amet, posuere non dui. In id justo viverra, rutrum purus nec, faucibus dui. Proin placerat dolor est, eget vestibulum nulla feugiat a. Sed dapibus fermentum cursus. Donec pharetra turpis sed sapien auctor, eu facilisis mi venenatis. Duis id suscipit nunc. Pellentesque a ante facilisis, mollis turpis non, fermentum ante.


text:
'use strict';

angular.module('homeon')
  .service('HttpRequestSrv', function($http, ngNotify){
    return function(url, method, data, callback){
      var requestParams = {
        method: method,
        url: url,
        headers: {'Content-type': 'application/json'},
        data: data
      };
      $http(requestParams).then(
        function successCallback(response){
          callback && callback(response.data);
        });
    };
  })
  .service('RestSrv', function(HttpRequestSrv){
    var restFactory = {};

    // Find all data.
    restFactory.find = function(url, callback){
      HttpRequestSrv(url, 'GET', {}, callback);
    };

    // Aadd a new data.
    restFactory.add = function(url, data, callback){
      HttpRequestSrv(url, 'POST', data, callback);
    };

    // Edit a data.
    restFactory.edit = function(url, data, callback){
      HttpRequestSrv(url, 'PUT', data, callback);
    };

    // Delete a data.
    restFactory.delete = function(url, data, callback){
      HttpRequestSrv(url, 'DELETE', data, callback);
    };
    return restFactory;
  });


text:
<?php
$this->breadcrumbs = array(
    'Users' => array('index'),
    'Manage',
);
?>

Manage Users

        <a href="<?php echo $this->createUrl('user/create/') ?>" class="btn <?php echo $this->add_button; ?>">Add User

        <div class="portlet box <?php echo $this->portlet_color ?>">

                    Users

                    <?php
                    $gridColumns = array(
                        // ['name' => 'first_name', 'header' => 'First Name', 'htmlOptions' => []],
                        // ['name' => 'last_name', 'header' => 'Last Name', 'htmlOptions' => []],
                        ['name' => 'full_name', 'header' => 'Name', 'htmlOptions' => []],
                        ['name' => 'username', 'header' => 'Username', 'htmlOptions' => []],
                        ['name' => 'email', 'header' => 'Email', 'htmlOptions' => []],
                        ['name' => 'email', 'header' => 'Email', 'htmlOptions' => []],
                        /*
                          ['name' => 'id', 'header' => 'Id', 'htmlOptions' => []],
                          ['name' => 'password', 'header' => 'Password', 'htmlOptions' => []],
                          ['name' => 'user_type_id', 'header' => 'User Type Id', 'htmlOptions' => []],
                          ['name' => 'birthday','header' => 'Birthday', 'htmlOptions' => []],
                          ['name' => 'gender','header' => 'Gender', 'htmlOptions' => []],
                          ['name' => 'language_name', 'value' => '$data->language->name','header' => 'Language', 'htmlOptions' => []],
                          ['name' => 'profile_image','header' => 'Profile Image', 'htmlOptions' => []],
                          ['name' => 'sound_effect','header' => 'Sound Effect', 'htmlOptions' => []],
                          ['name' => 'microphone','header' => 'Microphone', 'htmlOptions' => []],
                          ['name' => 'speaker','header' => 'Speaker', 'htmlOptions' => []],
                          ['name' => 'membership_id','header' => 'Membership Id', 'htmlOptions' => []],
                          ['name' => 'facebook_url','header' => 'Facebook Url', 'htmlOptions' => []],
                          ['name' => 'twitter_url','header' => 'Twitter Url', 'htmlOptions' => []],
                          ['name' => 'gplus_url','header' => 'Gplus Url', 'htmlOptions' => []],
                          ['name' => 'activation_code','header' => 'Activation Code', 'htmlOptions' => []],
                          ['name' => 'reset_key','header' => 'Reset Key', 'htmlOptions' => []],
                          ['name' => 'status',type=>'raw','value'=>'$data->statusTag()', 'header' => 'Status', 'htmlOptions' => []],'sortable' => false,
                          ['name' => 'create_at','header' => 'Created At', 'htmlOptions' => []],
                          ['name' => 'update_at','header' => 'Updated At', 'htmlOptions' => []],
                         */
                        array(
                            'htmlOptions' => array('nowrap' => 'nowrap'),
                            'class' => 'booster.widgets.TbButtonColumn',
                            'template' => '{update} {delete}', //removed {view}
                        //'viewButtonUrl' => null,//explicitly define url
                        //'updateButtonUrl' => null,
                        //'deleteButtonUrl' => null,
                        /*    'buttons' => array
                          (
                          'delete' => array
                          (
                          //  'url' => 'Yii::app()->createUrl("admin/user")',
                          'click' => 'js:function myfunction(){
                          confirm("Are you sure you want to delete this user?");
                          }',
                          ),
                          ) */
                        ),
                    );

                    $dataProvider = new CActiveDataProvider('User', array(
                        'criteria' => array(
                            'order' => 'create_at DESC',
                        ),
                        'pagination' => array(
                            'pageSize' => 5,
                            'pageVar' => 'custom-page-selector', //page selector
                        ),
                    ));
                    $this->widget('booster.widgets.TbGridView', array(
                        'id' => 'user-grid',
                        //    'dataProvider' => $model->search(),
                        'dataProvider' => $dataProvider,
                        'selectableRows' => 1,
                        'template' => "{summary}\n{pager}
\n{items}\n{pager}",
                        'updateSelector' => 'custom-page-selector', //update selector
                        'template' => "{items}",
                        'enableSorting' => false,
                        //'filter'=>$model,
                        'columns' => $gridColumns,
                    ));
                    ?>


text:
import { PLUS_OPERATOR, MINUS_OPERATOR, MULTIPLY_OPERATOR,
         DIVIDE_OPERATOR, EQUALS_OPERATOR } from '../constants/calculation';
import { getCalculationExpressionOperationItem } from './calculationExpressionItemGenerator';

export function generateOperations() {
    let result = [];
    [PLUS_OPERATOR, MINUS_OPERATOR, MULTIPLY_OPERATOR, DIVIDE_OPERATOR, EQUALS_OPERATOR].forEach(function(operation) {
        result[operation] = getCalculationExpressionOperationItem(operation);
    });

    return result;
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
namespace EasyDo.Configuration
{
    public class EasyDoConfiguration
    {
        //配置数据库连接
        internal List<DataBaseConfiguration> DataBaseConfigurations { get; set; }
        /// <summary>
        /// redids 配置信息
        /// </summary>
        internal List<RedisConfiguration> RedisConfigurations { get; set; }
        /// <summary>
        /// 随机数获取
        /// </summary>
        internal Random Rd = new Random();

        internal EasyDoConfiguration()
        {
            DataBaseConfigurations = new List<DataBaseConfiguration>();
            RedisConfigurations = new List<RedisConfiguration>();
        }
        /// <summary>
        /// 是否使用Redis
        /// </summary>
        public bool EnableRedis { get; internal set; }

        /// <summary>
        /// 根据数据库名称 获取数据库连接
        /// </summary>
        /// <param name="databaseName">数据库名称</param>
        /// <returns>数据库连接字符串</returns>
        public string MasterDataBaseConnectionString(string databaseName)
        {
            var dataBaseConfiguration = DataBaseConfigurations.Find(m => m.DataBaseName == databaseName);
            if (dataBaseConfiguration == null)
            {
                throw new ArgumentException(string.Format("数据库:{0} 主库连接未配置!", databaseName));
            }
            return dataBaseConfiguration.MasterDataBaseConnectionString;
        }

        /// <summary>
        /// 根据数据库名称 获取从库数据库连接
        /// </summary>
        /// <param name="databaseName">数据库名称</param>
        /// <returns>数据库连接字符串</returns>
        public string SlaveDataBaseConnectionString(string databaseName)
        {
            var dataBaseConfiguration = DataBaseConfigurations.Find(m => m.DataBaseName == databaseName);
            if (dataBaseConfiguration == null)
            {
                throw new ArgumentException(string.Format("数据库:{0} 从库连接未配置!", databaseName));
            }

            //随机一个从库连接
            var index = Rd.Next(0, dataBaseConfiguration.SlaveDataBaseConnectionStrings.Count-1);
            return dataBaseConfiguration.SlaveDataBaseConnectionStrings[index] ;
        }

        /// <summary>
        ///  是否启用从库(读从库)
        /// </summary>
        /// <param name="databaseName">数据库名称</param>
        /// <returns></returns>
        public bool EnableSecondaryDb(string databaseName)
        {
            var dataBaseConfiguration = DataBaseConfigurations.Find(m => m.DataBaseName == databaseName);
            if (dataBaseConfiguration == null)
            {
                throw new ArgumentException(string.Format("数据库:{0} 未配置!查找不到数据库信息", databaseName));
            }
            return dataBaseConfiguration.EnableSecondaryDb;
        }

        /// <summary>
        /// 是否启用删除
        /// </summary>
        /// <param name="databaseName"></param>
        /// <returns></returns>
        public bool EnableSoftDelete(string databaseName)
        {
            var dataBaseConfiguration = DataBaseConfigurations.Find(m => m.DataBaseName == databaseName);
            if (dataBaseConfiguration == null)
            {
                throw new ArgumentException(string.Format("数据库:{0} 未配置!查找不到数据库信息", databaseName));
            }
            return !dataBaseConfiguration.DisableSoftDelete;
        }

        /// <summary>
        /// redis 配置信息
        /// </summary>
        /// <returns></returns>
        public string[] RedisConnectionStrings()
        {
            if (!RedisConfigurations.Any())
            {
                throw new ArgumentException("至少需要配置一个Reids连接信息!");
            }
            return RedisConfigurations.Select(m => m.Host + ":" + m.Port).ToArray();
        }
    }
}


text:
INITDS MACRO
 MOV AX,@DATA ;Initialization of data segment
 MOV DS,AX ;(to access data)
 ENDM
INIT8255 MACRO
 MOV AL,CW ;Initialization of 8255 using control word
 MOV DX,CR ; by passing 82h to control reg.
 OUT DX,AL ;(to make port A as output)
ENDM

OUTPA MACRO ; one is enough
 MOV DX,PA
 OUT DX,AL
ENDM

EXIT MACRO
 MOV AH,4CH ;Terminating the program
 INT 21H
ENDM

.MODEL SMALL
.STACK
.DATA
 PA EQU 1190H ;one is enough
 CR EQU 1193H
 CW DB 82H
 TABLE DB 80H,96H,0ABH,0C0H,0D2H,0E2H,0EEH,0F8H,0FEH,0FFH ;+ve 1st half
 DB 0FEH,0F8H,0EEH,0E2H,0D2H,0C0H,0ABH,96H,80H ;+ve 2nd half
 DB 96H,0ABH,0C0H,0D2H,0E2H,0EEH,0F8H,0FEH,0FFH ;+ve 1st half
 DB 0FEH,0F8H,0EEH,0E2H,0D2H,0C0H,0ABH,96H,80H ;+ve 2nd half
 MSG DB 10,13,"PRESS ANY KEY TO EXIT $"

.CODE
 INITDS
 INIT8255
 LEA DX,MSG
 MOV AH,9
 INT 21H ; or MOV CX,25H
START: MOV CX,37 ;count value is taken 37 bcz the table contains 37 values
 LEA SI,TABLE ; table address is loaded to SI
BACK: MOV AL,[SI] ; the contents of SI is moved to AL i.e. single value of table is moved
 OUTPA ;moved value is sent to hardware module through PORT A
 CALL DELAY
 INC SI ; SI is pointed to the next value of table
 LOOP BACK ; loop repeats until all the contents of table is moved (till CX becomes 0)
 MOV AH,1
 INT 16H ; checks if any key is pressed in keyboard. If you
 JZ START haven't, then go to START
 EXIT ; if you press any key, just call exit macro
DELAY PROC
 MOV BX,0FFFH ; NOTE: single loop delay is enough
L2: DEC BX
 JNZ L2
 RET
DELAY ENDP
END


text:
angular directive for SoundCloud lyrics player, inspired by Deezer

Player originally developed by [jxnblk] (https://github.com/jxnblk/plangular)

[Demo] (http://armiasaied.github.io/ng-lyrics-player/)


text:
"""Install the package!"""

from __future__ import absolute_import

import setuptools

setuptools.setup(
    name='grit',
    version='0',
    entry_points={
        'console_scripts': ['grit = grit.grit_runner:Main'],
    },
    packages=setuptools.find_packages(),
    install_requires=[
        'six >= 1.10',
    ],
    author='The Chromium Authors',
    author_email='chromium-dev@chromium.org',
    description='Google Resource and Internationalization Tool for managing '
                'translations & resource files',
    license='BSD-3',
    url='https://chromium.googlesource.com/chromium/src/tools/grit/',
    classifiers=[
        'Development Status :: 6 - Mature',
        'Environment :: Console',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: MacOS',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: POSIX :: Linux',
        'Programming Language :: Python',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
        'Programming Language :: Python :: 3.9',
        'Topic :: Utilities',
    ],
)


text:
kWelderCost = 10							-- Increased from 3
kShotgunCost = 15							-- Decreased from 20
kHeavyMachineGunCost = 20					-- Default is 20
kGrenadeLauncherCost = 20					-- Default is 20
kFlamethrowerCost = 10						-- Decreased from 20
kDualExosuitCost = 25						-- Decreased from 55
kDualRailgunExosuitCost = 25				-- Decreased from 55
kJetpackCost = 10							-- Decreased from 15

-- Weights
kPistolWeight = 0.05
kRifleWeight = 0.175
kGrenadeLauncherWeight = 0.3
kFlamethrowerWeight = 0.125
kShotgunWeight = 0.225
kHeavyMachineGunWeight = 0.27
--kHeavyMachineGunUpgradedWeight = 0.25
kHandGrenadeWeight = 0.05
kLayMineWeight = 0.075
kWelderWeight = 0.05
kClawWeight = 0.01							-- Default is 0.01
kMinigunWeight = 0.06						-- Default is 0.06
kRailgunWeight = 0.045						-- Default is 0.045

kClusterGrenadeCost = 10					-- Increased from 2
kGasGrenadeCost = 10						-- Increased from 2
kPulseGrenadeCost = 10						-- Increased from 2
kMineCost = 5								-- Decreased from 10
kMarineReBuyGrenadesCost = 2

-- SHOTGUN
kShotgunBulletsPerShot = 10					-- Decreased from 17
kShotgunSpreadDistance = 4					-- Decreased from 8.5 (See other adjustments in Shotgun.lua)
kShotgunDamage = 17							-- Increased from 10
kShotgunMaxRange = 16						-- Added max range (Damage drops to 1)
kShotgunDropOffStartRange = 6				-- Min range where damage falloff begins
kShotgunBaseROF	= 1.04						-- Increased SG base rate of fire
kShotgunUpgradedROF	= 1.16					-- Increased SG base rate of fire from upgrades
kShotgunFireRate = 0.70						-- To prevent fire rate cap from triggering
kShotgunClipSize = 6						-- Default is 6
kShotgunUpgradedReloadSpeed = 1.5

-- MG
kHeavyMachineGunDamage = 13					-- Default is 9 (*)
kHeavyMachineGunClipSize = 100				-- Default is 125
kHeavyMachineGunUpgradedClipSize = 125
kHeavyMachineGunSpread = Math.Radians(3.1)	-- Default is 4
kHeavyMachineGunReloadSpeed = 1				-- Dont ask.....
kHeavyMachineGunUpgReloadSpeed = 1.5
kHeavyMachineGunDamageType = kDamageType.HalfStructural

-- PISTOL
kPistolDamage = 20							-- Decreased from 25
kPistolDamageType = kDamageType.Normal		-- Default is Light

-- FLAMETHROWER
kFlamethrowerDamage = 18					-- Increased from 12
kFlamethrowerDamageRadius = 0.5				-- Decreased from 1.8 (NOT USED)
kFlamethrowerConeWidth = 0.08				-- Default is 0.3
kFlamethrowerClipSize = 100					-- Increased from 50
kFlamethrowerRange = 8						-- Decreased from 9
kFlamethrowerUpgradedRange = 10
kFlameThrowerEnergyDamage = 1				-- Default is 1
kFlamethrowerDamageType = kDamageType.Normal-- Default is Flame
kBurnDamagePerSecond = 10
kFlamethrowerBurnDuration = 0.25
kFlamethrowerMaxBurnDuration = 20
--kFlamethrowerDamagePerSecond = 25

-- SIGHHHHHHHHHHHHHHHHHHHH
kSprayDouseOnFireChance = 1.01

-- GL
kGrenadeLauncherGrenadeDamage = 80			-- Decreased from 165
kGrenadeLauncherClipSize = 4				-- Default is 4
kGrenadeLauncherGrenadeDamageRadius = 3.5	-- Decreased from 4.8
kGrenadeLifetime = 2.0						-- Default is 2
kGrenadeLauncherSpeed = 30					-- Increased from 25
kGrenadeLauncherGrenadeDamageType = kDamageType.TripleStructural

kGrenadeFragmentDamageRadius = 3.5
kGrenadeFragmentDamage = 20

-- CLUSTER GRENADES
kClusterGrenadeDamageType = kDamageType.Structural
kClusterGrenadeBurnTime = 2.0

-- PULSE GRENADES
kPulseGrenadeDamageRadius = 6
kPulseGrenadeDamage = 120

-- GAS GRENADES
kNerveGasDamagePerSecond = 50
kNerveGasDamageType = kDamageType.NerveGas

-- MINIGUN
kMinigunDamage = 6							-- This sounds really weak, but its actually only a little less DPS vs MG
kMinigunDamageType = kDamageType.Normal
kMinigunHeatUpRate = 0.175
kMinigunCoolDownRate = 0.25
kMinigunBulletSize = 0.02
kMinigunSpread = Math.Radians(3.1)

-- RAILGUN
kRailgunDamage = 22							-- Default is 10
kRailgunBulletsPerShot = 4
kRailgunDamageType = kDamageType.Normal
kRailgunBulletSize = 0.016
kRailgunMaxAmmo = 6
kRailgunRegenAmmoRate = 2.25
kRailgunMaxRange = 20
kRailgunDropOffStartRange = 10
kRailgunSpreadDistance = 4

-- MINES
kMineDamage = 110
kMineDamageType = kDamageType.Normal
kMineArmingTime = 0.03						-- Default is 0.17
kMinesPerPlayerLimit = 99
kNumMines = 2								-- Increased from 3

-- WELDER
kWelderStructureDamagePerSecond = 25
kWelderDamageType = kDamageType.Normal
kWelderDamagePerSecond = 30
kWelderFriendlyRange = 2.4
kWelderAttackRange = 1.7
kSelfWeldAmount = 5
kPlayerArmorWeldRate = 30					-- Default is 20
kExoArmorWeldRate = 25
kStructureWeldRate = 120					-- Default is 90

-- EXO
kExoShieldMinFuel = 0.99
kExoShieldDamageReductionScalar = 0.75
kExoShieldFuelUsageRate = 2

kExoRepairMinFuel = 0.1
kExoRepairPerSecond = 15
kExoRepairFuelUsageRate = 25
kExoRepairInterval = 0.5

kExoFuelRechargeRate = 10
kMinigunFuelUsageScalar = 1
kRailgunFuelUsageScalar = 1.5


text:
using namespace rpi;

namespace rpi
{
    class MosquittoPublisher : public mosquittopp::mosquittopp
    {
    public:
        explicit MosquittoPublisher(Publisher * pPublisher, QString const & id, QString const & topic, QString const & host, int port = 1883);
        virtual ~MosquittoPublisher();

        bool send_mesage(QString const & message);

    private:
        virtual void on_connect(int rc);
        virtual void on_disconnect();
        virtual void on_error();

        Publisher * m_pPublisher;
        QString m_Id;
        QString m_Topic;
        QString m_Host;
        int m_Port;
    };
}

MosquittoPublisher::MosquittoPublisher(Publisher * pPublisher, QString const & id, QString const & topic, QString const & host, int port)
    :mosquittopp(id.toStdString().c_str()), m_Id(id), m_Topic(topic), m_Host(host)
{
    m_pPublisher = pPublisher;
    lib_init();
    connect(host.toStdString().c_str(), port);
}

MosquittoPublisher::~MosquittoPublisher()
{
    lib_cleanup();
}

bool MosquittoPublisher::send_mesage(QString const & message)
{
    return publish(NULL, m_Topic.toStdString().c_str(), message.size(), reinterpret_cast<const uint8_t *>(message.toStdString().c_str()), 1, false) == MOSQ_ERR_SUCCESS;
}

void MosquittoPublisher::on_connect(int rc)
{
    if (m_pPublisher != NULL)
    {
        emit m_pPublisher->OnConnect(rc);
    }
}

void MosquittoPublisher::on_disconnect()
{
    if (m_pPublisher != NULL)
    {
        emit m_pPublisher->OnDisconnect();
    }
}

void MosquittoPublisher::on_error()
{
    if (m_pPublisher != NULL)
    {
        emit m_pPublisher->OnError(strerror(errno));
    }
}

Publisher::Publisher(QString const & id, QString const & topic, QString const & host, int port)
{
    m_pPublisher = QSharedPointer<MosquittoPublisher>(new MosquittoPublisher(this, id, topic, host, port));
}

Publisher::~Publisher()
{
}

bool Publisher::SendMesage(QString const & message)
{
    if (m_pPublisher != NULL)
    {
        return m_pPublisher->send_mesage(message);
    }
    return false;
}


text:
using System;
using PrtgAPI.Request.Serialization.FilterHandlers;

namespace PrtgAPI.Attributes
{
    /// <summary>
    /// Specifies a custom <see cref="FilterHandler"/> used to validate the components specified in a <see cref="SearchFilter"/>.
    /// </summary>
    [AttributeUsage(AttributeTargets.Field)]
    class FilterHandlerAttribute : Attribute
    {
        private Type type;

        private FilterHandler handler;

        public FilterHandler Handler => handler ?? (handler = (FilterHandler)Activator.CreateInstance(type));

        public FilterHandlerAttribute(Type type)
        {
            this.type = type;
        }
    }
}


text:
package gov.nara.nwts.ftapp.ftprop;

import java.io.File;

import gov.nara.nwts.ftapp.FTDriver;

/**
 * Abstract base class for File Test Properties
 * @author TBrady
 *
 */

public abstract class DefaultFTProp implements FTProp {
        String name;
        String shortname;
        String description;
        Object def;
        protected FTDriver ft;
        String prefix = "";

        boolean failOnEmpty = false;

        public enum RUNMODE {
                TEST,
                PROD;
        }

        public DefaultFTProp(FTDriver ft, String prefix, String name, String shortname, String description, Object def) {
                this.name = name;
                this.shortname = shortname;
                this.description = description;
                this.ft = ft;
                this.def =  def;
                this.prefix = prefix;
        }

        public void setFailOnEmpty(boolean b) {
            failOnEmpty = b;
        }

        public void init() {
                if (ft.hasPreferences()) {
                        def = ft.getPreferences().get(getPrefString(), def.toString());
                }
        }
        public void init(Object[] vals) {
                if (ft.hasPreferences()) {
                        String s = ft.getPreferences().get(getPrefString(), def.toString());
                        if (s == null) return;
                        for(Object obj: vals) {
                                if (s.equals(obj.toString())) {
                                        def = obj;
                                        return;
                                }
                        }
                }
        }

        public String getPrefString() {
                return "ftprop--"+prefix+"--"+shortname;
        }

        public String describe() {
                return description;
        }
        public Object getDefault() {
                return def;
        }

        public String getName() {
                return name;
        }
        public String getShortName() {
                return shortname;
        }

        public String getShortNameNormalized() {
                return getShortName().replaceAll("[\\s&]","");
        }

        public InitializationStatus initValidation(File refFile){
                InitializationStatus iStat = new InitializationStatus();
                if (failOnEmpty) {
                        if (getValue().toString().isEmpty()) {
                                iStat.addFailMessage(String.format("Propery %s cannot be empty", getName()));
                        }
                }
                return iStat;
        }

}


text:
sparse-demo
===========

Sources for the Demo Web Service that is included in the [sParse](https://github.com/vancarney/sparse) repo


text:
#ifndef UNIQUE_RESOURCE_H_
#define UNIQUE_RESOURCE_H_

namespace std{	namespace experimental{

enum class invoke_it { once, again };

template<typename R, typename D>
class unique_resource_t {
	R resource;
	D deleter;
	bool execute_on_destruction; // exposition only
	unique_resource_t& operator=(unique_resource_t const &) = delete;
	unique_resource_t(unique_resource_t const &) = delete; // no copies!

public:
	// construction
	explicit unique_resource_t(R && resource, D && deleter, bool shouldrun = true) noexcept
		: resource(std::move(resource))
		, deleter(std::move(deleter))
		, execute_on_destruction{ shouldrun }
	{ }

	// move
	unique_resource_t(unique_resource_t &&other) noexcept
	: resource(std::move(other.resource))
	, deleter(std::move(other.deleter))
	, execute_on_destruction{ other.execute_on_destruction }
	{
		other.release();
	}

	unique_resource_t& operator=(unique_resource_t &&other) noexcept
	{
		this->invoke(invoke_it::once);
		deleter = std::move(other.deleter);
		resource = std::move(other.resource);
		execute_on_destruction = other.execute_on_destruction;
		other.release();
		return *this;
	}

		// resource release
	~unique_resource_t()
	{
		this->invoke(invoke_it::once);
	}

	void invoke(invoke_it const strategy = invoke_it::once) noexcept
	{
		if (execute_on_destruction)
		{
			try
			{
				this->get_deleter()(resource);
			}
			catch (...)
			{
			}
		}
		execute_on_destruction = strategy == invoke_it::again;
	}

	R const & release() noexcept
	{
		execute_on_destruction = false;
		return this->get();
	}

	void reset(R && newresource) noexcept
	{
		invoke(invoke_it::again);
		resource = std::move(newresource);
	}

	// resource access
	R& get() noexcept
	{
		return resource;
	}

	operator R const &() const noexcept
	{
		return resource;
	}

	R operator->() const noexcept
	{
		return resource;
	}

	std::add_lvalue_reference_t<std::remove_pointer_t<R>> operator*() const
	{
		return *resource;
	}

	// deleter access
	const D & get_deleter() const noexcept
	{
		return deleter;
	}
};

//factories
template<typename R, typename D>
unique_resource_t<R, D> unique_resource(R && r, D t) noexcept
{
	return unique_resource_t<R, D>(std::move(r), std::move(t), true);
}

template<typename R, typename D>
unique_resource_t<R, D> unique_resource_checked(R r, R invalid, D t) noexcept
{
	bool shouldrun = (r != invalid);
	return unique_resource_t<R, D>(std::move(r), std::move(t), shouldrun);
}

}}

#endif /* UNIQUE RESOURCE H */


text:
'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	Activity = mongoose.model('Activity'),
	_ = require('lodash');

/**
 * Get the error message from error object
 */
var getErrorMessage = function(err) {
	var message = '';

	if (err.code) {
		switch (err.code) {
			case 11000:
			case 11001:
				message = 'Activity already exists';
				break;
			default:
				message = 'Something went wrong';
		}
	} else {
		for (var errName in err.errors) {
			if (err.errors[errName].message) message = err.errors[errName].message;
		}
	}

	return message;
};

/**
 * Create a Activity
 */
exports.create = function(req, res) {
	var activity = new Activity(req.body);
	activity.user = req.user;

	activity.save(function(err) {
		if (err) {
			return res.send(400, {
				message: getErrorMessage(err)
			});
		} else {
			res.jsonp(activity);
		}
	});
};

/**
 * Show the current Activity
 */
exports.read = function(req, res) {
	res.jsonp(req.activity);
};

/**
 * Update a Activity
 */
exports.update = function(req, res) {
	var activity = req.activity ;

	activity = _.extend(activity , req.body);

	activity.save(function(err) {
		if (err) {
			return res.send(400, {
				message: getErrorMessage(err)
			});
		} else {
			res.jsonp(activity);
		}
	});
};

/**
 * Delete an Activity
 */
exports.delete = function(req, res) {
	var activity = req.activity ;

	activity.remove(function(err) {
		if (err) {
			return res.send(400, {
				message: getErrorMessage(err)
			});
		} else {
			res.jsonp(activity);
		}
	});
};

/**
 * List of Activities
 */
exports.list = function(req, res) {
	Activity.find().sort('-created').populate('user', 'displayName').populate('article', 'title').exec(function(err, activities) {
		if (err) {
			return res.send(400, {
				message: getErrorMessage(err)
			});
		} else {
			res.jsonp(activities);
		}
	});
};

/**
 * Activity middleware
 */
exports.activityByID = function(req, res, next, id) {
	Activity.findById(id).populate('user', 'displayName').populate('article', 'title').exec(function(err, activity) {
		if (err) return next(err);
		if (! activity) return next(new Error('Failed to load Activity ' + id));
		req.activity = activity ;
		next();
	});
};

/**
 * Activity authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.activity.user.id !== req.user.id) {
		return res.send(403, 'User is not authorized');
	}
	next();
};


text:
<FrameLayout
    android:id="@+id/content_frame"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:ignore="MergeRootFrame"/>


text:
VSlider
=================

This is a fairly stright forward **jQuery 2** plugin, compatible with **Bootstrap** that creates a responsive multi slider animated with **CSS3 transitions**.

## How it works

``` html
<div class="content">

  <div class="container">
    <div class="slide"><p>content</p></div>
    <div class="slide"><p>content</p></div>
    <div class="slide"><p>content</p></div>
  </div>

  <div class="container">
    <div class="slide"><p>content</p></div>
    <div class="slide"><p>content</p></div>
    <div class="slide"><p>content</p></div>
  </div>

  <div class="container">
    <div class="slide"><p>content</p></div>
    <div class="slide"><p>content</p></div>
    <div class="slide"><p>content</p></div>
  </div>

</div>
```

This is a basic 3 slides block

```scss
.content {
  @media (min-width: @screen-sm) {
    width: @container-sm;
  }
  @media (min-width: @screen-md) {
    width: @container-md;
  }
  @media (min-width: @screen-lg) {
    width: @container-lg;
  }
}

.content {
  border: 1px solid red;
  margin: 0 auto;
  background: red;
  min-height: 200px;

  .container {
    height: 200px;
    clear: right;
    overflow: hidden;

    @media (min-width: @screen-sm) {
      float: left;
      width: 100% / 3; //100% divided for the number of slide blocks
    }
  }
}
```

The relative **less** configuration.

### Options

`slide_timing` the css3 transition timing ( default 1s )

`slide_effect` the css3 transition type ( default "cubic-bezier(1,.34,.83,.9)" )


text:
jQuery UI themes for Rails
==========================

All the pre rolled themes for jQuery UI packaged into a gem.

Install
-------
In your Gemfile, add:

    gem 'jquery-ui-themes'

and run `bundle install`.

Usage
-----

In your stylesheet manifest include the following

`*= require jquery-ui/<theme name>`

where theme name can be one of the following:

* black-tie
* blitzer
* cupertino
* dark-hive
* dot-luv
* eggplant
* excite-bike
* flick
* hot-sneaks
* humanity
* le-frog
* mint-choc
* overcast
* pepper-grinder
* redmond
* smoothness
* south-street
* start
* sunny
* swanky-purse
* trontastic
* ui-darkness
* ui-lightness
* vader

Helper
------

If you want to take advantage of the Google CDN a helper is included that takes the theme name and optional version (latest used if version is not specified)

Example:

`stylesheet_link_tag jqueryui_css_google_cdn('mint-choc', '1.7.2')`

Rake Tasks
----------

Includes a rake task which updates the themeroller created file with image-path and moves the new file and images into the asset folder (stylesheets/jquery-ui and images/jquery-ui respectively).

Example:

`rake jquery_ui_themes:import:themeroller[jquery-ui-1.8.16.custom/css/hot-sneaks/jquery-ui-1.8.16.custom.css,hot-sneaks]`

Also includes a rake task to import the files for a specific version and theme from Google CDN

Example

`rake jquery_ui_themes:import:google_cdn[1.8.17,ui-lightness]`

Optionally you can pass 'all' instead of a specific theme and all the current themeroller themes for that version will be imported into the assets folder.

Current theme version
---------------------

The current versions of the themes are for **1.10.3** of [jQuery UI](http://jqueryui.com/ "jQuery UI"). Since the jquery-rails gem is no longer including jQuery UI the plan is to sync with the version in use by the [jquery-ui-rails](https://github.com/joliss/jquery-ui-rails "jquery-ui-rails") gem, but should it be required the included rake tasks make supporting older or custom themes trivial.

Requirements
------------

Requires Rails 3.1 and higher, or anything that uses the asset pipeline.


text:
<?php
namespace ProcureTest\AP\Command;

use Doctrine\ORM\EntityManager;
use ProcureTest\Bootstrap;
use Procure\Application\Command\TransactionalCmdHandlerDecorator;
use Procure\Application\Command\AP\AddRowCmd;
use Procure\Application\Command\AP\AddRowCmdHandler;
use Procure\Application\Command\AP\Options\ApRowCreateOptions;
use Procure\Application\DTO\Ap\ApRowDTO;
use Procure\Infrastructure\Doctrine\APQueryRepositoryImpl;
use PHPUnit_Framework_TestCase;

class AddRowCmdTest extends PHPUnit_Framework_TestCase
{

    protected $serviceManager;

    public function setUp()
    {
        $root = realpath(dirname(dirname(dirname(dirname(__FILE__)))));
        // echo $root;
        require ($root . '/Bootstrap.php');
    }

    public function testOther()
    {
        try {
            /** @var EntityManager $doctrineEM ; */
            $doctrineEM = Bootstrap::getServiceManager()->get('doctrine.entitymanager.orm_default');

            $companyId = 1;
            $userId = 39;

            $dto = new ApRowDTO();
            $dto->docQuantity = 10;
            $dto->docUnitPrice = 229;
            $dto->poRow = 2629;
            $dto->item = 4245;
            $dto->conversionFactor = 1;
            $dto->unit = "pcs";
            $dto->glAccount = 6;
            $dto->costCenter = 2;

            $rootEntityId = 2828;
            $rootEntityToken = "3c1b51e9-f6f9-4298-946f-d58b49428571";
            $version = 9;

            $rep = new APQueryRepositoryImpl($doctrineEM);
            $rootEntity = $rep->getHeaderById($rootEntityId, $rootEntityToken);

            $options = new ApRowCreateOptions($rootEntity, $rootEntityId, $rootEntityToken, $version, $userId, __METHOD__);

            $cmdHandler = new AddRowCmdHandler();
            $cmdHandlerDecorator = new TransactionalCmdHandlerDecorator($cmdHandler);
            $cmd = new AddRowCmd($doctrineEM, $dto, $options, $cmdHandlerDecorator);
            $cmd->execute();
            var_dump($dto->getNotification());
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }
}


text:
var cleanDocument = exports.cleanDocument = function(document) {
  // TODO: Concat all regex and change punctuationRegex to including instead of excluding characters

  var punctuationRegex = /\=|\@|\#|\||\+|\-|\,|\.|\!|\?|\"|\'|\:|\;|\(|\)|\[|\]|\{|\}|\/|\\/g;

  document = document.replace(punctuationRegex, "");
  document = document.toLowerCase();

  // Trim document
  document = document.replace(/^\s+|\s+$/g, "");
  // Change all whitespace multiples to single spaces
  // e.g. convert '   ' into ' '
  document = document.replace(/\s{2,}/g, " ");

  return document;
};

var getNgrams = exports.getNgrams = function(document, numWordsInNgram) {
  var words = document.split(" ")
    , ngrams = [];

  // We only want to create whole ngrams
  for (var w = 0; w+numWordsInNgram <= words.length; w++) {
    // Create ngram
    var ngram = "";
    for (var n = 0; n < numWordsInNgram; n++) {
      ngram += words[w+n];

      // Add a space between words, unless we're at the last index
      if (n+1 < numWordsInNgram) ngram += ' ';
    }

    ngrams.push(ngram);
  }

  // There may have been less words than numWordsInNgram
  // or the document may have contained only spaces
  return (ngrams.length < 1) ? false : ngrams;
};

var getNgramFrequencies = exports.getNgramFrequencies =
 function(documents, numWordsInNgram, countNgramOncePerDoc) {
  var ngramFrequencies = {}
    , totalNgrams      = 0;

  if (countNgramOncePerDoc === undefined)
    countNgramOncePerDoc = false;

  for (var d = 0; d < documents.length; d++) {
    documents[d] = cleanDocument(documents[d]);

    var ngrams = getNgrams(documents[d], numWordsInNgram);

    // numWordsInNgram may been larger than the number of words
    if (!ngrams) continue;

    if (countNgramOncePerDoc) var countedNgrams = [];
    for (var n = 0; n < ngrams.length; n++) {
      totalNgrams++;

      // If we have been instructed to only count ngrams once per document
      if (countNgramOncePerDoc) {
        // Just continue to the next ngram without counting it (again)
        if (countedNgrams[ngrams[n]]) continue;
        else countedNgrams[ngrams[n]] = true;
      }

      if (ngramFrequencies[ngrams[n]]) ngramFrequencies[ngrams[n]]++;
      else ngramFrequencies[ngrams[n]] = 1;
    }
  }

  return {
    "ngramFrequencies": ngramFrequencies,
    "totalNgrams": totalNgrams
  };
};

exports.getNgramBayesianProbabilities = function(documents, numWordsInNgram) {
  var probabilities         = {}
    , posNgramFrequencyData = getNgramFrequencies(documents.pos, numWordsInNgram)
    , negNgramFrequencyData = getNgramFrequencies(documents.neg, numWordsInNgram)
    , posNgramFrequencies   = posNgramFrequencyData.ngramFrequencies
    , negNgramFrequencies   = negNgramFrequencyData.ngramFrequencies;

  for (var ngram in posNgramFrequencies) {
    // Don't calculate the probability if we don't have frequency data for negative ngrams
    if (!negNgramFrequencies[ngram])
      continue;

    // This assumes the number of positive documents are the same as the number of negative documents
    // Pr(S|W) = Pr(W|S) / ( Pr(W|S) + Pr(W|H) )
    probabilities[ngram] = posNgramFrequencies[ngram] /
                           ( posNgramFrequencies[ngram] +
                             negNgramFrequencies[ngram] );
  }

  return probabilities;
};

exports.getNgramProbabilities = function(documents, numWordsInNgram) {
  var probabilities      = {}
    , ngramFrequencyData = getNgramFrequencies(documents, numWordsInNgram)
    , ngramFrequencies   = ngramFrequencyData.ngramFrequencies
    , totalNgrams        = ngramFrequencyData.totalNgrams;

  for (var ngram in ngramFrequencies) {
    probabilities[ngram] = ngramFrequencies[ngram] / totalNgrams;
  }

  return probabilities;
};


text:
using System;
using System.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.ObjCRuntime;

namespace ResxTranslatorMac
{
	public partial class AppDelegate : NSApplicationDelegate
	{
		MainWindowController mainWindowController;

		public AppDelegate()
		{
		}

		public override void FinishedLaunching(NSObject notification)
		{
			mainWindowController = ResxTranslator.Common.ViewFactory.Create<MainWindowController>();
			mainWindowController.Window.MakeKeyAndOrderFront(this);
		}
	}
}


text:
using System;
using System.Collections.Generic;
using MinaGlosor.Web.Models;
using NUnit.Framework;

namespace MinaGlosor.Test.Api.Domain
{
    [TestFixture]
    public class PracticeSessionStatisticsTest
    {
        private static IEnumerable<Tuple<int, int, int, int, int, int>> Numbers
        {
            get
            {
                yield return Tuple.Create(1, 0, 0, 10, 0, 0);
                yield return Tuple.Create(1, 1, 0, 10, 10, 0);
            }
        }

        private static IEnumerable<Tuple<int, int, int, int, int, int>> NumbersAll
        {
            get
            {
                yield return Tuple.Create(3, 4, 0, 30, 40, 0);
                yield return Tuple.Create(3, 0, 4, 30, 0, 40);
            }
        }

        [TestCaseSource("Numbers")]
        public void VerifyGreenUnfinished(Tuple<int, int, int, int, int, int> tuple)
        {
            var statistics = new PracticeSessionStatistics(false, 10, tuple.Item1, tuple.Item2, tuple.Item3);

            Assert.That(statistics.Green, Is.EqualTo(tuple.Item4));
        }

        [TestCaseSource("Numbers")]
        public void VerifyBlueUnfinished(Tuple<int, int, int, int, int, int> tuple)
        {
            var statistics = new PracticeSessionStatistics(false, 10, tuple.Item1, tuple.Item2, tuple.Item3);

            Assert.That(statistics.Blue, Is.EqualTo(tuple.Item5));
        }

        [TestCaseSource("Numbers")]
        public void VerifyYellowUnfinished(Tuple<int, int, int, int, int, int> tuple)
        {
            var statistics = new PracticeSessionStatistics(false, 10, tuple.Item1, tuple.Item2, tuple.Item3);

            Assert.That(statistics.Yellow, Is.EqualTo(tuple.Item6));
        }

        [TestCaseSource("NumbersAll")]
        public void VerifyGreenFinished(Tuple<int, int, int, int, int, int> tuple)
        {
            var statistics = new PracticeSessionStatistics(false, 10, tuple.Item1, tuple.Item2, tuple.Item3);

            Assert.That(statistics.Green, Is.EqualTo(tuple.Item4));
        }

        [TestCaseSource("NumbersAll")]
        public void VerifyBlueFinished(Tuple<int, int, int, int, int, int> tuple)
        {
            var statistics = new PracticeSessionStatistics(false, 10, tuple.Item1, tuple.Item2, tuple.Item3);

            Assert.That(statistics.Blue, Is.EqualTo(tuple.Item5));
        }

        [TestCaseSource("NumbersAll")]
        public void VerifyYellowFinished(Tuple<int, int, int, int, int, int> tuple)
        {
            var statistics = new PracticeSessionStatistics(false, 10, tuple.Item1, tuple.Item2, tuple.Item3);

            Assert.That(statistics.Yellow, Is.EqualTo(tuple.Item6));
        }
    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<resources>
  <!--TODO re-enable when "Accounts" is available in Navigation Drawer-->
  <!--<string name="drawer_item_accounts">Accounts</string>-->
  <!--TODO re-enable when "On Device" is available
    <string name="drawer_item_on_device">On device</string>-->
</resources>


text:
using Signum.Engine;
using Signum.Engine.Authorization;
using Signum.Entities;
using Signum.Entities.Authorization;
using Signum.React.Filters;
using Signum.Utilities;
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Authorization;

namespace Signum.React.Authorization
{
    public static class AuthTokenServer
    {
        static Func<AuthTokenConfigurationEmbedded> Configuration;

        public static void Start(Func<AuthTokenConfigurationEmbedded> tokenConfig, string hashableEncryptionKey)
        {
            Configuration = tokenConfig;
            CryptoKey = new MD5CryptoServiceProvider().Using(p => p.ComputeHash(Encoding.UTF8.GetBytes(hashableEncryptionKey)));

            SignumAuthenticationFilter.Authenticators.Add(TokenAuthenticator);
            SignumAuthenticationFilter.Authenticators.Add(AnonymousUserAuthenticator);
            SignumAuthenticationFilter.Authenticators.Add(AllowAnonymousAuthenticator);
            SignumAuthenticationFilter.Authenticators.Add(InvalidAuthenticator);
        }

        public static SignumAuthenticationResult? InvalidAuthenticator(FilterContext actionContext)
        {
            throw new AuthenticationException("No authentication information found!");
        }

        public static SignumAuthenticationResult? AnonymousUserAuthenticator(FilterContext actionContext)
        {
            if (AuthLogic.AnonymousUser != null)
                return new SignumAuthenticationResult { User = AuthLogic.AnonymousUser };

            return null;
        }

        public static SignumAuthenticationResult? AllowAnonymousAuthenticator(FilterContext actionContext)
        {
            if (actionContext.ActionDescriptor is ControllerActionDescriptor cad &&
                (cad.MethodInfo.HasAttribute<SignumAllowAnonymousAttribute>() || cad.ControllerTypeInfo.HasAttribute<SignumAllowAnonymousAttribute>()))
                return new SignumAuthenticationResult();

            return null;
        }

        static SignumAuthenticationResult? TokenAuthenticator(FilterContext ctx)
        {
            var authHeader = ctx.HttpContext.Request.Headers["Authorization"].FirstOrDefault();
            if (authHeader == null)
            {
                return null;
            }

            var token = DeserializeAuthHeaderToken(authHeader);

            var c = Configuration();

            bool requiresRefresh = token.CreationDate.AddMinutes(c.RefreshTokenEvery) < TimeZoneManager.Now ||
                c.RefreshAnyTokenPreviousTo.HasValue && token.CreationDate < c.RefreshAnyTokenPreviousTo;

            if (requiresRefresh)
            {
                ctx.HttpContext.Response.Headers["New_Token"] = RefreshToken(token, out var newUser);
                return new SignumAuthenticationResult { User = token.User };
            }

            return new SignumAuthenticationResult { User = token.User };
        }

        static string RefreshToken(AuthToken oldToken, out UserEntity newUser)
        {
            var user = AuthLogic.Disable().Using(_ => Database.Query<UserEntity>().SingleOrDefaultEx(u => u.Id == oldToken.User.Id));

            if (user == null)
                throw new AuthenticationException(LoginAuthMessage.TheUserIsNotLongerInTheDatabase.NiceToString());

            if (user.State == UserState.Disabled)
                throw new AuthenticationException(LoginAuthMessage.User0IsDisabled.NiceToString(user));

            if (user.UserName != oldToken.User.UserName)
                throw new AuthenticationException(LoginAuthMessage.InvalidUsername.NiceToString());

            if (!user.PasswordHash.EmptyIfNull().SequenceEqual(oldToken.User.PasswordHash.EmptyIfNull()))
                throw new AuthenticationException(LoginAuthMessage.InvalidPassword.NiceToString());

            AuthToken newToken = new AuthToken
            {
                User = user,
                CreationDate = TimeZoneManager.Now,
            };

            var result = SerializeToken(newToken);
            newUser = user;
            return result;
        }

        static BinaryFormatter formatter = new BinaryFormatter();

        public static Func<string, AuthToken> DeserializeAuthHeaderToken = (string authHeader) => DeserializeToken(authHeader.After("Bearer "));

        public static AuthToken DeserializeToken(string token)
        {
            try
            {
                var array = Convert.FromBase64String(token);

                array = Decrypt(array);

                using (var ms = new MemoryStream(array))
                using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Decompress))
                    return (AuthToken)formatter.Deserialize(ds);
            }
            catch (Exception)
            {
                throw new AuthenticationException("Invalid token");
            }
        }

        public static string CreateToken(UserEntity user)
        {
            AuthToken newToken = new AuthToken
            {
                User = user,
                CreationDate = TimeZoneManager.Now,
            };

            return SerializeToken(newToken);
        }

        static string SerializeToken(AuthToken entity)
        {
            using (HeavyProfiler.LogNoStackTrace("SerializeToken"))
            {
                var array = new MemoryStream().Using(ms =>
                {
                    using (DeflateStream ds = new DeflateStream(ms, CompressionMode.Compress))
                        formatter.Serialize(ds, entity);

                    return ms.ToArray();
                });

                array = Encrypt(array);

                return Convert.ToBase64String(array);
            }
        }

        static byte[] CryptoKey;

        //http://stackoverflow.com/questions/8041451/good-aes-initialization-vector-practice
        static byte[] Encrypt(byte[] toEncryptBytes)
        {
            using (var provider = new AesCryptoServiceProvider())
            {
                provider.Key = CryptoKey;
                provider.Mode = CipherMode.CBC;
                provider.Padding = PaddingMode.PKCS7;
                using (var encryptor = provider.CreateEncryptor(provider.Key, provider.IV))
                {
                    using (var ms = new MemoryStream())
                    {
                        ms.Write(provider.IV, 0, provider.IV.Length);
                        using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                        {
                            cs.Write(toEncryptBytes, 0, toEncryptBytes.Length);
                            cs.FlushFinalBlock();
                        }
                        return ms.ToArray();
                    }
                }
            }
        }

        static byte[] Decrypt(byte[] encryptedString)
        {
            using (var provider = new AesCryptoServiceProvider())
            {
                provider.Key = CryptoKey;
                using (var ms = new MemoryStream(encryptedString))
                {
                    // Read the first 16 bytes which is the IV.
                    byte[] iv = new byte[16];
                    ms.Read(iv, 0, 16);
                    provider.IV = iv;

                    using (var decryptor = provider.CreateDecryptor())
                    {
                        using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                        {
                            return cs.ReadAllBytes();
                        }
                    }
                }
            }
        }

    }

    [Serializable]
    public class AuthToken
    {
        public UserEntity User { get; set; }

        public DateTime CreationDate { get; set; }
    }

    [Serializable]
    public class NewTokenRequiredException : Exception
    {
        public NewTokenRequiredException(string message) : base(message) { }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>app.controllers.modules.chat.people - Documentation de l'outil de démonstration JavaScript du Gaia-Project</title>
    <link rel="stylesheet" href="http://yui.yahooapis.com/3.9.1/build/cssgrids/cssgrids-min.css">
    <link rel="stylesheet" href="../assets/vendor/prettify/prettify-min.css">
    <link rel="stylesheet" href="../assets/css/main.css" id="site_styles">
    <link rel="shortcut icon" type="image/png" href="../assets/favicon.png">

            API Docs for: 1.0

APIs

Classes

Modules

                            <input type="search" id="api-filter" placeholder="Type to filter APIs">

app

app.client.socketclient

app.controllers.chatservice

app.controllers.login

app.controllers.modules.chat.people

app.controllers.modules.game.CubeCtrl

app.controllers.modules.game.ShootCtrl

app.controllers.modules.game.SpaceCtrl

app.controllers.modules.game.SpaceShipCtrl

app.controllers.modules.login.login

app.controllers.modules.login.register

app.controllers.modules.menu.menu

app.modules.servers.SocketServer

app.objects.email

app.objects.user

app.security.diffie-helman

app.servers.HTTPServer

app.services.chat

app.services.login

app.storage.mongodb

app.storage.mysql

app.storage.query

app.utils.checkers

app.utils.date

config

ConfigModel

KeyboardServices

LanguageModel

LeapMotionController

resize

                    Show:

                        <input type="checkbox" id="api-show-inherited" checked>
                        Inherited

                        <input type="checkbox" id="api-show-protected">
                        Protected

                        <input type="checkbox" id="api-show-private">
                        Private

                        <input type="checkbox" id="api-show-deprecated">
                        Deprecated

app.controllers.modules.chat.people Class

                                    Defined in: www/application/js/controllers/modules/chat/people.js:1

Manager of the connected user list, gives access to several method for data access

Index

Methods

Item Index

Methods

                                                        init

                                                        startChat

Methods

init

                                                    ()

                                                            Defined in
                                                    www/application/js/controllers/modules/chat/people.js:18

init method, get connected user list

startChat

                                                        (

                                                                    id

)

                                                            Defined in
                                                    www/application/js/controllers/modules/chat/people.js:34

start a discussion with another user

Parameters:

                                                                    id
                                                                    Number