text:
import re

from datetime import datetime, timedelta

class GraphiteRetention(object):
    """
    Represents one graphite retention. Provides utilities to get time buckets.
    """
    RETENTION_RE = re.compile(r'^(\d+)([a-z]+)$')
    MULTIPLIERS = {
        's': 1,
        'm': 60,
        'h': 60 * 60,
        'd': 60 * 60 * 24,
        'w': 60 * 60 * 24 * 7,
        'y': 60 * 60 * 24 * 365,
    }

    def __init__(self, retention):
        precision, duration = retention.split(':')
        self.precision = self._str_to_timedelta(precision)
        self.duration = self._str_to_timedelta(duration)

    def _str_to_timedelta(self, retention):
        match = self.RETENTION_RE.match(retention)
        seconds = int(match.group(1)) * self.MULTIPLIERS[match.group(2)]
        return timedelta(seconds=seconds)

    def get_buckets(self, now=None, finish=None):
        """
        Returns an iterator of tuples (start, end) that define the time
        buckets that this retention scheme covers.
        kwargs:
            now: timestamp of current time. Defaults to current time.
            finish: timestamp of when to stop buckets. Defaults to now.
        """
        if now is None:
            now = datetime.utcnow()
        if finish is None:
            finish = now
        start = now - self.duration

        while start < finish:
            end = start + self.precision
            if end > finish:
                end = finish
            yield (start, end)
            start = end

class RetentionScheme(object):
    """
    Represents multiple graphite retentions. Provides utilities to get time
    buckets across all retentions.
    """
    def __init__(self, retentions):
        self.retentions = [GraphiteRetention(r) for r in retentions.split(',')]

    def get_buckets(self, now=None):
        """
        Returns an iterator of tuples (start, end) that define the time
        buckets that all the retention schemes cover.
        kwargs:
            now: timestamp of current time. Defaults to current time.
        """
        if now is None:
            now = datetime.utcnow()
        finish = now

        for r in self.retentions:
            beginning = now
            for start, end in r.get_buckets(now=now, finish=finish):
                # We always want to end the next retention at the earliest
                # point that this retention covers, to avoid overlaps
                beginning = min(beginning, start)
                yield (start, end)
            # The next retention should end where this one started
            finish = beginning

redpajama_set_name: RedPajamaGithub


text:
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*  Fluent Bit
 *  ==========
 *  Copyright (C) 2019-2021 The Fluent Bit Authors
 *  Copyright (C) 2015-2018 Treasure Data Inc.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

#ifndef FLB_WE_WMI_H
#define FLB_WE_WMI_H

#include "we.h"

int we_wmi_init(struct flb_we *ctx);
int we_wmi_exit(struct flb_we *ctx);

#endif


text:
from django.conf.urls import url

urlpatterns = [
    url(r'^$', 'schedules.views.index', name='index'),
    url(r'^home$', 'schedules.views.home', name='home'),
    url(r'^login$', 'schedules.views.log_in', name='login'),
    url(r'^logout$', "schedules.views.log_out", name="logout"),

    url(r'^query-users$', 'schedules.views.query_users'),

    url(r'^project/create$', 'schedules.views.create_project'),
    url(r'^project/s/(?P<project_slug>.+?)/all-members', 'schedules.views.query_project_members'),
    url(r'^project/s/(?P<project_slug>.+?)/remove-member', 'schedules.views.query_remove_member'),
    url(r'^project/s/(?P<project_slug>.+?)/add-member', 'schedules.views.add_member'),
    url(r'^project/s/(?P<project_slug>.+?)/submit$', 'schedules.views.submit_schedule'),
    url(r'^project/s/(?P<project_slug>.+?)/home$', 'schedules.views.project'),
]


text:
// Plato.NET
// Copyright (c) 2017 ReflectSoftware Inc.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using Plato.ExceptionManagement.Interfaces;
using Plato.Core.Interfaces;
using Plato.Core.Miscellaneous;
using Plato.Core.Strings;
using System;
using System.Collections.Specialized;

namespace Plato.ExceptionManagement
{
    /// <summary>
    /// To take advantage of this Exception Publisher, the following attributes
    /// must be added to the app/web config file.
    /// <platoSetting>
    /// <exceptionManagement mode="on">
    /// <publisher mode="on"name="TextFilePublisher"type="Plato.ExceptionManagement.ExceptionLogTextFilePublisher, Plato.ExceptionManagement"recycle="5"filePath="$(workingdir)\Logs\ri_exceptions.txt"/>
    /// </exceptionManagement>
    /// </platoSetting>
    ///
    /// In addition to this section a configuration sections needs to be defined as well.
    /// <configSections>
    /// <section name="platoSetting"type="Plato.Configuration.ConfigurationHandler, Plato.Configuration"/>
    /// </configSections>
    ///
    /// </summary>
    public class ExceptionLogTextFilePublisher : IExceptionPublisher, IDisposable
    {
        private readonly static string _separator;

        private string _filePath;
        private int _recycle;
        private ILogTextFileWriter _logTextFileWriter;

        /// <summary>
        /// Gets a value indicating whether this <see cref="ExceptionLogTextFilePublisher"/> is disposed.
        /// </summary>
        /// <value>
        ///   <c>true</c> if disposed; otherwise, <c>false</c>.
        /// </value>
        public bool Disposed { get; private set; }

        /// <summary>
        /// Initializes the <see cref="ExceptionLogTextFilePublisher"/> class.
        /// </summary>
        static ExceptionLogTextFilePublisher()
        {
            _separator = string.Format("{0,80}", string.Empty).Replace(" ", "_");
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ExceptionLogTextFilePublisher"/> class.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="args">The arguments.</param>
        public ExceptionLogTextFilePublisher(NameValueCollection parameters, params object[] args)
        {
            Disposed = false;

            _recycle = 0;
            int.TryParse(parameters["recycle"], out _recycle);
            if (_recycle < 0)
            {
                _recycle = 0;
            }

            _filePath = parameters["filePath"];

            CreateTextFileWriter(_filePath, _recycle);
        }

        /// <summary>
        /// Creates the text file writer.
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <param name="recycle">The recycle.</param>
        protected void CreateTextFileWriter(string filePath, int recycle)
        {
            if (string.IsNullOrWhiteSpace(filePath))
            {
                return;
            }

            if (_logTextFileWriter == null)
            {
                _logTextFileWriter = new LogTextFileWriter(filePath, recycle, true);
            }
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            lock (this)
            {
                if (!Disposed)
                {
                    Disposed = true;
                    GC.SuppressFinalize(this);

                    _logTextFileWriter?.Dispose();
                    _logTextFileWriter = null;
                }
            }
        }
        /// <summary>
        /// Publishes the specified exception.
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <param name="additionalParameters">The additional parameters.</param>
        public void Publish(Exception exception, NameValueCollection additionalParameters)
        {
            try
            {
                lock (this)
                {
                    if (_logTextFileWriter != null)
                    {
                        var entry = ExceptionFormatter.ConstructMessage(exception, additionalParameters);
                        _logTextFileWriter.WriteLine($"{entry}{Environment.NewLine}{_separator}{Environment.NewLine}");
                    }
                }
            }
            catch (Exception)
            {
            }
        }
    }
}


text:
var program = require('commander');
var cli = require('./cli');
var conf = require('../package.json');
var config;
var bingo = false;

/* eslint no-console: "off" */
program.usage('<command> [options]');

program.setConfig = function(conf) {
  config = conf;
  if (config.execPath) {
    process.env.STARTING_EXEC_PATH = process.env.STARTING_EXEC_PATH || config.execPath;
  }
  return this;
};

program.getConfig = function(name) {
  if (!config) {
    config = {};
  }

  var _config = {};
  var options = getOptions();

  Object.keys(config).forEach(function (name) {
    if (!/Callback$/.test(name) && typeof config[name] == 'function') {
      _config[name] = config[name](options);
    } else {
      _config[name] = config[name];
    }
  });

  return arguments.length > 0 ? _config[name] : _config;
};

program.parse_ = program.parse;

function getMaxHttpHeaderSize(argv) {
  for (var i = 3, len = argv.length; i < len; i++) {
    var name = argv[i];
    if (name === '--max-http-header-size') {
      var size = argv[i + 1];
      argv.splice(i, 1);
      if (size && size[0] !== '-') {
        argv.splice(i + 1, 1);
      }
      return size > 0 ? size : 0;
    }
    if (/^--max-http-header-size=([^\s]+)$/.test(name)) {
      argv.splice(i, 1);
      return RegExp.$1 > 0 ? RegExp.$1 : 0;
    }
  }
  return 0;
}

program.parse = function(argv) {

  if (!program.optionFor('--version')) {
    program
      .version(program.getConfig('version') || conf.version);
  }

  program
    .command('run')
    .description('Start a front service')
    .action(function () {
      bingo = true;
      cli.run(program.getConfig('main'), getOptions(), program.getConfig('runCallback'));
    });

  program
    .command('start')
    .description('Start a background service')
    .action(function () {
      bingo = true;
      cli.start(program.getConfig('main'), getOptions(),
        program.getConfig('startCallback'), program.getConfig('version'));
    });

  program
    .command('stop')
    .description('Stop current background service')
    .action(function () {
      bingo = true;
      cli.stop(program.getConfig('main'), program.getConfig('stopCallback'));
    });

  program
    .command('restart')
    .description('Restart current background service')
    .action(function () {
      bingo = true;
      cli.restart(program.getConfig('main'), getOptions(),
        program.getConfig('restartCallback'), program.getConfig('version'));
    });

  program
    .command('help')
    .description('Display help information')
    .action(function () {
      bingo = true;
      program.help();
    });
  argv = Array.prototype.slice.call(argv || process.argv || []);
  program.__maxHttpHeaderSize = getMaxHttpHeaderSize(argv);
  program.parse_(argv);

  if (!bingo) {
    console.log('Type \'' + (program.getConfig('name') || conf.name) + ' help\' for usage.');
  }

  return program;
};

function getOptions() {
  var options = {
    __maxHttpHeaderSize: program.__maxHttpHeaderSize,
    clearPreOptions: program.prevOptions === false,
    noGlobalPlugins: program.globalPlugins === false
  };
  Object.keys(program).forEach(function(name) {
    if (program.optionFor('--' + name)) {
      options[name] = program[name];
    }
  });

  return options;
}

module.exports = program;
module.exports.cli = require('./cli');


text:
<?php
abstract class qCal_DateTime_Recur_Rule {

	/**
	 * @var array The sub-rules of this rule.
	 */
	protected $rules = array();
	/**
	 * @var mixed The value of this rule
	 */
	protected $value;
	/**
	 * Constructor
	 * @param The value of the rule. If this is a ByMonth rule, then 1 would mean January
	 */
	public function __construct($value) {

		$this->value = $value;

	}
	/**
	 * Attach rules to this rule. For instance, if this is a byMonth rule, then
	 * we can attach byDay rules like "-1SU" for the last Sunday of the month.
	 */
	public function attach(qCal_DateTime_Recur_Rule $rule) {

		$this->rules[] = $rule;

	}
	/**
	 * Creates the recurrences for this rule. Left to children to do this.
	 */
	abstract public function getRecurrences();

}


text:
package domain

import "testing"
import "time"

func TestCreateNews(t *testing.T) {
	cases := []struct {
		inTitle, inContent string
		want               News
	}{
		{"", "", News{Title: "", Content: "", Date: now().Round(time.Minute)}},
		{"hello", "world", News{Title: "hello", Content: "world", Date: now().Round(time.Minute)}},
	}

	for _, c := range cases {
		got := *CreateNewsItem(c.inTitle, c.inContent)
		got.Date = got.Date.Round(time.Minute)
		if got != c.want {
			t.Errorf("CreateNews(%q, %q) == %q, want %q", c.inTitle, c.inContent, got, c.want)
		}
	}
}


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="@android:style/Theme.Holo.Light">
        <!-- Customize your theme here. -->
    </style>

    <style name="CustomActionBarTheme" parent="@android:style/Theme.Holo.Light">
        <!-- Customize your theme here. -->
        <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>

    <!-- ActionBar styles -->
    <style name="MyActionBar"
        parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
        <item name="android:background">#FFBB33</item>
    </style>

</resources>


text:
<?php

require_once('loader.php');

$addSuccess = false;
$updateSuccess = false;
$errorMessage = '';

if(isset($_POST['studentSubmitButton']) && $_POST['studentSubmitButton'] == 'Update Student') {

    $studentBllObj = new StudentBLL();
    $studentId = $_POST['studentId'];
    $studentName = $_POST['studentName'];
    $studentRoll = $_POST['studentRoll'];
    $studentEmail = $_POST['studentEmail'];
    $studentDateOfBirth = $_POST['studentDateOfBirth'];

    $aStudent = new StudentDTO($studentId, $studentRoll, $studentName, $studentEmail, $studentDateOfBirth);
    $updateResult = $studentBllObj->UpdateStudent($aStudent);

    if($updateResult > 0) {
        $updateSuccess = true;
    } else {
        if ($studentBllObj->errorMessage != '') {
            $errorMessage = $studentBllObj->errorMessage;
        } else {
            $errorMessage = 'Record can\'t be updated. Operation failed.';
        }
    }

} elseif(isset($_GET['id']) && (int)$_GET['id'] >0) {

    $studentId = (int)$_GET['id'];
    $action = '';
    if (isset($_GET['action'])) {
        $action = $_GET['action'];
    }

    $studentBllObj = new StudentBLL();
    $aStudent = $studentBllObj->GetStudent($studentId);

    if ($action == 'add') {
        $addSuccess = true;
    }

} else {
    header("Location: index.php");
}

$pageTitle = "Edit Student";
include_once("Templates/header.php");

?>

Edit Student

    <?php if ($addSuccess === true): ?>

Record added successfully.

    <?php endif; ?>
    <?php if ($updateSuccess === true): ?>

Record updated successfully.

    <?php endif; ?>
    <?php if ($errorMessage != ''): ?>

<?php echo $errorMessage; ?>

    <?php endif; ?>

    <form action="edit.php" method="post" name="studentInfoForm" id="studentInfoForm" class="form-horizontal">

            Name

                <input type="text" value="<?php echo $aStudent->GetName(); ?>" name="studentName" id="studentName" class="form-control" placeholder="Name" />

            Roll

                <input type="text" value="<?php echo $aStudent->GetRoll(); ?>" name="studentRoll" id="studentRoll" class="form-control" placeholder="Roll" />

            Email

                <input type="email" value="<?php echo $aStudent->GetEmail(); ?>" name="studentEmail" id="studentEmail" class="form-control" placeholder="Email" />

            Date Of Birth

                <input type="text" value="<?php echo $aStudent->GetDateOfBirth(); ?>" name="studentDateOfBirth" id="studentDateOfBirth" class="form-control" placeholder="Date Of Birth" />

        <input type="hidden" value="<?php echo $aStudent->GetId(); ?>" name="studentId" id="studentId" />

                <input type="submit" name="studentSubmitButton" id="studentSubmitButton" value="Update Student" class="btn  btn-primary" />

    </form>

<?php include_once("Templates/footer.php"); ?>


text:
var path        = require('path'),
    gulp        = require('gulp'),
    gutil       = require('gulp-util'),
    mirror      = require('gulp-mirror'),
    uglify      = require('gulp-uglify'),
    rename      = require('gulp-rename'),
    source      = require('vinyl-source-stream'),
    sourcemaps  = require('gulp-sourcemaps'),
    buffer      = require('vinyl-buffer'),
    browserify  = require('browserify'),
    watchify    = require('watchify'),
    handleErrors = require('../util/handleErrors');

// TODO - Concat license header to dev/prod build files.
function rebundle(devBundle) {
    if (devBundle) {
        gutil.log('Starting dev rebundle...');
    }

    var debug, min;

    debug = sourcemaps.init({loadMaps: true});
    debug.pipe(sourcemaps.write('./', {sourceRoot: './'}))
        .pipe(gulp.dest(paths.out));

    min = rename({ suffix: '.min' });
    min.pipe(sourcemaps.init({loadMaps: true}))
        .pipe(uglify())
        .pipe(sourcemaps.write('./', {sourceRoot: './', addComment: false}))
        .pipe(gulp.dest(paths.out));

    var stream = this.bundle()
        .on('error', handleErrors.handler)
        .pipe(handleErrors())
        .pipe(source('pixi.js'))
        .pipe(buffer());

    if (devBundle) {
        return stream.pipe(debug).once('end', function () {
            gutil.log('Dev rebundle complete.');
        });
    }
    else {
        return stream.pipe(mirror(debug, min));
    }
}

function createBundler(args) {
    args = args || {};
    args.debug = true;
    args.standalone = 'PIXI';

    var bundle = browserify(paths.jsEntry, args),
        argv = require('minimist')(process.argv.slice(2)),
        exclude = (argv.exclude || []).concat(argv.e || []);

    for (var i = 0; i < exclude.length; ++i) {
        bundle.ignore(require.resolve('../../src/' + exclude[i]));
    }

    return bundle;
}

function watch(onUpdate) {
    var bundler = watchify(createBundler(watchify.args));

    bundler.on('update', function () {
        var bundle = rebundle.call(this, true);

        if (onUpdate) {
            bundle.on('end', onUpdate);
        }
    });

    return rebundle.call(bundler);
}

module.exports = function bundle() {
    return rebundle.call(createBundler());
};

module.exports.watch = watch;
module.exports.rebundle = rebundle;
module.exports.createBundler = createBundler;


text:
<?php

namespace Utill\MQ\Factory;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class FactoryServicePageLog  implements FactoryInterface{

    public function createService(ServiceLocatorInterface $serviceLocator) {

        $publicKey = $serviceLocator->get('servicePublicKeyReader');

        $routeMatch = $serviceLocator->get('Application')->getMvcEvent()->getRouteMatch();
        $controller = $routeMatch->getParam('controller');
        $action = $routeMatch->getParam('action');

        $request = $serviceLocator->get('Request');
        $uri = $request->getUri();
        $scheme = $uri->getScheme();
        $host = $uri->getHost();
        $base = sprintf('%s://%s', $scheme, $host);

        $remoteAddr = $request->getServer('REMOTE_ADDR');
        $params = $request->getContent();
        $method = $request->getMethod();

        /**
        * sends login info to message queue
        * @author Mustafa Zeynel Dağlı
        * @todo after tests ,  thif feature will be added as a service manager entity
        */
       $PageEntryLogMQ = new \Utill\MQ\PageEntryLogMQ();
       $PageEntryLogMQ->setChannelProperties(array('queue.name' => \Utill\MQ\AbstractMQ::PAGE_ENTRY_LOG_QUEUE_NAME));
       $message = new \Utill\MQ\MessageMQ\MQMessagePageEntryLog();
       ;

       $message->setMessageBody(array('message' => 'Kullanıcı sayfa giris log servis!',
                                      //'s_date'  => date('l jS \of F Y h:i:s A'),
                                      'log_datetime'  => date('Y-m-d G:i:s '),
                                      'pk' => $publicKey,
                                      'url' => $base,
                                      'path' => $controller.'/'.$action,
                                      'method' => $method,
                                      'ip' => $remoteAddr,
                                      'params' => serialize($params),
                                      'type_id' => \Utill\MQ\MessageMQ\MQMessagePageEntryLog::PAGE_ENTRY_OPERATIN,
                                      'logFormat' => 'database'));
       $message->setMessageProperties(array('delivery_mode' => 2,
                                            'content_type' => 'application/json'));
       $PageEntryLogMQ->setMessage($message->setMessage());
       $PageEntryLogMQ->basicPublish();

        return true;

    }

}


text:
package af;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@SpringBootApplication
@ConfigurationPropertiesScan("af.props")
public class CfgpropsApplication {

	public static void main(String[] args) {
		SpringApplication.run(CfgpropsApplication.class, args);
	}
}


text:
CREATE TABLE ACT_GE_PROPERTY
(
    NAME_                          NVARCHAR(64),
    VALUE_                         NVARCHAR(300),
    REV_                           INT,
    CONSTRAINT ACT_GE_PROPERTY_PK PRIMARY KEY (NAME_)
) ENGINE=InnoDB;

CREATE TABLE ACT_GE_BYTEARRAY
(
    ID_                            NVARCHAR(64),
    REV_                           INT,
    NAME_                          NVARCHAR(255),
    DEPLOYMENT_ID_                 NVARCHAR(64),
    BYTES_                         LONGBLOB,
    GENERATED_                     BIT,
    CONSTRAINT ACT_GE_BYTEARRAY_PK PRIMARY KEY (ID_)
) ENGINE=InnoDB;

CREATE TABLE ACT_RE_DEPLOYMENT
(
    ID_                            NVARCHAR(64),
    NAME_                          NVARCHAR(255),
    CATEGORY_                      NVARCHAR(255),
    TENANT_ID_                     NVARCHAR(255)             DEFAULT '',
    DEPLOY_TIME_                   DATETIME,
    CONSTRAINT ACT_RE_DEPLOYMENT_PK PRIMARY KEY (ID_)
) ENGINE=InnoDB;

CREATE TABLE ACT_RE_MODEL
(
    ID_                            NVARCHAR(64)              NOT NULL,
    REV_                           INT,
    NAME_                          NVARCHAR(255),
    KEY_                           NVARCHAR(255),
    CATEGORY_                      NVARCHAR(255),
    CREATE_TIME_                   DATETIME,
    LAST_UPDATE_TIME_              DATETIME,
    VERSION_                       INT,
    META_INFO_                     LONGTEXT,
    DEPLOYMENT_ID_                 NVARCHAR(64),
    EDITOR_SOURCE_VALUE_ID_        NVARCHAR(64),
    EDITOR_SOURCE_EXTRA_VALUE_ID_  NVARCHAR(64),
    TENANT_ID_                     NVARCHAR(255)             DEFAULT '',
    CONSTRAINT ACT_RE_MODEL_PK PRIMARY KEY (ID_)
) ENGINE=InnoDB;

CREATE TABLE ACT_RU_EXECUTION
(
    ID_                            NVARCHAR(64),
    REV_                           INT,
    PROC_INST_ID_                  NVARCHAR(64),
    BUSINESS_KEY_                  NVARCHAR(255),
    PARENT_ID_                     NVARCHAR(64),
    PROC_DEF_ID_                   NVARCHAR(64),
    SUPER_EXEC_                    NVARCHAR(64),
    ACT_ID_                        NVARCHAR(255),
    IS_ACTIVE_                     BIT,
    IS_CONCURRENT_                 BIT,
    IS_SCOPE_                      BIT,
    IS_EVENT_SCOPE_                BIT,
    SUSPENSION_STATE_              INT,
    CACHED_ENT_STATE_              INT,
    TENANT_ID_                     NVARCHAR(255)             DEFAULT '',
    NAME_                          NVARCHAR(255),
    LOCK_TIME_                     DATETIME,
    CONSTRAINT ACT_RU_EXECUTION_PK PRIMARY KEY (ID_)
) ENGINE=InnoDB;

CREATE TABLE ACT_RU_JOB
(
    ID_                            NVARCHAR(64)              NOT NULL,
    REV_                           INT,
    TYPE_                          NVARCHAR(255)             NOT NULL,
    LOCK_EXP_TIME_                 DATETIME,
    LOCK_OWNER_                    NVARCHAR(255),
    EXCLUSIVE_                     BIT,
    EXECUTION_ID_                  NVARCHAR(64),
    PROCESS_INSTANCE_ID_           NVARCHAR(64),
    PROC_DEF_ID_                   NVARCHAR(64),
    RETRIES_                       INT,
    EXCEPTION_STACK_ID_            NVARCHAR(64),
    EXCEPTION_MSG_                 LONGTEXT,
    DUEDATE_                       DATETIME,
    REPEAT_                        NVARCHAR(255),
    HANDLER_TYPE_                  NVARCHAR(255),
    HANDLER_CFG_                   LONGTEXT,
    TENANT_ID_                     NVARCHAR(255)             DEFAULT '',
    CONSTRAINT ACT_RU_JOB_PK PRIMARY KEY (ID_)
) ENGINE=InnoDB;

CREATE TABLE ACT_RE_PROCDEF
(
    ID_                            NVARCHAR(64)              NOT NULL,
    REV_                           INT,
    CATEGORY_                      NVARCHAR(255),
    NAME_                          NVARCHAR(255),
    KEY_                           NVARCHAR(255)             NOT NULL,
    VERSION_                       INT                       NOT NULL,
    DEPLOYMENT_ID_                 NVARCHAR(64),
    RESOURCE_NAME_                 LONGTEXT,
    DGRM_RESOURCE_NAME_            LONGTEXT,
    DESCRIPTION_                   LONGTEXT,
    HAS_START_FORM_KEY_            BIT,
    HAS_GRAPHICAL_NOTATION_        BIT,
    SUSPENSION_STATE_              INT,
    TENANT_ID_                     NVARCHAR(255)             DEFAULT '',
    CONSTRAINT ACT_RE_PROCDEF_PK PRIMARY KEY (ID_)
) ENGINE=InnoDB;

CREATE TABLE ACT_RU_TASK
(
    ID_                            NVARCHAR(64),
    REV_                           INT,
    EXECUTION_ID_                  NVARCHAR(64),
    PROC_INST_ID_                  NVARCHAR(64),
    PROC_DEF_ID_                   NVARCHAR(64),
    NAME_                          NVARCHAR(255),
    PARENT_TASK_ID_                NVARCHAR(64),
    DESCRIPTION_                   LONGTEXT,
    TASK_DEF_KEY_                  NVARCHAR(255),
    OWNER_                         NVARCHAR(255),
    ASSIGNEE_                      NVARCHAR(255),
    DELEGATION_                    NVARCHAR(64),
    PRIORITY_                      INT,
    CREATE_TIME_                   DATETIME,
    DUE_DATE_                      DATETIME,
    CATEGORY_                      NVARCHAR(255),
    SUSPENSION_STATE_              INT,
    TENANT_ID_                     NVARCHAR(255)             DEFAULT '',
    FORM_KEY_                      NVARCHAR(255),
    CONSTRAINT ACT_RU_TASK_PK PRIMARY KEY (ID_)
) ENGINE=InnoDB;

CREATE TABLE ACT_RU_IDENTITYLINK
(
    ID_                            NVARCHAR(64),
    REV_                           INT,
    GROUP_ID_                      NVARCHAR(255),
    TYPE_                          NVARCHAR(255),
    USER_ID_                       NVARCHAR(255),
    TASK_ID_                       NVARCHAR(64),
    PROC_INST_ID_                  NVARCHAR(64),
    PROC_DEF_ID_                   NVARCHAR(64),
    CONSTRAINT ACT_RU_IDENTITYLINK_PK PRIMARY KEY (ID_)
) ENGINE=InnoDB;

CREATE TABLE ACT_RU_VARIABLE
(
    ID_                            NVARCHAR(64)              NOT NULL,
    REV_                           INT,
    TYPE_                          NVARCHAR(255)             NOT NULL,
    NAME_                          NVARCHAR(255)             NOT NULL,
    EXECUTION_ID_                  NVARCHAR(64),
    PROC_INST_ID_                  NVARCHAR(64),
    TASK_ID_                       NVARCHAR(64),
    BYTEARRAY_ID_                  NVARCHAR(64),
    DOUBLE_                        DOUBLE PRECISION,
    LONG_                          BIGINT,
    TEXT_                          LONGTEXT,
    TEXT2_                         LONGTEXT,
    CONSTRAINT ACT_RU_VARIABLE_PK PRIMARY KEY (ID_)
) ENGINE=InnoDB;

CREATE TABLE ACT_RU_EVENT_SUBSCR
(
    ID_                            NVARCHAR(64)              NOT NULL,
    REV_                           INT,
    EVENT_TYPE_                    NVARCHAR(255)             NOT NULL,
    EVENT_NAME_                    NVARCHAR(255),
    EXECUTION_ID_                  NVARCHAR(64),
    PROC_INST_ID_                  NVARCHAR(64),
    ACTIVITY_ID_                   NVARCHAR(64),
    CONFIGURATION_                 NVARCHAR(255),
    CREATED_                       DATETIME                  NOT NULL,
    PROC_DEF_ID_                   NVARCHAR(64),
    TENANT_ID_                     NVARCHAR(255)             DEFAULT '',
    CONSTRAINT ACT_RU_EVENT_SUBSCR_PK PRIMARY KEY (ID_)
) ENGINE=InnoDB;

CREATE TABLE ACT_EVT_LOG
(
    LOG_NR_                        BIGINT                   AUTO_INCREMENT,
    TYPE_                          NVARCHAR(64),
    PROC_DEF_ID_                   NVARCHAR(64),
    PROC_INST_ID_                  NVARCHAR(64),
    EXECUTION_ID_                  NVARCHAR(64),
    TASK_ID_                       NVARCHAR(64),
    TIME_STAMP_                    DATETIME                  NOT NULL,
    USER_ID_                       NVARCHAR(255),
    DATA_                          LONGBLOB,
    LOCK_OWNER_                    NVARCHAR(255),
    LOCK_TIME_                     DATETIME,
    IS_PROCESSED_                  SMALLINT                  DEFAULT 0,
    CONSTRAINT ACT_EVT_LOG_PK PRIMARY KEY (LOG_NR_)
) ENGINE=InnoDB;

CREATE INDEX ACT_IDX_EXEC_BUSKEY ON ACT_RU_EXECUTION (BUSINESS_KEY_);

CREATE INDEX ACT_IDX_TASK_CREATE ON ACT_RU_TASK (CREATE_TIME_);

CREATE INDEX ACT_IDX_IDENT_LNK_USER ON ACT_RU_IDENTITYLINK (USER_ID_);

CREATE INDEX ACT_IDX_IDENT_LNK_GROUP ON ACT_RU_IDENTITYLINK (GROUP_ID_);

CREATE INDEX ACT_IDX_EVENT_SUBSCR_CONFIG_ ON ACT_RU_EVENT_SUBSCR (CONFIGURATION_);

CREATE INDEX ACT_IDX_VARIABLE_TASK_ID ON ACT_RU_VARIABLE (TASK_ID_);

CREATE INDEX ACT_IDX_BYTEAR_DEPL ON ACT_GE_BYTEARRAY (DEPLOYMENT_ID_);

ALTER TABLE ACT_GE_BYTEARRAY ADD CONSTRAINT ACT_FK_BYTEARR_DEPL FOREIGN KEY (DEPLOYMENT_ID_) REFERENCES ACT_RE_DEPLOYMENT (ID_);

ALTER TABLE ACT_RE_PROCDEF ADD CONSTRAINT ACT_UNIQ_PROCDEF UNIQUE (KEY_, VERSION_, TENANT_ID_);

CREATE INDEX ACT_IDX_EXE_PROCINST ON ACT_RU_EXECUTION (PROC_INST_ID_);

ALTER TABLE ACT_RU_EXECUTION ADD CONSTRAINT ACT_FK_EXE_PROCINST FOREIGN KEY (PROC_INST_ID_) REFERENCES ACT_RU_EXECUTION (ID_);

CREATE INDEX ACT_IDX_EXE_PARENT ON ACT_RU_EXECUTION (PARENT_ID_);

ALTER TABLE ACT_RU_EXECUTION ADD CONSTRAINT ACT_FK_EXE_PARENT FOREIGN KEY (PARENT_ID_) REFERENCES ACT_RU_EXECUTION (ID_);

CREATE INDEX ACT_IDX_EXE_SUPER ON ACT_RU_EXECUTION (SUPER_EXEC_);

ALTER TABLE ACT_RU_EXECUTION ADD CONSTRAINT ACT_FK_EXE_SUPER FOREIGN KEY (SUPER_EXEC_) REFERENCES ACT_RU_EXECUTION (ID_);

CREATE INDEX ACT_IDX_EXE_PROCDEF ON ACT_RU_EXECUTION (PROC_DEF_ID_);

ALTER TABLE ACT_RU_EXECUTION ADD CONSTRAINT ACT_FK_EXE_PROCDEF FOREIGN KEY (PROC_DEF_ID_) REFERENCES ACT_RE_PROCDEF (ID_);

CREATE INDEX ACT_IDX_TSKASS_TASK ON ACT_RU_IDENTITYLINK (TASK_ID_);

ALTER TABLE ACT_RU_IDENTITYLINK ADD CONSTRAINT ACT_FK_TSKASS_TASK FOREIGN KEY (TASK_ID_) REFERENCES ACT_RU_TASK (ID_);

CREATE INDEX ACT_IDX_ATHRZ_PROCEDEF ON ACT_RU_IDENTITYLINK (PROC_DEF_ID_);

ALTER TABLE ACT_RU_IDENTITYLINK ADD CONSTRAINT ACT_FK_ATHRZ_PROCEDEF FOREIGN KEY (PROC_DEF_ID_) REFERENCES ACT_RE_PROCDEF (ID_);

CREATE INDEX ACT_IDX_IDL_PROCINST ON ACT_RU_IDENTITYLINK (PROC_INST_ID_);

ALTER TABLE ACT_RU_IDENTITYLINK ADD CONSTRAINT ACT_FK_IDL_PROCINST FOREIGN KEY (PROC_INST_ID_) REFERENCES ACT_RU_EXECUTION (ID_);

CREATE INDEX ACT_IDX_TASK_EXEC ON ACT_RU_TASK (EXECUTION_ID_);

ALTER TABLE ACT_RU_TASK ADD CONSTRAINT ACT_FK_TASK_EXE FOREIGN KEY (EXECUTION_ID_) REFERENCES ACT_RU_EXECUTION (ID_);

CREATE INDEX ACT_IDX_TASK_PROCINST ON ACT_RU_TASK (PROC_INST_ID_);

ALTER TABLE ACT_RU_TASK ADD CONSTRAINT ACT_FK_TASK_PROCINST FOREIGN KEY (PROC_INST_ID_) REFERENCES ACT_RU_EXECUTION (ID_);

CREATE INDEX ACT_IDX_TASK_PROCDEF ON ACT_RU_TASK (PROC_DEF_ID_);

ALTER TABLE ACT_RU_TASK ADD CONSTRAINT ACT_FK_TASK_PROCDEF FOREIGN KEY (PROC_DEF_ID_) REFERENCES ACT_RE_PROCDEF (ID_);

CREATE INDEX ACT_IDX_VAR_EXE ON ACT_RU_VARIABLE (EXECUTION_ID_);

ALTER TABLE ACT_RU_VARIABLE ADD CONSTRAINT ACT_FK_VAR_EXE FOREIGN KEY (EXECUTION_ID_) REFERENCES ACT_RU_EXECUTION (ID_);

CREATE INDEX ACT_IDX_VAR_PROCINST ON ACT_RU_VARIABLE (PROC_INST_ID_);

ALTER TABLE ACT_RU_VARIABLE ADD CONSTRAINT ACT_FK_VAR_PROCINST FOREIGN KEY (PROC_INST_ID_) REFERENCES ACT_RU_EXECUTION (ID_);

CREATE INDEX ACT_IDX_VAR_BYTEARRAY ON ACT_RU_VARIABLE (BYTEARRAY_ID_);

ALTER TABLE ACT_RU_VARIABLE ADD CONSTRAINT ACT_FK_VAR_BYTEARRAY FOREIGN KEY (BYTEARRAY_ID_) REFERENCES ACT_GE_BYTEARRAY (ID_);

CREATE INDEX ACT_IDX_JOB_EXCEPTION ON ACT_RU_JOB (EXCEPTION_STACK_ID_);

ALTER TABLE ACT_RU_JOB ADD CONSTRAINT ACT_FK_JOB_EXCEPTION FOREIGN KEY (EXCEPTION_STACK_ID_) REFERENCES ACT_GE_BYTEARRAY (ID_);

CREATE INDEX ACT_IDX_EVENT_SUBSCR ON ACT_RU_EVENT_SUBSCR (EXECUTION_ID_);

ALTER TABLE ACT_RU_EVENT_SUBSCR ADD CONSTRAINT ACT_FK_EVENT_EXEC FOREIGN KEY (EXECUTION_ID_) REFERENCES ACT_RU_EXECUTION (ID_);

CREATE INDEX ACT_IDX_MODEL_SOURCE ON ACT_RE_MODEL (EDITOR_SOURCE_VALUE_ID_);

ALTER TABLE ACT_RE_MODEL ADD CONSTRAINT ACT_FK_MODEL_SOURCE FOREIGN KEY (EDITOR_SOURCE_VALUE_ID_) REFERENCES ACT_GE_BYTEARRAY (ID_);

CREATE INDEX ACT_IDX_MODEL_SOURCE_EXTRA ON ACT_RE_MODEL (EDITOR_SOURCE_EXTRA_VALUE_ID_);

ALTER TABLE ACT_RE_MODEL ADD CONSTRAINT ACT_FK_MODEL_SOURCE_EXTRA FOREIGN KEY (EDITOR_SOURCE_EXTRA_VALUE_ID_) REFERENCES ACT_GE_BYTEARRAY (ID_);

CREATE INDEX ACT_IDX_MODEL_DEPLOYMENT ON ACT_RE_MODEL (DEPLOYMENT_ID_);

ALTER TABLE ACT_RE_MODEL ADD CONSTRAINT ACT_FK_MODEL_DEPLOYMENT FOREIGN KEY (DEPLOYMENT_ID_) REFERENCES ACT_RE_DEPLOYMENT (ID_);


text:
class CScriptCfg
{
public:
	string	strScriptBetid;
	string	strSrcriptDarkid;
	string	m_ipoScritptid;
	string m_redpacketScriptid;
};

class CNewestScriptCfg
{
public:
	string	strNewScriptBetid;
	string	strNewSrcriptRedPacektid;
	string	strNewipoScritptid;
};

class CMainCfg
{
public:
	CMainCfg()
	{
		bStartServer = false;
		IntIsChinese = -1;
	}

	bool	bStartServer;
	int	 IntIsChinese;

	string	strServerCfgName;
};

class CDarkTxCfg
{
public:
	INT64	SendBuyernFee;
	INT64	SendSellernFee;
	INT64	SendBuyerConfirednFee;
	INT64	SendBuyerCancelnFee;
};

class CAnonmyCfg
{
public:
	string	strBinPath;
	string	strSendID;
	string	strRecvID1;
	string	strRecvID2;
	int		nMoney;
	int		nHeight;
	int		nFee;
};

class CSesureTradeCfg
{
public:
	string	strBinPath;
	string strAddr;
	string strBuyerID;
	string strSellerID;
	string strArID;
	int nTxFee;
	int nHeight;
	int nDeposite;
	int nPay;
	int nMaxFine;
	int nFine;
	int nArFee;
};

class CP2PBetCfg
{
public:
	INT64	SendBetFee;
	INT64	AcceptBetnFee;
	INT64	OpenBetnFee;
	INT64	GetAppAmountnFee;
	INT64   GetRechangeFee;
};
class CRedPacketCfg
{
public:
	INT64	SendRedPacketCommFee;
	INT64	AcceptRedPacketCommFee;
	INT64	SendRedPacketSpecailFee;
	INT64	AcceptRedPacketSpecailFee;
};

class CRedPacketStepCfg
{
public:
	INT64	SendRedPacketCommStep;
	INT64	AcceptRedPacketCommStep;
	INT64	SendRedPacketSpecailStep;
	INT64	AcceptRedPacketSpecailStep;
};

class CP2PBetStepCfg
{
public:
	INT64	SendBetStep;
	INT64	AcceptBetnStep;
	INT64	OpenBetnStep;
	INT64	GetAppAmountnStep;
	INT64   GetRechangeStep;
};

class CNetParamCfg
{
public:
	CString	server_ip;
	CString	rpc_port;
	CString server_ui_port;
	CString rpc_user;
	CString rpc_password;
};

class CLogParamCfg
{
public:
	vector<CString> vTag;
	BOOL   bPrintFileLine;
	BOOL   bPrinttimestamps;
	BOOL   bLogFlag;
	int    nMaxLogSize;         //ÈÕÖ¾Îļþ×î´óÖµ£¨µ¥Î»M£©
public:
	CLogParamCfg():bPrintFileLine(TRUE), bPrinttimestamps(TRUE), bLogFlag(TRUE), nMaxLogSize(100){
		vTag.clear();
	}
	~CLogParamCfg(){};
};

class CJsonConfigHelp
{
	DEFINE_SINGLETON(CJsonConfigHelp)
public:
	void Init();
	void ReadJsonConfig(const string& strFilePath);
	void GetMainCfgData(CMainCfg& mainCfg);
	void GetDarkCfgData(CDarkTxCfg& darkCfg);
	void GetAnonymCfgData(CAnonmyCfg& anonymCfg);
	void GetSesureTradeCfgData(CSesureTradeCfg& sesureCfg);
	void GetP2PBetCfgData(CP2PBetCfg& p2pCfg);
	void GetScriptCfgData(CScriptCfg& scriptCfg);
	void GetNetParamCfgData(CNetParamCfg& netparm);
	void GetLogParamCfg(CLogParamCfg &logCfg);
	void GetRedPacketCfgData(CRedPacketCfg &redpacketcfg);
	void GetClosConfig(int &closeconf);
	void GetPopTipsConfig(bool &flag);
	void AddItemString(const CString& strFilePath,CAutoComplete &m_comboxinput);
	string  GetConfigRootStr(const string& strFilePath);
	void GetNewestScriptData(CNewestScriptCfg &newScript);
	void GetRedPacketStep(CRedPacketStepCfg &redPackestep);
	void GetP2pBetStep(CP2PBetStepCfg &p2pbetstep);
	CONFIG_APP_DATA GetAppValue(const Json::Value &root);
	void GetListAppConfig(map<string,CONFIG_APP_DATA> &mlisapp);
	void GetHelpUrl(string &helpen,string &helpcn);
	void GetInsertAppId(map<string,string> &listappid);
private:
	void ReadMainCfgData(const Json::Value& root);
	void ReadSesureTradeCfgData(const Json::Value& root);
	void ReadDarkCoinCfgData(const Json::Value& root);
	void ReadP2PCfgData(const Json::Value& root);
	void ReadAnonymCfgData(const Json::Value& root);
	void ReadScriptCfgData(const Json::Value& root);
	void ReadNetParmCfgData(const Json::Value& root);
	void ReadLogParamCfg(const Json::Value &root);
	void ReadRedPacketCfgData(const Json::Value &root);
	void ReadCloseCfgData(const Json::Value &root);
	void ReadNewestCfgData(const Json::Value &root);
	void ReadRedPacketStep(const Json::Value &root);
	void ReadP2pBetStep(const Json::Value &root);
	void AddString(const Json::Value& root,CAutoComplete &m_comboxinput);
	void ReadListAppConfig(const Json::Value &root);
	void ReadHelpUrl(const Json::Value &root);
	void ReadInsertAppId(const Json::Value &root);
public:
	void ModifyAppFeeCfgData( Json::Value& root,const CString &LeaderKey,const CString &Key,const CString &KeyValue);

private:
	BOOL			m_bInvalid;
	CMainCfg		m_MainCfg;
	CDarkTxCfg		m_DarkCfg;
	CAnonmyCfg		m_AnonymCfg;
	CP2PBetCfg		m_P2PBetCfg;
	CSesureTradeCfg	m_SesureTradeCfg;
	CScriptCfg      m_Scriptid;
	CNetParamCfg    m_NetParam;
	CLogParamCfg     m_LogParamCfg;
	CRedPacketCfg    m_RedPacketCfg;
	int              m_close;                     /// 0 Ìáʾ¹Ø±Õ¶Ô»°¿ò 1 ²»Ìáʾ¹Ø±Õ¶Ô»°¿ò²¢ÇÒÒþ²Ø 2²»Ìáʾ¹Ø±Õ¶Ô»°¿ò²¢ÇҹرÕÇ®°ü
	CNewestScriptCfg m_newScript;
	CRedPacketStepCfg m_redPackestep;
	CP2PBetStepCfg    m_p2pbetstep;
	bool              m_poptip;
	map<string,CONFIG_APP_DATA> m_listapp;
	string            m_helpcn;
	string            m_helpen;
	map<string,string> m_listappid;
};


text:
module Projects
  module Boards
    class IssuesController < Boards::ApplicationController
      before_action :authorize_read_issue!, only: [:index]
      before_action :authorize_create_issue!, only: [:create]
      before_action :authorize_update_issue!, only: [:update]

      def index
        issues = ::Boards::Issues::ListService.new(project, current_user, filter_params).execute
        issues = issues.page(params[:page])

        render json: {
          issues: serialize_as_json(issues),
          size: issues.total_count
        }
      end

      def create
        service = ::Boards::Issues::CreateService.new(project, current_user, issue_params)
        issue = service.execute

        if issue.valid?
          render json: serialize_as_json(issue)
        else
          render json: issue.errors, status: :unprocessable_entity
        end
      end

      def update
        service = ::Boards::Issues::MoveService.new(project, current_user, move_params)

        if service.execute(issue)
          head :ok
        else
          head :unprocessable_entity
        end
      end

      private

      def issue
        @issue ||=
          IssuesFinder.new(current_user, project_id: project.id)
                      .execute
                      .where(iid: params[:id])
                      .first!
      end

      def authorize_read_issue!
        return render_403 unless can?(current_user, :read_issue, project)
      end

      def authorize_create_issue!
        return render_403 unless can?(current_user, :admin_issue, project)
      end

      def authorize_update_issue!
        return render_403 unless can?(current_user, :update_issue, issue)
      end

      def filter_params
        params.merge(board_id: params[:board_id], id: params[:list_id])
      end

      def move_params
        params.permit(:board_id, :id, :from_list_id, :to_list_id)
      end

      def issue_params
        params.require(:issue).permit(:title).merge(board_id: params[:board_id], list_id: params[:list_id], request: request)
      end

      def serialize_as_json(resource)
        resource.as_json(
          labels: true,
          only: [:iid, :title, :confidential, :due_date],
          include: {
            assignee: { only: [:id, :name, :username], methods: [:avatar_url] },
            milestone: { only: [:id, :title] }
          },
          user: current_user
        )
      end
    end
  end
end


text:
dumbster
========

Debian Packaging for dumbster


text:
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                Toggle navigation

            </button>

                J4LP {{ icon('key') }} AUTH

Back to Auth

            {% if current_user.is_authenticated() %}

{{ current_user.character_name }}

Logout

            {% else %}

Login

            {% endif %}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="author" content="Emanuel Eichhammer" />
<meta name="copyright" content="(C) 2013-2015 Emanuel Eichhammer" />
<title>QCPBarData Class Reference</title>
<link href="qt.css" rel="stylesheet" type="text/css"/>

Main Page ·
Class Overview ·
Hierarchy ·
All Classes ·
Special Pages

Public Functions |
Public Members

QCPBarData Class Reference

Holds the data of one single data point (one bar) for QCPBars.
 More...

Public Functions

 	QCPBarData ()

 	QCPBarData (double key, double value)

Public Members

double 	key

double 	value

Detailed Description

Holds the data of one single data point (one bar) for QCPBars.

The container for storing multiple data points is QCPBarDataMap.

The stored data is:

key: coordinate on the key axis of this bar

value: height coordinate on the value axis of this bar

See Also

QCPBarDataaMap

Constructor & Destructor Documentation

          QCPBarData::QCPBarData
          (
          	)

Constructs a bar data point with key and value set to zero.

          QCPBarData::QCPBarData
          (
          double
          key,

          double
          value

          )

Constructs a bar data point with the specified key and value.

The documentation for this class was generated from the following files:

src/plottables/plottable-bars.h

src/plottables/plottable-bars.cpp


text:
layout: post
title:  "Thoughts of pre-compiling CSS"
date:   2018-11-14 15:06:54 -0600
categories: SSG
comments: true
---

## Static Site Generators

### Personal thoughts
Lovely concept. Easy to get up and running and update. To abstact the backend helps the developer in most scenarios since YAGNI, you aint gonna need it. Myself is a classic example of adding unnessecary stuff to my project. A full stack react project with Redux, GraphQL and websockets in a kubernetes kluster for moms food blog with 5 yearly vistors anyone? SSGs makes things get done in an easy way — does more than enough for, in my case, most situations.


text:
export const FETCH_OPTIONS_REQUEST = 'SIMPR_FETCH_OPTIONS_REQUEST';
export const FETCH_OPTIONS_RESPONSE = 'SIMPR_FETCH_OPTIONS_RESPONSE';

const fireFetchOptionsRequest = () => ({
    type: FETCH_OPTIONS_REQUEST,
});

const fireFetchOptionsResponse = (options) => ({
    type: FETCH_OPTIONS_RESPONSE,
    payload: {
        ...options,
    },
});

export const fireFetchOptions = () =>
    (dispatch) => {
        dispatch(fireFetchOptionsRequest());

        chrome.storage.sync.get({
            permissions: {}
        }, ({ permissions }) => {
            dispatch(fireFetchOptionsResponse({
                permissions,
            }));
        });
    };


text:
#import <Cocoa/Cocoa.h>

@interface CheckpointAsSheetController : NSObject
{
    IBOutlet NSWindow *sheet;
    IBOutlet NSCell *formCell;
    BOOL didSave;
}

/** Shows the sheet, returns the entered name, or nil if the user pressed cancel */
- (NSString *)showSheet;

- (IBAction)save: (id)sender;
- (IBAction)cancel: (id)sender;

@end


text:
/*
 * Serve JSON to our AngularJS client
 */

// For a real app, you'd make database requests here.
// For this example, "data" acts like an in-memory "database"
var data = {
  "posts": [
    {
      "title": "Lorem ipsum",
      "text": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
    },
    {
      "title": "Sed egestas",
      "text": "Sed egestas, ante et vulputate volutpat, eros pede semper est, vitae luctus metus libero eu augue. Morbi purus libero, faucibus adipiscing, commodo quis, gravida id, est. Sed lectus."
    }
  ]
};

// GET

exports.posts = function (req, res) {
  var posts = [];
  data.posts.forEach(function (post, i) {
    posts.push({
      id: i,
      title: post.title,
      text: post.text.substr(0, 50) + '...'
    });
  });
  res.json({
    posts: posts
  });
};

exports.post = function (req, res) {
  var id = req.params.id;
  if (id >= 0 && id < data.posts.length) {
    res.json({
      post: data.posts[id]
    });
  } else {
    res.json(false);
  }
};

// POST

exports.addPost = function (req, res) {
  data.posts.push(req.body);
  res.json(req.body);
};

// PUT

exports.editPost = function (req, res) {
  var id = req.params.id;

  if (id >= 0 && id < data.posts.length) {
    data.posts[id] = req.body;
    res.json(true);
  } else {
    res.json(false);
  }
};

// DELETE

exports.deletePost = function (req, res) {
  var id = req.params.id;

  if (id >= 0 && id < data.posts.length) {
    data.posts.splice(id, 1);
    res.json(true);
  } else {
    res.json(false);
  }
};


text:
#include "gemat3d.h"
#pragma pack (push, 8)

#ifndef AXAUTOEXP
#ifdef AXAUTO15_DLL
	#define AXAUTOEXP __declspec(dllexport)
#else
	#define AXAUTOEXP __declspec(dllimport)
#endif
#endif

//#pragma warning(disable : 4290)

class AXAUTOEXP AcAxMatrix3d : public AcGeMatrix3d
{
public:
    // constructors
    AcAxMatrix3d();
    AcAxMatrix3d(const VARIANT* var) throw(HRESULT);
    AcAxMatrix3d(const VARIANT& var) throw(HRESULT);
    AcAxMatrix3d(const SAFEARRAY* safeArrayPt) throw(HRESULT);

    // equal operators
    AcAxMatrix3d& operator=(const VARIANT* var) throw(HRESULT);
    AcAxMatrix3d& operator=(const VARIANT& var) throw(HRESULT);
    AcAxMatrix3d& operator=(const SAFEARRAY* safeArrayPt) throw(HRESULT);

    // utilities
private:
    AcAxMatrix3d& fromSafeArray(const SAFEARRAY* safeArrayPt) throw(HRESULT);
    void validateVariant(const VARIANT* var, VARIANT* reliable) const throw(HRESULT);
};

#pragma pack (pop)
#endif


text:
namespace BullsAndCowsGame.Models.Commands
{
    using System;
    using BullsAndCowsGame.Interfaces;

    public abstract class Command : ICommand
    {
        public abstract void ProcessCommand(IGameEngine engine);
    }
}


text:
package org.apache.sling.mongodb.impl;

import java.util.Map;

import org.apache.sling.api.resource.ModifiableValueMap;
import org.apache.sling.api.resource.Resource;

public class ChangeableValueMap
    extends ReadableValueMap
    implements ModifiableValueMap {

    private final MongoDBResource resource;

    public ChangeableValueMap(final MongoDBResource resource) {
        super(resource.getProperties());
        this.resource = resource;
    }

    /**
     * @see java.util.Map#clear()
     */
    public void clear() {
        throw new UnsupportedOperationException("clear");
    }

    /**
     * @see java.util.Map#put(java.lang.Object, java.lang.Object)
     */
    public Object put(final String name, final Object value) {
        final Object oldValue = this.valueMap.get(name);
        final String key = MongoDBResourceProvider.propNameToKey(name);

        this.resource.getProperties().put(key, value);

        // update map and resource
        this.createValueMap(this.resource.getProperties());
        this.resource.changed();

        return oldValue;
    }

    /**
     * @see java.util.Map#putAll(java.util.Map)
     */
    public void putAll(final Map<? extends String, ? extends Object> m) {
        for(final Map.Entry<? extends String, ? extends Object> e : m.entrySet() ) {
            this.put(e.getKey(), e.getValue());
        }
    }

    /**
     * @see java.util.Map#remove(java.lang.Object)
     */
    public Object remove(final Object name) {
        final Object result = this.valueMap.get(name);
        if ( result != null ) {
            final String key = MongoDBResourceProvider.propNameToKey(name.toString());

            this.resource.getProperties().removeField(key);

            // update map and resource
            this.createValueMap(this.resource.getProperties());
            this.resource.changed();
        }
        return result;
    }

    protected MongoDBResource getResource() {
        return this.resource;
    }
}


text:
<?php

/**
 * @file Version.php
 * @brief This file contains the Version class.
 * @details
 * @author Filippo F. Fadda
 */

//! Root namespace.
namespace ReIndex;

/**
 * @brief This helper class is aimed to provide the software version number.
 * @details The version number is composed by a group of three numbers. The first one is the major release number, the
 * second one is the minor release number and the third one is used to identify the maintenance version.
 */
class Version extends \EoC\Version {

  const MAJOR = '0';       //!< Major release number.
  const MINOR = '23';      //!< Minor release number.
  const MAINTENANCE = '0'; //!< Maintenance release number (bug fixes only).

}


text:
namespace codegen
{

	using namespace parser;

	CodeGen::CodeGen(Parser& _p) : _parser(_p)
	{ }

	void CodeGen::generate()
	{
		visit(_parser.getRoot());
		pack.instructions.push_back(Instruction(VM_CODE::STOP, 0));
		pack.variablesSize = var_id.size();
	}

	void CodeGen::visit(Node* _node)
	{
		if (_node->asIdentifier())
			visit(_node->asIdentifier());
		else if (_node->asAssignment())
			visit(_node->asAssignment());
		else if (_node->asNumber())
			visit(_node->asNumber());
		else if (_node->asBinaryExpression())
			visit(_node->asBinaryExpression());
		else if (_node->asUnaryExpression())
			visit(_node->asUnaryExpression());
		else if (_node->asBlockExpression())
			visit(_node->asBlockExpression());
		else if (_node->asIfStmt())
			visit(_node->asIfStmt());
		else if (_node->asWhileStmt())
			visit(_node->asWhileStmt());
		else if (_node->asDefStmt())
			visit(_node->asDefStmt());
	}

	void CodeGen::visit(BlockExprNode* _node)
	{
		for (auto i = _node->children.begin(); i != _node->children.end(); ++i)
		{
			visit(*i);
			if ((*i)->asUnaryExpression() ||
				(*i)->asBinaryExpression() ||
				(*i)->asIdentifier() ||
				(*i)->asNumber())
				pack.instructions.push_back(Instruction(VM_CODE::Out, 0));
		}
	}

	void CodeGen::visit(UnaryExprNode* _node)
	{

	}

	void CodeGen::visit(BinaryExprNode* _node)
	{
		visit(_node->left);
		visit(_node->right);
		switch (_node->op)
		{
		case OperatorType::ADD:
			pack.instructions.push_back(Instruction(VM_CODE::Add, 0));
			break;
		case OperatorType::SUB:
			pack.instructions.push_back(Instruction(VM_CODE::Sub, 0));
			break;
		case OperatorType::MUL:
			pack.instructions.push_back(Instruction(VM_CODE::Mul, 0));
			break;
		case OperatorType::DIV:
			pack.instructions.push_back(Instruction(VM_CODE::Div, 0));
			break;
		case OperatorType::MOD:
			pack.instructions.push_back(Instruction(VM_CODE::Mod, 0));
			break;
		case OperatorType::POW:
			pack.instructions.push_back(Instruction(VM_CODE::Pow, 0));
			break;
		default:
			pack.instructions.push_back(Instruction(VM_CODE::Pop, 0));
			pack.instructions.push_back(Instruction(VM_CODE::Pop, 0));
		}
	}

	void CodeGen::visit(NumberNode* _node)
	{
		auto index = pack.constant.size();
		if (_node->maybeInt)
			pack.constant.push_back(Object(static_cast<int>(_node->value)));
		else
			pack.constant.push_back(Object(_node->value));
		pack.instructions.push_back(Instruction(VM_CODE::LoadC, index));
	}

	void CodeGen::visit(IdentifierNode* _node)
	{
		// read the value of the memory
		// and push to the top of the stack
		auto index = var_id[_node->name];
		pack.instructions.push_back(Instruction(VM_CODE::LoadV, index));
	}

	void CodeGen::visit(AssignmentNode* _node)
	{
		// find if the var is exisits
		// if not exisits add a possition for it
		auto _name = _node->identifier;
		unsigned int _index;
		if (var_id.find(_name) == var_id.end()) // not find
		{
			_index = var_id.size();
			var_id[_name] = _index;
		}
		else
			_index = var_id[_name];

		visit(_node->expression);
		pack.instructions.push_back(Instruction(VM_CODE::StoreV, _index));
	}

	void CodeGen::visit(IfStmtNode* _node)
	{
		// wait to finsih;
	}

	void CodeGen::visit(WhileStmtNode* _node)
	{
		// wait to finish
	}

	void CodeGen::visit(DefStmtNode* _node)
	{
		// wait to finish
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one or more
  ~ contributor license agreements.  See the NOTICE file distributed with
  ~ this work for additional information regarding copyright ownership.
  ~ The ASF licenses this file to You under the Apache License, Version 2.0
  ~ (the "License"); you may not use this file except in compliance with
  ~ the License.  You may obtain a copy of the License at
  ~
  ~    http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.stratio.spark</groupId>
    <artifactId>spark-parent_2.11</artifactId>
    <version>2.2.0.6-SNAPSHOT</version>

  </parent>

  <artifactId>spark-docker-integration-tests_2.11</artifactId>
  <packaging>jar</packaging>
  <name>Spark Project Docker Integration Tests</name>
  <url>http://spark.apache.org/</url>
  <properties>
    <sbt.project.name>docker-integration-tests</sbt.project.name>
  </properties>

  <repositories>
    <repository>
      <id>db</id>
      <url>https://app.camunda.com/nexus/content/repositories/public/</url>
      <releases>
        <enabled>true</enabled>
        <checksumPolicy>warn</checksumPolicy>
      </releases>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
      <groupId>com.spotify</groupId>
      <artifactId>docker-client</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpcore</artifactId>
      <scope>test</scope>
    </dependency>
    <!-- Necessary in order to avoid errors in log messages: -->
    <dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>18.0</version>
    </dependency>
    <dependency>
      <groupId>com.stratio.spark</groupId>
      <artifactId>spark-core_2.11</artifactId>
      <version>2.2.0.6-SNAPSHOT</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.stratio.spark</groupId>
      <artifactId>spark-core_2.11</artifactId>
      <version>2.2.0.6-SNAPSHOT</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.stratio.spark</groupId>
      <artifactId>spark-sql_2.11</artifactId>
      <version>2.2.0.6-SNAPSHOT</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.stratio.spark</groupId>
      <artifactId>spark-sql_2.11</artifactId>
      <version>2.2.0.6-SNAPSHOT</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.stratio.spark</groupId>
      <artifactId>spark-tags_2.11</artifactId>
      <version>2.2.0.6-SNAPSHOT</version>
      <type>test-jar</type>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.postgresql</groupId>
      <artifactId>postgresql</artifactId>
      <scope>test</scope>
    </dependency>
    <!-- Oracle ojdbc jar, used for oracle  integration suite for docker testing.
     See https://github.com/apache/spark/pull/11306 for background on why we need
     to use a an ojdbc jar for the testcase. The maven dependency here is commented
     because currently the maven repository does not contain the ojdbc jar mentioned.
     Once the jar is available in maven, this could be uncommented. -->
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc6</artifactId>
      <version>11.2.0.1.0</version>
      <scope>test</scope>
    </dependency>

    <!-- DB2 JCC driver manual installation instructions

       You can build this datasource if you:
        1) have the DB2 artifacts installed in a local repo and supply the URL:
          -Dmaven.repo.drivers=http://my.local.repo

        2) have a copy of the DB2 JCC driver and run the following commands :
          mvn install:install-file -Dfile=${path to db2jcc4.jar} \
            -DgroupId=com.ibm.db2 \
            -DartifactId=db2jcc4 \
            -Dversion=10.5 \
            -Dpackaging=jar

       Note: IBM DB2 JCC driver is available for download at
          http://www-01.ibm.com/support/docview.wss?uid=swg21363866
     -->
    <dependency>
      <groupId>com.ibm.db2.jcc</groupId>
      <artifactId>db2jcc4</artifactId>
      <version>10.5.0.5</version>
      <type>jar</type>
    </dependency>
  </dependencies>
</project>


text:
using System;

/// <summary>
/// System.Convert.ToDecimal(Single)
/// </summary>
public class ConvertToDecimal17
{
    #region Public Methods
    public bool RunTests()
    {
        bool retVal = true;

        TestLibrary.TestFramework.LogInformation("[Positive]");
        retVal = PosTest1() && retVal;
        retVal = PosTest2() && retVal;
        retVal = PosTest3() && retVal;

        return retVal;
    }

    #region Positive Test Cases
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Convert a random Single to decimal");

        try
        {
            Single i = TestLibrary.Generator.GetSingle(-55);
            decimal decimalValue = Convert.ToDecimal(i);
            if (decimalValue != (i as IConvertible).ToDecimal(null))
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,i is:" + i);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }

    public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Check a single which is  -.123");

        try
        {
            Single i = -.123f;
            decimal decimalValue = Convert.ToDecimal(i);
            if (decimalValue != -0.123m)
            {
                TestLibrary.TestFramework.LogError("003", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }

    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: Check a single which is  +.123");

        try
        {
            Single i = (Single)(+.123);
            decimal decimalValue = Convert.ToDecimal(i);
            if (decimalValue != 0.123m)
            {
                TestLibrary.TestFramework.LogError("005", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }
    #endregion

    #region Nagetive Test Cases
    #endregion
    #endregion

    public static int Main()
    {
        ConvertToDecimal17 test = new ConvertToDecimal17();

        TestLibrary.TestFramework.BeginTestCase("ConvertToDecimal17");

        if (test.RunTests())
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("PASS");
            return 100;
        }
        else
        {
            TestLibrary.TestFramework.EndTestCase();
            TestLibrary.TestFramework.LogInformation("FAIL");
            return 0;
        }
    }
}


text:
import React, { Component } from 'react'
import {
  View,
  StyleSheet,
  TextInput,
  TouchableOpacity,
  DeviceEventEmitter
} from 'react-native'
import Toast from 'antd-mobile/lib/toast'
import TouchID from 'react-native-touch-id'

import Container from '../components/Container'
import TextPingFang from '../components/TextPingFang'

import Storage from '../common/storage'
import { WIDTH } from '../common/styles';
import { Actions } from 'react-native-router-flux'

export default class AppAuth extends Component {

  state = {
    password: '',
    passwordConfirm: '',
    numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
    gotoApp: false,
    cancelValidate: false,
    pswOnly: false
  }

  async componentDidMount() {
    if (this.props.gotoApp) {
      this.setState({ gotoApp: true })
      DeviceEventEmitter.once('validateId', this._validateId.bind(this))
    }

    if (this.props.cancelValidate)
      this.setState({ cancelValidate: true })
  }

  async _validateId() {
    if (this.state.pswOnly) return

    try {
      const type = await TouchID.isSupported()
      if (type) {
        const isSucceed = await TouchID.authenticate('需要验证')
        if (isSucceed) {
          Actions.pop()
        }
      }
    } catch (err) {
      console.log(err)
      this.setState({ pswOnly: true })
    }
  }

  async _validate(password) {
    const appAuthPsw = await Storage.get('appAuthPsw')
    if (appAuthPsw !== password) {
      Toast.fail('密码错误', 1)
      this.setState({ password: '' })
    } else {
      if (this.state.cancelValidate) {
        this.props.cb()
      }
      Actions.pop()
    }
  }

  async _setPsw(num) {
    let { password, passwordConfirm, gotoApp, cancelValidate } = this.state

    // 设置密码
    if (password.length < 4) {
      password = password.concat(num)
      this.setState({password})

      // 验证密码
      if ((gotoApp || cancelValidate) && password.length === 4) {
        this._validate(password)
      }
      return
    }

    // 再次输入密码
    if (!gotoApp && !cancelValidate && password.length === 4 && passwordConfirm.length < 4) {
      passwordConfirm = passwordConfirm.concat(num)
      this.setState({passwordConfirm})

      if (passwordConfirm.length === 4) {
        if (password === passwordConfirm) {
          await Storage.set('appAuthPsw', password)
          await Storage.set('openAppAuth', true)
          this.props.cb()
          Actions.pop()
        } else {
          this.setState({isDifferent: true})
        }
      }
    }
  }

  _delete() {
    let { password, passwordConfirm } = this.state
    if (password.length && password.length < 4) {
      this.setState({password: password.slice(0, -1)})
    } else {
      this.setState({passwordConfirm: passwordConfirm.slice(0, -1), isDifferent: false})
    }
  }

  render() {
    return (
      <Container>
        <View style={styles.psw_container}>
          <TextInput
            style={styles.psw_item}
            secureTextEntry
            editable={false}
            underlineColorAndroid='transparent'
            value={this.state.password.length < 4 ? this.state.password[0] : this.state.passwordConfirm[0]}
          />
          <TextInput
            style={styles.psw_item}
            secureTextEntry
            editable={false}
            underlineColorAndroid='transparent'
            value={this.state.password.length < 4 ? this.state.password[1] : this.state.passwordConfirm[1]}
          />
          <TextInput
            style={styles.psw_item}
            secureTextEntry
            editable={false}
            underlineColorAndroid='transparent'
            value={this.state.password.length < 4 ? this.state.password[2] : this.state.passwordConfirm[2]}
          />
          <TextInput
            style={styles.psw_item}
            secureTextEntry
            editable={false}
            underlineColorAndroid='transparent'
            value={this.state.password.length < 4 ? this.state.password[3] : this.state.passwordConfirm[3]}
          />
        </View>

        <TextPingFang
          style={[
            styles.text_tip,
            {
              color: this.state.isDifferent ? '#f00' : '#000'
            }
          ]}
        >
          {
            (() => {
              if (this.state.gotoApp || this.state.cancelValidate) return '验证密码'
              return this.state.password.length < 4 ? '设置密码' : (this.state.isDifferent ? '密码不一致' : '再次输入密码')
            })()
          }
        </TextPingFang>

        <View style={styles.numbers_container}>
          {
            this.state.numbers.map(num => {
              return (
                <TouchableOpacity
                  key={num}
                  style={styles.num_container}
                  onPress={() => this._setPsw(num)}
                >
                  <TextPingFang style={styles.text_num}>{num}</TextPingFang>
                </TouchableOpacity>
              )
            })
          }
        </View>

        <View style={styles.btns_container}>
          <TouchableOpacity style={{display: this.state.gotoApp ? 'none' : 'flex'}} onPress={() => Actions.pop()}>
            <TextPingFang style={styles.text_btn}>取消</TextPingFang>
          </TouchableOpacity>
          <TouchableOpacity onPress={() => this._delete()}>
            <TextPingFang style={styles.text_btn}>删除</TextPingFang>
          </TouchableOpacity>
        </View>
      </Container>
    )
  }
}

const styles = StyleSheet.create({
  psw_container: {
    width: WIDTH - 48,
    marginTop: 48,
    height: 50,
    flexDirection: 'row',
    justifyContent: 'space-around'
  },
  psw_item: {
    width: 50,
    textAlign: 'center',
    borderBottomWidth: 4,
    borderBottomColor: '#F1F1F1'
  },
  text_tip: {
    marginTop: 16,
    fontSize: 16,
    fontWeight: '400'
  },
  numbers_container: {
    width: WIDTH - 95,
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-evenly'
  },
  num_container: {
    width: 80,
    height: 80,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 40,
    backgroundColor: '#f1f1f1',
    marginTop: 24,
  },
  text_num: {
    fontSize: 24,
    color: '#000',
    textAlign: 'center',
    fontWeight: '500'
  },
  btns_container: {
    width: WIDTH - 48,
    flexDirection: 'row',
    justifyContent: 'space-around'
  },
  text_btn: {
    fontSize: 18,
    fontWeight: '400',
    marginTop: 36
  }
})


text:
"""
elevator minigame.

walks the user through creating an elevator speech
"""
from django.contrib.auth import logout, authenticate, login
from django.shortcuts import render
from gateway.models.Elevator import Elevator, Elevator_Form
from gateway.models.venture import Venture
from django.db import transaction

def elevator_view(request):
    """render elevator_view(request) minigame."""
    form = Elevator_Form
    minigame = {
        "title": "Elevator- Minigame",
        "subtitle": "Coming Soon!",
        "is_elevator": "active"
    }

    return render(
        request,
        'minigame/elevator.html',
        dict(minigame=minigame)
    )
    """contains temp data for venture currently"""
    with transaction.atomic():
        venture = Venture(
            title="Murphee's Irish Coats",
            image="coat",
            progress=90,
            step="1",
            hook="Bringing the comfort and quality of Traditional Irish coats\
             to an Online International Exchange"
        )
        if request.method == 'POST':
            form = Elevator_Form(request.POST)
            if form.is_valid():
                elevator = form.save()
                venture.elevator = elevator
                venture.save()


text:
/**
 * @file
 * @author zdying
 */

var pkg = require('../../helpers/package');

module.exports = function parseLoaders(customLoaders){
    var loaders = [];

    if(!customLoaders || Array.isArray(customLoaders) === false){
        return customLoaders
    }

    customLoaders.forEach(function(loader, index){
        /*
         *  loaders: [
         *      // type1
         *      {loader: 'babel', test: /\.js$/},
         *      {
         *          // type2
         *          'dep1': function(dep1, dep1Path){
         *              return {loader: 'babel', test: /\.js$/}
         *          },
         *          // type3
         *          'dep2': {loader: 'babel', test: /\.js$/}
         *      }
         *  ]
         */

        if(loader.loader){
            // type1 ==> 直接使用loader
            installLoader(loader);
            log.debug('before change loader', JSON.stringify(loader));
            loader.loader = pkg.getPackagePath(loader.loader) || loader.loader;
            log.debug('after change loader', JSON.stringify(loader));
            loaders.push(loader);
        }else{
            // type2/type3 ==> 先安装,然后设置
            for(var denpendence in loader){
                if(loader.hasOwnProperty(denpendence)){
                    var currLoader = loader[denpendence];
                    var currLoaderType = typeof currLoader;
                    var loaderResult = null;

                    if(currLoaderType === 'function'){
                        // type2
                        loaderResult = installCustomDependencies(denpendence, 'loaders', currLoader);
                        log.debug('loader config is function:', currLoader);
                    }else if(currLoaderType === 'object' && currLoader !== null){
                        // type3
                        installCustomDependencies(denpendence, 'loaders', null);

                        log.debug('loader config is object:', JSON.stringify(currLoader));
                        loaderResult = currLoader
                    }

                    installLoader(loaderResult);

                    log.debug('before change loader:', JSON.stringify(loaderResult));
                    loaderResult.loader = pkg.getPackagePath(loaderResult.loader) || loaderResult.loader;
                    log.debug('after change loader:', JSON.stringify(loaderResult));

                    loaders.push(loaderResult)
                }
            }
        }
    });

    return loaders
};

function installLoader(loader){
    var loaderContent = loader.loader;
    var loaders = Array.isArray(loaderContent) ? loaderContent : loaderContent.split('!');
    var installed = false;
    // 需要安装的package
    var loadersName = loaders.map(function(name){
        var _name = name.split('?')[0];
        if(_name.indexOf('-loader') === -1){
            _name += '-loader';
        }

        var exists = pkg.checkIfPackageExist(_name.split('@')[0], _name.split('@')[1]);

        if(exists){
            return ''
        }else{
            return _name
        }
    });

    loadersName = loadersName.join(' ').trim();

    // 如果需要安装的模块不为空, 安装相应的模块
    if(loadersName !== ''){
        log.debug('packages that need to install:', loadersName);
        installed = pkg.installPackageAndDependencies(loadersName, 'loader')
    }

    return installed
}

function installCustomDependencies(pkgs, type, cbk){
    var installed = pkg.installPackageAndDependencies(pkgs, type);

    var params = pkgs.split(' ').map(function(pkgName){
        return pkg.getPackagePath(pkgName);
    });
    var modules = params.map(function(p){
        return require(p)
    });

    if(typeof cbk === 'function'){
        log.debug('call plugin config callback ...');
        var result = cbk.apply(null, modules.concat(params));
        log.debug('loader config callback result:', typeof result === 'function' ? result : JSON.stringify(result));

        return result
    }
}


text:
package org.jbb.permissions.impl.acl;

import org.apache.commons.lang3.EnumUtils;
import org.jbb.permissions.api.permission.PermissionType;
import org.jbb.permissions.impl.acl.dao.AclPermissionTypeRepository;
import org.jbb.permissions.impl.acl.model.AclPermissionTypeEntity;
import org.springframework.stereotype.Component;

import lombok.RequiredArgsConstructor;

@Component
@RequiredArgsConstructor
public class PermissionTypeTranslator {

    private final AclPermissionTypeRepository aclPermissionTypeRepository;

    public AclPermissionTypeEntity toEntity(PermissionType type) {
        return aclPermissionTypeRepository.findAllByName(type.name());
    }

    public PermissionType toApiModel(AclPermissionTypeEntity typeEntity) {
        return EnumUtils.getEnum(PermissionType.class, typeEntity.getName());
    }
}


text:
Jekyll-based website for UCSB CS16, for shared course materials.

* website: <https://ucsb-cs16.github.io>
* The theme currently being used can be find in the jekyll-theme value in `_config.yml`
* The navigation is set by the values in `_data/navigation.yml`

# Travis-CI

Build Status: [![Build Status](https://travis-ci.org/ucsb-cs16/ucsb-cs16.github.io.svg?branch=master)](https://travis-ci.org/ucsb-cs16/ucsb-cs16.github.io)

The continuous integration service [travis-ci.org](https://travis-ci.org) can be used to check whether a Github Pages site is
building properly, and if not, see the syntax errors.

The site for this repo is:  <https://travis-ci.org/ucsb-cs16/ucsb-cs16.github.io>

* At that site you can enable builds (if the logo shows grey for no info), or see a log of the latest build.
* Also, see the green dots, yellow dots, and red x's on the [Commit log of this repo](https://github.com/ucsb-cs16/ucsb-cs16.github.io/commits/master)
* [These instructions](https://docs.travis-ci.com/user/status-images/) explain how to add a Build Status logo to a README.md

To test locally:
* One time setup:
    * `git clone` the repo
    * Install rvm (the Ruby version manager)
    * Run `./setup.sh` to install correct ruby version, bundler version, and bundle the gems
* From then on, to test the site locally:
    * Run `./jekyll.sh
    * Point browser to <http://localhost:4000>


text:
"""Config flow for Landis+Gyr Heat Meter integration."""
from __future__ import annotations

import logging
import os

import async_timeout
import serial
import serial.tools.list_ports
from ultraheat_api import HeatMeterService, UltraheatReader
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_DEVICE
from homeassistant.exceptions import HomeAssistantError

from .const import DOMAIN, ULTRAHEAT_TIMEOUT

_LOGGER = logging.getLogger(__name__)

CONF_MANUAL_PATH = "Enter Manually"

STEP_USER_DATA_SCHEMA = vol.Schema(
    {
        vol.Required(CONF_DEVICE): str,
    }
)

class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle a config flow for Ultraheat Heat Meter."""

    VERSION = 1

    async def async_step_user(self, user_input=None):
        """Step when setting up serial configuration."""
        errors = {}

        if user_input is not None:
            if user_input[CONF_DEVICE] == CONF_MANUAL_PATH:
                return await self.async_step_setup_serial_manual_path()

            dev_path = await self.hass.async_add_executor_job(
                get_serial_by_id, user_input[CONF_DEVICE]
            )
            _LOGGER.debug("Using this path : %s", dev_path)

            try:
                return await self.validate_and_create_entry(dev_path)
            except CannotConnect:
                errors["base"] = "cannot_connect"

        ports = await self.get_ports()

        schema = vol.Schema({vol.Required(CONF_DEVICE): vol.In(ports)})
        return self.async_show_form(step_id="user", data_schema=schema, errors=errors)

    async def async_step_setup_serial_manual_path(self, user_input=None):
        """Set path manually."""
        errors = {}

        if user_input is not None:
            dev_path = user_input[CONF_DEVICE]
            try:
                return await self.validate_and_create_entry(dev_path)
            except CannotConnect:
                errors["base"] = "cannot_connect"

        schema = vol.Schema({vol.Required(CONF_DEVICE): str})
        return self.async_show_form(
            step_id="setup_serial_manual_path",
            data_schema=schema,
            errors=errors,
        )

    async def validate_and_create_entry(self, dev_path):
        """Try to connect to the device path and return an entry."""
        model, device_number = await self.validate_ultraheat(dev_path)

        _LOGGER.debug("Got model %s and device_number %s", model, device_number)
        await self.async_set_unique_id(device_number)
        self._abort_if_unique_id_configured()
        data = {
            CONF_DEVICE: dev_path,
            "model": model,
            "device_number": device_number,
        }
        return self.async_create_entry(
            title=model,
            data=data,
        )

    async def validate_ultraheat(self, port: str):
        """Validate the user input allows us to connect."""

        reader = UltraheatReader(port)
        heat_meter = HeatMeterService(reader)
        try:
            async with async_timeout.timeout(ULTRAHEAT_TIMEOUT):
                # validate and retrieve the model and device number for a unique id
                data = await self.hass.async_add_executor_job(heat_meter.read)
                _LOGGER.debug("Got data from Ultraheat API: %s", data)

        except Exception as err:
            _LOGGER.warning("Failed read data from: %s. %s", port, err)
            raise CannotConnect(f"Error communicating with device: {err}") from err

        _LOGGER.debug("Successfully connected to %s", port)
        return data.model, data.device_number

    async def get_ports(self) -> dict:
        """Get the available ports."""
        ports = await self.hass.async_add_executor_job(serial.tools.list_ports.comports)
        formatted_ports = {}
        for port in ports:
            formatted_ports[
                port.device
            ] = f"{port}, s/n: {port.serial_number or 'n/a'}" + (
                f" - {port.manufacturer}" if port.manufacturer else ""
            )
        formatted_ports[CONF_MANUAL_PATH] = CONF_MANUAL_PATH
        return formatted_ports

def get_serial_by_id(dev_path: str) -> str:
    """Return a /dev/serial/by-id match for given device if available."""
    by_id = "/dev/serial/by-id"
    if not os.path.isdir(by_id):
        return dev_path

    for path in (entry.path for entry in os.scandir(by_id) if entry.is_symlink()):
        if os.path.realpath(path) == dev_path:
            return path
    return dev_path

class CannotConnect(HomeAssistantError):
    """Error to indicate we cannot connect."""


text:
<PackageItem xmlns:tcm="http://www.tridion.com/ContentManager/5.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.sdltridion.com/ContentManager/ImportExport/Package/2013">
  <Data>
    <tcm:Data>
      <tcm:Title>test-experiment-example1-variant1</tcm:Title>
      <tcm:Type>Normal</tcm:Type>
      <tcm:Schema xlink:type="simple" xlink:title="News Article" xlink:href="/webdav/401%20Automated%20Test%20Parent/Building%20Blocks/Modules/Core/Editor/Schemas/News%20Article.xsd" IsMandatory="false" />
      <tcm:Content>
        <NewsArticle xmlns="http://www.sdl.com/web/schemas/core">
          <headline>test-experiment-example1-variant1-headline</headline>
          <articleBody>
            <subheading>test-experiment-example1-variant1-subheading</subheading>
            <content>

test-experiment-example1-variant1-content

test-experiment-example1-variant1-url</content>
          </articleBody>
        </NewsArticle>
      </tcm:Content>
      <tcm:Metadata>
        <Metadata xmlns="http://www.sdl.com/web/schemas/core">
          <standardMeta>
            <dateCreated>2014-08-18T12:12:42</dateCreated>
            <description>test-experiment-example1-variant1-meta-description</description>
            <name>test-experiment-example1-variant1-short-title</name>
            <introText>test-experiment-example1-variant1-intro-text</introText>
          </standardMeta>
        </Metadata>
      </tcm:Metadata>
      <tcm:IsBasedOnTridionWebSchema>true</tcm:IsBasedOnTridionWebSchema>
      <tcm:MultimediaType xlink:type="simple" xlink:title="" xlink:href="tcm:0-0-0" />
    </tcm:Data>
  </Data>
  <Dependencies>
    <Dependency dependencyType="Publication" itemUrl="/webdav/401%20Automated%20Test%20Parent" linkName="LocationInfo/ContextRepository" />
    <Dependency dependencyType="OrganizationalItemFolder" itemUrl="/webdav/401%20Automated%20Test%20Parent/Building%20Blocks/Content/Test/Smoke/SmartTarget" linkName="LocationInfo/OrganizationalItem" />
    <Dependency dependencyType="Schema" itemUrl="/webdav/401%20Automated%20Test%20Parent/Building%20Blocks/Modules/Core/Editor/Schemas/News%20Article.xsd" linkName="Schema" />
  </Dependencies>
</PackageItem>


text:
<!DOCTYPE HTML>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>$title$</title>
    <link href="/css/bootstrap.css" rel="stylesheet">
    <link href="/css/syntax.css" rel="stylesheet">
    <link href="/css/carousel.css" rel="stylesheet">
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
    $mathjax$

    $partial("templates/nav.html")$

$title$

$date$

      $body$
      $partial("templates/footer.html")$


text:
import { observable, action } from 'mobx'
import { registerAction } from 'utils/actions'
import { isPlainObject } from 'utils/is'
import settings from 'settings'
import i18n from 'utils/createI18n'

const getSettingValueHelper = store => Object.keys(store).filter(e => e !== '_keys').reduce((p, v) => {
  p[v] = isPlainObject(store[v]) ? store[v].value : store[v]
  return p
}, {})

export const SETTING_STORE_HYDRATE = 'SETTING_STORE_HYDRATE'

const state = observable({
  activeTabId: 'GENERAL',
  tabIds: ['GENERAL', 'APPEARANCE', 'EDITOR', 'KEYMAP', 'EXTENSIONS'],
  tabNames: {
    GENERAL: i18n`settings.tabs.general`,
    APPEARANCE: i18n`settings.tabs.appearance`,
    EDITOR: i18n`settings.tabs.editor`,
    KEYMAP: i18n`settings.tabs.keymap`,
    EXTENSIONS: i18n`settings.tabs.extensions`,
  },
  get activeTab () {
    return settings[this.activeTabId.toLowerCase()]
  },
  settings,
  activateTab: action((tabId) => {
    state.activeTabId = tabId
  }),
  toJS () {
    return {
      editor: getSettingValueHelper(settings.editor),
      general: getSettingValueHelper(settings.general),
      appearance: getSettingValueHelper(settings.appearance),
    }
  },
})

export const hydrate = registerAction(SETTING_STORE_HYDRATE, (json) => {
  Object.keys(json).forEach((tabItem) => {
    Object.keys(json[tabItem]).forEach((item) => {
      const stateRef = state.settings[tabItem][item]
      if (stateRef && stateRef.value) {
        stateRef.value = json[tabItem][item]
      }
    })
  })
})

export default state


text:
package com.google.gwt.core.ext;

/**
 * Generates source code for subclasses during deferred binding requests.
 * Subclasses must be thread-safe.
 */
public abstract class Generator {

  /**
   * Escapes string content to be a valid string literal.
   *
   * @return an escaped version of unescaped, suitable for being
   *         enclosed in double quotes in Java source
   */
  public static String escape(String unescaped) {
    int extra = 0;
    for (int in = 0, n = unescaped.length(); in < n; ++in) {
      switch (unescaped.charAt(in)) {
        case '\0':
        case '\n':
        case '\r':
        case '\"':
        case '\\':
          ++extra;
          break;
      }
    }

    if (extra == 0) {
      return unescaped;
    }

    char[] oldChars = unescaped.toCharArray();
    char[] newChars = new char[oldChars.length + extra];
    for (int in = 0, out = 0, n = oldChars.length; in < n; ++in, ++out) {
      char c = oldChars[in];
      switch (c) {
        case '\0':
          newChars[out++] = '\\';
          c = '0';
          break;
        case '\n':
          newChars[out++] = '\\';
          c = 'n';
          break;
        case '\r':
          newChars[out++] = '\\';
          c = 'r';
          break;
        case '\"':
          newChars[out++] = '\\';
          c = '"';
          break;
        case '\\':
          newChars[out++] = '\\';
          c = '\\';
          break;
      }
      newChars[out] = c;
    }

    return String.valueOf(newChars);
  }

  /**
   * Generate a default constructible subclass of the requested type. The
   * generator throws UnableToCompleteException if for any reason
   * it cannot provide a substitute class
   *
   * @return the name of a subclass to substitute for the requested class, or
   *         return null to cause the requested type itself to be
   *         used
   *
   */
  public abstract String generate(TreeLogger logger, GeneratorContext context,
      String typeName) throws UnableToCompleteException;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<router-rule>
    <table-shard-rule table="table" generatedPK="pk">
        <shard-dimension dbRule="#id# % 2"
                         dbIndexes="database0,database1"
                         tbRule="#id#.intdiv(2) % 2"
                         tbSuffix="everydb:[0,1]"
                         isMaster="true">
        </shard-dimension>
    </table-shard-rule>
</router-rule>


text:
import {
  GraphQLNonNull,
  GraphQLID
} from 'graphql';

import authorize from '../../authorize';
import config from '../../../../../config';
import userType from '../../types/user';
import DraftModel from '../../../models/draft';
import TabModel from '../../../models/tab';
import UserModel from '../../../models/user';

export default {
  type: userType,
  args: {
    id: {
      name: 'id',
      type: new GraphQLNonNull(GraphQLID)
    }
  },
  async resolve (root, params) {
    authorize(root);

    if (config.demo) {
      throw new Error('Remove user is disabled on the demo');
    }

    const removedUser = await UserModel.findByIdAndRemove(params.id).exec();

    if (!removedUser) {
      throw new Error('Error removing user');
    }

    // clean user's tabs and drafts
    await TabModel.find({_userId: removedUser._id}).remove();
    await DraftModel.find({userId: removedUser._id}).remove();

    return removedUser;
  }
};


text:
SSDP/UPnP implementation
---

[Complete UPnP specification](http://www.upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf)

[TODO list on trello.com](https://trello.com/b/MxC2CL35/ssdp-upnp)


text:
namespace JSBus
{
    using System.Web.Optimization;
    using System.Web.Routing;

    using JSBus.App_Start;

    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}


text:
class RenameCurrentCorral < ActiveRecord::Migration
  def change
    change_table :users do |t|
      t.rename :current_corral_location, :current_location
      t.rename :current_corral_latitude, :current_latitude
      t.rename :current_corral_longitude, :current_longitude
    end
  end
end


text:
#pragma once
#include <mixal_parse/parsers_utils.h>

namespace mixal_parse {

class MIXAL_PARSE_LIB_EXPORT Symbol
{
public:
	Symbol();

	Symbol(const char* name,
		LocalSymbolKind kind = LocalSymbolKind::Usual,
		LocalSymbolId id = k_invalid_local_symbol_id);

	Symbol(const std::string_view& name,
		LocalSymbolKind kind = LocalSymbolKind::Usual,
		LocalSymbolId id = k_invalid_local_symbol_id);

	static Symbol FromString(const std::string_view& str);

	bool is_valid() const;
	std::string_view name() const;

	LocalSymbolKind kind() const;
	bool is_local() const;

	LocalSymbolId local_id() const;

private:
	std::string_view name_;
	LocalSymbolKind kind_;
	LocalSymbolId id_;
};

bool operator==(const Symbol& lhs, const Symbol& rhs);
bool operator<(const Symbol& lhs, const Symbol& rhs);

} // namespace mixal_parse

////////////////////////////////////////////////////////////////////////////////

namespace mixal_parse {

inline Symbol::Symbol()
	: Symbol{std::string_view{}}
{
}

inline Symbol::Symbol(const char* name,
	LocalSymbolKind kind /*= LocalSymbolKind::Usual*/,
	LocalSymbolId id /*= k_invalid_local_symbol_id*/)
		: Symbol{std::string_view{name}, kind, id}
{
}

inline Symbol::Symbol(const std::string_view& name,
	LocalSymbolKind kind /*= LocalSymbolKind::Usual*/,
	LocalSymbolId id /*= k_invalid_local_symbol_id*/)
		: name_{name}
		, kind_{kind}
		, id_{id}
{
}

inline bool Symbol::is_valid() const
{
	return IsSymbol(name_);
}

inline std::string_view Symbol::name() const
{
	return name_;
}

inline LocalSymbolKind Symbol::kind() const
{
	return kind_;
}

inline bool Symbol::is_local() const
{
	return (kind_ != LocalSymbolKind::Usual);
}

inline LocalSymbolId Symbol::local_id() const
{
	return id_;
}

inline /*static*/ Symbol Symbol::FromString(const std::string_view& str)
{
	if (!IsLocalSymbol(str))
	{
		return Symbol{str};
	}

	const auto kind = ParseLocalSymbolKind(str);
	const auto id = ParseLocalSymbolId(str);
	if ((kind == LocalSymbolKind::Unknown) ||
		!IsValidLocalSymbolId(id))
	{
		return Symbol{};
	}

	return Symbol{str, kind, id};
}

inline bool operator==(const Symbol& lhs, const Symbol& rhs)
{
	return (lhs.name() == rhs.name());
}

inline bool operator<(const Symbol& lhs, const Symbol& rhs)
{
	return (lhs.name() < rhs.name());
}

} // namespace mixal_parse


text:
The ssair package provides a textual format for the Go SSA library IR, analogous to the LLVM IR textual representation. It also exposes machine specific op codes.

[![Build Status](http://travis-ci.org/bjwbell/ssair.svg?branch=master)](https://travis-ci.org/bjwbell/ssair)


text:
import * as React from "react";
import { mount } from "enzyme";
import {
  RawDesignerSensors as DesignerSensors,
  DesignerSensorsProps,
  mapStateToProps,
} from "../sensors";
import { fakeTimeSettings } from "../../__test_support__/fake_time_settings";
import { bot } from "../../__test_support__/fake_state/bot";
import { fakeState } from "../../__test_support__/fake_state";

describe("<DesignerSensors />", () => {
  const fakeProps = (): DesignerSensorsProps => ({
    dispatch: jest.fn(),
    timeSettings: fakeTimeSettings(),
    sensors: [],
    bot: bot,
    firmwareHardware: undefined,
    sensorReadings: [],
  });

  it("renders sensors panel", () => {
    const wrapper = mount(<DesignerSensors {...fakeProps()} />);
    ["sensors", "sensor history"].map(string =>
      expect(wrapper.text().toLowerCase()).toContain(string));
  });
});

describe("mapStateToProps()", () => {
  it("returns props", () => {
    const state = fakeState();
    const props = mapStateToProps(state);
    expect(props.firmwareHardware).toEqual(undefined);
  });
});


text:
using MineLib.Network.Classic.Enums;
using MineLib.Network.IO;

namespace MineLib.Network.Classic.Packets.Server
{
    public struct UpdateUserTypePacket : IPacketWithSize
    {
        public UserType UserType;

        public byte ID { get { return 0x0F; } }
        public short Size { get { return 2; } }

        public IPacketWithSize ReadPacket(IMinecraftDataReader reader)
        {
            UserType = (UserType) reader.ReadByte();

            return this;
        }

        IPacket IPacket.ReadPacket(IMinecraftDataReader reader)
        {
            return ReadPacket(reader);
        }

        public IPacket WritePacket(IMinecraftStream stream)
        {
            stream.WriteByte(ID);
            stream.WriteByte((byte) UserType);
            stream.Purge();

            return this;
        }
    }
}


text:
LOCATION=/usr/local
VERSION=0.1.15
# VERSION changes
#---------------------
# 0.1.14: Added 'install' usage
#
#CC=gcc

# if there isn't already a default CFLAGS set,
#	use our recommended settings.
#CFLAGS ?= -Wall -g -O2 -Werror $(CPU_OPTS)
#CFLAGS=-Wall -g -O2 -Wundef -Wshadow -Wsign-compare -I.
CFLAGS=-Wall  -I. -O2

# OLE decoding is still considered to be 'beta' mode - so it
#	disabled in the stable release of ripMIME for now
# You can turn it on, but watch out for various office files
#	which may/probably-will break ripMIME with a segfault
#	or other strange errors.  If you do wish to test this
#	and find a dud mailpack, please send through to
#	mailpacks@pldaniels.com
#
COMPONENTS= -DRIPOLE
LIBS=
#COMPONENTS=

#  DEBUGGING Related Flags

OBJ=ripmime
RIPOLE_OBJS= ripOLE/ole.o ripOLE/olestream-unwrap.o ripOLE/bytedecoders.o  ripOLE/bt-int.o
#RIPOLE_OBJS=
OFILES= strstack.o mime.o ffget.o MIME_headers.o tnef/tnef.o rawget.o pldstr.o logger.o libmime-decoders.o boundary-stack.o uuencode.o filename-filters.o $(RIPOLE_OBJS)

default: tnef/tnef.o ripmime ripOLE/ole.o

debug: CFLAGS=-Wall -ggdb -DDEBUG -I. -O0
debug: default

buildcodes.h:
	./generate-buildcodes.sh

ripOLE/ole.o:
	./build_ripOLE

tnef/tnef.o:
	./build_tnef

.c.o:
	${CC} ${CFLAGS} $(COMPONENTS) -c $*.c

all: ${OBJ}

solib: ${OFILES} ripmime-api.o
	gcc --shared -Wl,-soname,libripmime.so.1 ${OFILES} ripmime-api.o -o libripmime.so.1.4.0 -lc

libripmime: ${OFILES} ripmime-api.o
	ar ruvs libripmime.a ${OFILES}  ripmime-api.o

ripl: ripmime.a
	${CC} ${CFLAGS} ripmime.c ripmime.a -o ripmime

sco: ${OFILES}
	${CC} ${CFLAGS} ripmime.c ${OFILES} -o ripmime -lsocket

ripmime: ${OFILES} ripmime.c buildcodes.h
	${CC} ${CFLAGS} $(COMPONENTS) ripmime.c ${OFILES} -o ripmime ${LIBS}

riptest: ${OFILES}
	${CC} ${CFLAGS} riptest.c ${OFILES} -o riptest

install: ${OBJ}
	strip ripmime
	install -d ${LOCATION}/bin/
	install -m 755 ripmime ${LOCATION}/bin/
	install -d ${LOCATION}/man/
	install -m 644 ripmime.1  ${LOCATION}/man/man1

ffget_test: ffget_mmap_test.c ffget_mmap.[ch] logger.o ffget_mmap.o
	${CC} ${CFLAGS} ffget_mmap_test.c logger.o ffget_mmap.o -o ffgt

clean:
	rm -f *.o *core ${OBJ} buildcodes.h
	rm -f tnef/*.o
	rm -f ripOLE/*.o ripOLE/ripole

MIMEH: MIME_headers.o strlower.o
	${CC} ${CFLAGS} MIMEH_test.c MIME_headers.o strlower.o -o MIMEH_test