text:
var request = require('request')
  , moment  = require('moment')
  , http    = require('http')
  , zlib    = require('zlib')
  , crypto  = require('crypto')
  , mkdirp  = require('mkdirp')
  , fs      = require('fs')
  , helpers = require('./helper.js')
  , co      = require('co')
  , util    = require('util')
  , events  = require('events')
  , KeyFrame = require('./keyframe.js')
  , Chunk    = require('./chunk.js')

module.exports = Game

var chunkStatus = [];
var chunkdata;
var testGameID;
var chunkExists;
var requestMade = {};

util.inherits(Game, events.EventEmitter)

var mapIds = {
    1: "Summoner's Rift"
}

function Game(info, baseUrl) {

    events.EventEmitter.call(this)

    this.info = info
    this.baseUrl = baseUrl

    this.id        = info.gameId
    testGameID     = info.gameId
    requestMade.testGameID = {};
    requestMade.testGameID.chunks = {};
    requestMade.testGameID.keyframes = {};
    this.region    = info.platformId

    if(info.gameStartTime) {
        this.startTime = new Date(info.gameStartTime)
    }
    if(info.mapId) {
        this.map       = mapIds[info.mapId] || 'unkown(#' + info.mapId + ')'
    }
    this.mode      = info.gameMode || undefined
    this.type      = info.gameType || undefined
    this.summoners = info.participants || undefined
    this.banned    = info.bannedChampions || undefined
    this.createTime = undefined

    this.biggestKeyFrameId = 0
    this.biggestChunkId    = 0

    this.chunks = []
    this.keyframes = []

    this.obsKey = undefined
    if(info.obsKey) {
        this.obsKey = info.obsKey
    } else if(info.observers) {
        this.obsKey = info.observers.encryptionKey || undefined
    }
    if(this.obsKey) {
        this.cryptoKey = decrypt(this.id, this.obsKey)
    }
}

Game.prototype.setObserverKey = function(key) {
    this.obsKey = key
    this.cryptoKey = decrypt(this.id, key)
}

Game.prototype.getMetadata = function(cb) {
    console.log('Getting Metadata!');
    var url = this.baseUrl + 'consumer/getGameMetaData/' + this.region + '/' + this.id + '/1/token'
    cb = cb || function() {}
    request.get(url, function(err, res, body) {
        if(err) {
            return cb(err)
        }
        try {
            var data = JSON.parse(body)
        } catch(e) {
            console.error(url)
            console.error(e)
            console.error(body)
            return
        }
        this.readMetadata(data)
        console.log(this);
        cb(null, data, this)
    }.bind(this))
}

Game.prototype.readMetadata = function(data) {
    this.startTime  = helpers.parseRiotTime(data.startTime)
    this.createTime = helpers.parseRiotTime(data.createTime)
    this.ended      = !!data.gameEnded
}

Game.prototype.getLastChunkInfo = function(cb) {
    var url = this.baseUrl + 'consumer/getLastChunkInfo/' + this.region + '/' + this.id + '/1/token'
    cb = cb || function() {}
    request.get(url, function(err, res, body) {

        if(err) {
            return cb(err)
        }
        try {
            var data = JSON.parse(body)
        } catch(e) {
            console.error(e)
            console.error(body)
            return
        }
        cb(null, data, this)
    }.bind(this))
}

Game.prototype.startSpectate = function() {
    console.log('Polling for chunk!');
    this.pollForChunk()
}

Game.prototype.pollForChunk = co(function *() {
    var result = yield this.getLastChunkInfo.bind(this)
    var chunkdata = result[0]
    if(chunkdata.keyFrameId > this.biggestKeyFrameId) {
        var kf = new KeyFrame(this, chunkdata.keyFrameId, chunkdata)
        this.biggestKeyFrameId = chunkdata.keyFrameId
        this.keyframes[chunkdata.keyFrameId] = kf
        this.emit('keyframe.available', kf)
        console.log('Keyframe available!');
    }
    if(chunkdata.chunkId > this.biggestChunkId) {
        var chunk = new Chunk(this, chunkdata.chunkId, chunkdata)
        this.biggestChunkId = chunkdata.chunkId
        this.chunks[chunkdata.chunkId] = chunk
        this.emit('chunk.available', chunk)
        console.log('Chunk available!');
        //this.startDownloadChunk('./download/');

        if(chunkdata.endGameChunkId === chunkdata.chunkId) {
            this.ended = true
            this.emit('end')
            console.log('End!');
            //this.startDownloadChunk('./download/');
        }
    }
    setTimeout(this.pollForChunk.bind(this), chunkdata.nextAvailableChunk)
})

Game.prototype.startDownloadChunk = co(function *(outputDirectory, sDCChunkID) {

    var result = yield this.getLastChunkInfo.bind(this)
    var chunkdata = result[0]
/*    fs.exists(outputDirectory + testGameID + '/chunks/' + chunkdata.chunkId, function (err, exists){
        if(err) {
            console.log(err);
        }
        chunkExists = exists;
    })*/
    if (!fs.existsSync(outputDirectory + sDCChunkID)) {
    this.downloadChunk(outputDirectory, sDCChunkID)
    console.log('downloadChunk', sDCChunkID, outputDirectory);//, chunk
    }

/*    if (chunkdata.status === undefined){
        chunkdata.status = [];
        console.log('Set chunkdata array');
        chunkdata.status[chunkdata.chunkId] = undefined;
        chunkStatus = [];
    }
    if(chunkdata.status){
        console.log('Set chunkdata array value only');
        chunkdata.status[chunkdata.chunkId] = undefined;
    }
    chunkStatus[chunkdata.chunkId] = chunkdata.status[chunkdata.chunkId];
    if(chunkStatus[chunkdata.chunkId] === undefined) {
        this.downloadChunk(outputDirectory, chunkdata.chunkId)
        console.log('downloadChunk', chunkdata.chunkId, outputDirectory);//, chunk)
    }*/
    if(chunkdata.endGameChunkId !== sDCChunkID) {
        setTimeout(this.startDownloadChunk.bind(this, outputDirectory, sDCChunkID), chunkdata.nextAvailableChunk)
    }

})

Game.prototype.startDownloadKeyframe = co(function *(outputDirectory, sDKKeframeID) {

    var result = yield this.getLastChunkInfo.bind(this)
    var chunkdata = result[0]
/*    fs.exists(outputDirectory + testGameID + '/chunks/' + chunkdata.chunkId, function (err, exists){
        if(err) {
            console.log(err);
        }
        chunkExists = exists;
    })*/
    if (!fs.existsSync(outputDirectory + sDKKeframeID)) {
    this.downloadKeyframe(outputDirectory, sDKKeframeID)
    console.log('downloadKeyframe', sDKKeframeID, outputDirectory);//, chunk
    }

/*    if (chunkdata.status === undefined){
        chunkdata.status = [];
        console.log('Set chunkdata array');
        chunkdata.status[chunkdata.chunkId] = undefined;
        chunkStatus = [];
    }
    if(chunkdata.status){
        console.log('Set chunkdata array value only');
        chunkdata.status[chunkdata.chunkId] = undefined;
    }
    chunkStatus[chunkdata.chunkId] = chunkdata.status[chunkdata.chunkId];
    if(chunkStatus[chunkdata.chunkId] === undefined) {
        this.downloadChunk(outputDirectory, chunkdata.chunkId)
        console.log('downloadChunk', chunkdata.chunkId, outputDirectory);//, chunk)
    }*/
    if(chunkdata.endGameChunkId !== chunkdata.chunkId) {
        setTimeout(this.startDownloadKeyframe.bind(this, outputDirectory, sDKKeframeID), chunkdata.nextAvailableChunk)
    }

})

Game.prototype.downloadKeyframe = co(function *(dir, id) {
    try {
        yield mkdirp.bind(null, dir)
    }
    catch (err) {
        return console.error(err)
    }
    var ws       = fs.createWriteStream(dir + id + '.txt')
    var decipher = crypto.createDecipheriv('bf-ecb', this.cryptoKey, "")
    var gunzip   = zlib.createGunzip()
    var url      = this.baseUrl + 'consumer/getKeyFrame/' + this.region + '/' + this.id + '/' + id + '/token'

    console.log('[', id, '] GET ', url)
    if (requestMade.testGameID.keyframes[id] === undefined) {
        requestMade.testGameID.keyframes[id] = 1;
        console.log(requestMade.testGameID.keyframes);
    var req = http.request(url, function(res) {
        console.log('[', id, ']', res.statusCode)
        if(res.statusCode !== 200) {
            console.log('ERR[', id, '] HTTP:', res.statusCode, res.headers)
            return;
        }
/*        fs.writeFile('chunk ' + id + '.txt', res, function(err) {
            if (err) throw err;
            console.log('Wrote chunk ' + id + ' to file!');
        })*/
        console.log("KEYFRAME RESPONSE LENGTH: " + res.length);
        //console.log("KEYFRAME RESPONSE DATA: " + res);
        res.pipe(decipher).pipe(gunzip).pipe(ws);
        gunzip.on('error', function(err) {
            console.log('ERR[', id, '] GZIP:', err)
        })
        ws.on('finish', function() {
            console.log('[', id, '] done')
            //this.chunkStatus[id].status = 'done'
            console.log('Finished keyframe decrypt and saved to directory: ' + dir + id);
            //chunkStatus[id] = 'done';
        }.bind(this))
    }.bind(this))
    req.on('error', function(err) {
            console.log('ERR[', id, '] HTTP:', err)
    })
    req.end();
    //var testWrite = fs.createWriteStream()
    }
})

Game.prototype.downloadChunk = co(function *(dir, id) {
    try {
        yield mkdirp.bind(null, dir)
    }
    catch (err) {
        return console.error(err)
    }
    var ws       = fs.createWriteStream(dir + id)
    var decipher = crypto.createDecipheriv('bf-ecb', this.cryptoKey, "")
    var gunzip   = zlib.createGunzip()
    var url      = this.baseUrl + 'consumer/getGameDataChunk/' + this.region + '/' + this.id + '/' + id + '/token'

    console.log('[', id, '] GET ', url)
    if (requestMade.testGameID.chunks[id] === undefined) {
        requestMade.testGameID.chunks[id] = 1;
        console.log(requestMade.testGameID.chunks);
    var req = http.request(url, function(res) {
        console.log('[', id, ']', res.statusCode)
        if(res.statusCode !== 200) {
            console.log('ERR[', id, '] HTTP:', res.statusCode, res.headers)
            return;
        }
        console.log("KEYFRAME RESPONSE LENGTH: " + res.length);
        //console.log("KEYFRAME RESPONSE DATA: " + res);

/*        fs.writeFile('chunk ' + id + '.txt', res, function(err) {
            if (err) throw err;
            console.log('Wrote chunk ' + id + ' to file!');
        })*/
        res.pipe(decipher).pipe(gunzip).pipe(ws);
        gunzip.on('error', function(err) {
            console.log('ERR[', id, '] GZIP:', err)
        })
        ws.on('finish', function() {
            console.log('[', id, '] done')
            //this.chunkStatus[id].status = 'done'
            console.log('Finished chunk decrypt and saved to directory: ' + dir + id);
            chunkStatus[id] = 'done';
        }.bind(this))
    }.bind(this))
    req.on('error', function(err) {
            console.log('ERR[', id, '] HTTP:', err)
    })
    req.end();
    //var testWrite = fs.createWriteStream()
    }
})

function decrypt(pass, data) {
    if(!Buffer.isBuffer(pass)) {
        pass  = new Buffer(pass.toString());
    }
    var decipher  = crypto.createDecipheriv('bf-ecb', pass, "")
    var inBuf = new Buffer(data, 'base64');
    decipher.write(inBuf);
    //decipher.end();
    return decipher.read();
}


text:
    ( ((std::ostringstream&)(std::ostringstream() << msg)).str() )
#define MAKE_CSTRING( msg )                                             \
    ( ((std::ostringstream&)(std::ostringstream() << msg)).str().c_str() )

#define COMMENT_CHAR '#'

inline std::istream& comment(std::istream &s)
{
    char c;
    while (s.get(c)) {
        if (!isspace(c)) {
            if (c == COMMENT_CHAR) {
                while (s.get(c) && c != '\n');
            } else {
                s.putback(c);
                break;
            }
        }
    }
    return s;
}

inline unsigned long getMilliSeconds() {
#ifdef WIN32
//     typedef unsigned long LONGLONG;
//     typedef long LARGE_INTEGER;

    static LONGLONG frequency=0;
    if(!frequency)
        QueryPerformanceFrequency((LARGE_INTEGER*)&frequency);
    LONGLONG counter;
    QueryPerformanceCounter((LARGE_INTEGER*)&counter);
    return (unsigned long) (counter*1000 / frequency);
#else
    static struct timeval time;
    gettimeofday(&time, 0);
    return (unsigned long)time.tv_sec*1000 + (unsigned long)time.tv_usec/1000;
#endif
}

template<class T>
std::string toString(T v) {
    std::stringstream ss;
    ss << v;
    return ss.str();
}

template<class T>
T& fromString(const std::string& str, T& v) {
    std::istringstream ss(str);
    ss >> v;
    return v;
}

std::string& replaceAll(std::string& txt, char src, char tar);

int matlabCall(const std::string& cmd);

const char* getTemp();

// only usable if LINUX defined
const std::string& __set_fnmatchpattern(const std::string& pattern);
int __fixed_fnmatch(const struct dirent* dent);

#if defined(LINUX) || defined(DARWIN)
template<class T>
int findFiles(const std::string& fmask, T iter) { return 0; }
#else
template<class T>
int findFiles(const std::string& fmask, T iter) {
    struct _finddata_t ff;
    int ffhandle;
    int ffcount=0;
    if((ffhandle = _findfirst(fmask.c_str(), &ff)) != -1) {
        do {
            *iter++ = ff.name;
            ffcount++;
        } while(_findnext(ffhandle, &ff) == 0);
    }
    return ffcount;
}
#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
'use strict';

module.exports = require('./persistence');


text:
from __future__ import print_function

import argparse
import os
import pipes
import re
import subprocess
import sys
import tempfile
import textwrap

if sys.version_info[0] < 3:
  input = raw_input

IS_WINDOWS = sys.platform.startswith('win')

def SubprocessCheckCall0Or1(args):
    """Like subprocss.check_call(), but allows a return code of 1.

    Returns True if the subprocess exits with code 0, False if it exits with
    code 1, and re-raises the subprocess.check_call() exception otherwise.
    """
    try:
        subprocess.check_call(args, shell=IS_WINDOWS)
    except subprocess.CalledProcessError as e:
        if e.returncode != 1:
            raise
        return False

    return True

def GitMergeBaseIsAncestor(ancestor, descendant):
    """Determines whether |ancestor| is an ancestor of |descendant|.
    """
    return SubprocessCheckCall0Or1(
        ['git', 'merge-base', '--is-ancestor', ancestor, descendant])

def main(args):
    parser = argparse.ArgumentParser(
        description='Update the in-tree copy of an imported project')
    parser.add_argument(
        '--repository',
        default='https://chromium.googlesource.com/crashpad/crashpad',
        help='The imported project\'s remote fetch URL',
        metavar='URL')
    parser.add_argument(
        '--subtree',
        default='third_party/crashpad/crashpad',
        help='The imported project\'s location in this project\'s tree',
        metavar='PATH')
    parser.add_argument(
        '--update-to',
        default='FETCH_HEAD',
        help='What to update the imported project to',
        metavar='COMMITISH')
    parser.add_argument(
        '--fetch-ref',
        default='HEAD',
        help='The remote ref to fetch',
        metavar='REF')
    parser.add_argument(
        '--readme',
        help='The README.chromium file describing the imported project',
        metavar='FILE',
        dest='readme_path')
    parser.add_argument(
        '--exclude',
        default=['codereview.settings', 'infra'],
        action='append',
        help='Files to exclude from the imported copy',
        metavar='PATH')
    parsed = parser.parse_args(args)

    original_head = (
        subprocess.check_output(['git', 'rev-parse', 'HEAD'],
                                shell=IS_WINDOWS).rstrip())
    original_head = original_head.decode('utf-8')

    # Read the README, because that's what it's for. Extract some things from
    # it, and save it to be able to update it later.
    readme_path = (parsed.readme_path or
                   os.path.join(os.path.dirname(__file__ or '.'),
                                'README.chromium'))
    readme_content_old = open(readme_path, 'rb').read().decode('utf-8')

    project_name_match = re.search(
        r'^Name:\s+(.*)$', readme_content_old, re.MULTILINE)
    project_name = project_name_match.group(1)

    # Extract the original commit hash from the README.
    revision_match = re.search(r'^Revision:\s+([0-9a-fA-F]{40})($|\s)',
                               readme_content_old,
                               re.MULTILINE)
    revision_old = revision_match.group(1)

    subprocess.check_call(['git', 'fetch', parsed.repository, parsed.fetch_ref],
                          shell=IS_WINDOWS)

    # Make sure that parsed.update_to is an ancestor of FETCH_HEAD, and
    # revision_old is an ancestor of parsed.update_to. This prevents the use of
    # hashes that are known to git but that don't make sense in the context of
    # the update operation.
    if not GitMergeBaseIsAncestor(parsed.update_to, 'FETCH_HEAD'):
        raise Exception('update_to is not an ancestor of FETCH_HEAD',
                        parsed.update_to,
                        'FETCH_HEAD')
    if not GitMergeBaseIsAncestor(revision_old, parsed.update_to):
        raise Exception('revision_old is not an ancestor of update_to',
                        revision_old,
                        parsed.update_to)

    # git-filter-branch needs a ref to update. It's not enough to just tell it
    # to operate on a range of commits ending at parsed.update_to, because
    # parsed.update_to is a commit hash that can't be updated to point to
    # anything else.
    subprocess.check_call(['git', 'update-ref', 'UPDATE_TO', parsed.update_to],
                          shell=IS_WINDOWS)

    # Filter the range being updated over to exclude files that ought to be
    # missing. This points UPDATE_TO to the rewritten (filtered) version.
    # git-filter-branch insists on running from the top level of the working
    # tree.
    toplevel = subprocess.check_output(['git', 'rev-parse', '--show-toplevel'],
                                       shell=IS_WINDOWS).rstrip()
    subprocess.check_call(
        ['git',
         'filter-branch',
         '--force',
         '--index-filter',
         'git rm -r --cached --ignore-unmatch ' +
             ' '.join(pipes.quote(path) for path in parsed.exclude),
         revision_old + '..UPDATE_TO'],
        cwd=toplevel,
        shell=IS_WINDOWS)

    # git-filter-branch saved a copy of the original UPDATE_TO at
    # original/UPDATE_TO, but this isn't useful because it refers to the same
    # thing as parsed.update_to, which is already known.
    subprocess.check_call(
        ['git', 'update-ref', '-d', 'refs/original/UPDATE_TO'],
        shell=IS_WINDOWS)

    filtered_update_range = revision_old + '..UPDATE_TO'
    unfiltered_update_range = revision_old + '..' + parsed.update_to

    # This cherry-picks each change in the window from the filtered view of the
    # upstream project into the current branch.
    assisted_cherry_pick = False
    try:
        if not SubprocessCheckCall0Or1(['git',
                                        'cherry-pick',
                                        '--keep-redundant-commits',
                                        '--strategy=subtree',
                                        '-Xsubtree=' + parsed.subtree,
                                        '-x',
                                        filtered_update_range]):
            assisted_cherry_pick = True
            print("""
Please fix the errors above and run "git cherry-pick --continue".
Press Enter when "git cherry-pick" completes.
You may use a new shell for this, or ^Z if job control is available.
Press ^C to abort.
""", file=sys.stderr)
            input()
    except:
        # ^C, signal, or something else.
        print('Aborting...', file=sys.stderr)
        subprocess.call(['git', 'cherry-pick', '--abort'], shell=IS_WINDOWS)
        raise

    # Get an abbreviated hash and subject line for each commit in the window,
    # sorted in chronological order. Use the unfiltered view so that the commit
    # hashes are recognizable.
    log_lines = subprocess.check_output(
        ['git',
         '-c',
         'core.abbrev=12',
         'log',
         '--abbrev-commit',
         '--pretty=oneline',
         '--reverse',
         unfiltered_update_range],
         shell=IS_WINDOWS).decode('utf-8').splitlines(False)

    if assisted_cherry_pick:
        # If the user had to help, count the number of cherry-picked commits,
        # expecting it to match.
        cherry_picked_commits = int(subprocess.check_output(
            ['git', 'rev-list', '--count', original_head + '..HEAD'],
            shell=IS_WINDOWS))
        if cherry_picked_commits != len(log_lines):
            print('Something smells fishy, aborting anyway...', file=sys.stderr)
            subprocess.call(['git', 'cherry-pick', '--abort'], shell=IS_WINDOWS)
            raise Exception('not all commits were cherry-picked',
                            len(log_lines),
                            cherry_picked_commits)

    # Make a nice commit message. Start with the full commit hash.
    revision_new = subprocess.check_output(
        ['git', 'rev-parse', parsed.update_to],
        shell=IS_WINDOWS).decode('utf-8').rstrip()
    new_message = u'Update ' + project_name + ' to ' + revision_new + '\n\n'

    # Wrap everything to 72 characters, with a hanging indent.
    wrapper = textwrap.TextWrapper(width=72, subsequent_indent = ' ' * 13)
    for line in log_lines:
        # Strip trailing periods from subjects.
        if line.endswith('.'):
            line = line[:-1]

        # If any subjects have what look like commit hashes in them, truncate
        # them to 12 characters.
        line = re.sub(r'(\s)([0-9a-fA-F]{12})([0-9a-fA-F]{28})($|\s)',
                      r'\1\2\4',
                      line)

        new_message += '\n'.join(wrapper.wrap(line)) + '\n'

    # Update the README with the new hash.
    readme_content_new = re.sub(
        r'^(Revision:\s+)([0-9a-fA-F]{40})($|\s.*?$)',
        r'\g<1>' + revision_new,
        readme_content_old,
        1,
        re.MULTILINE)

    # If the in-tree copy has no changes relative to the upstream, clear the
    # "Local Modifications" section of the README.
    has_local_modifications = True
    if SubprocessCheckCall0Or1(['git',
                                'diff-tree',
                                '--quiet',
                                'UPDATE_TO',
                                'HEAD:' + parsed.subtree]):
        has_local_modifications = False

        if not parsed.exclude:
            modifications = 'None.\n'
        elif len(parsed.exclude) == 1:
            modifications = (
                ' - %s has been excluded.\n' % parsed.exclude[0])
        else:
            modifications = (
                ' - The following files have been excluded:\n')
            for excluded in sorted(parsed.exclude):
                modifications += '    - ' + excluded + '\n'
        readme_content_new = re.sub(r'\nLocal Modifications:\n.*$',
                                    '\nLocal Modifications:\n' + modifications,
                                    readme_content_new,
                                    1,
                                    re.DOTALL)

    # The UPDATE_TO ref is no longer useful.
    subprocess.check_call(['git', 'update-ref', '-d', 'UPDATE_TO'],
                          shell=IS_WINDOWS)

    # This soft-reset causes all of the cherry-picks to show up as staged, which
    # will have the effect of squashing them along with the README update when
    # committed below.
    subprocess.check_call(['git', 'reset', '--soft', original_head],
                          shell=IS_WINDOWS)

    # Write the new README.
    open(readme_path, 'wb').write(readme_content_new.encode('utf-8'))

    # Commit everything.
    subprocess.check_call(['git', 'add', readme_path], shell=IS_WINDOWS)

    try:
        commit_message_name = None
        with tempfile.NamedTemporaryFile(mode='wb',
                                         delete=False) as commit_message_f:
            commit_message_name = commit_message_f.name
            commit_message_f.write(new_message.encode('utf-8'))
        subprocess.check_call(['git',
                               'commit', '--file=' + commit_message_name],
                              shell=IS_WINDOWS)
    finally:
        if commit_message_name:
            os.unlink(commit_message_name)

    if has_local_modifications:
        print('Remember to check the Local Modifications section in ' +
              readme_path, file=sys.stderr)

    return 0

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


text:
<?

class htaccess{
    var $fHtaccess=""; // path and filename for htaccess file
    var $fHtgroup="";  // path and filename for htgroup file
    var $fPasswd="";   // path and filename for passwd file

    var $authType="Basic"; // Default authentification type
    var $authName="Internal area"; // Default authentification name

    /**
    * Initialising class htaccess
    */
    function htaccess(){
    }

    /**
    * Sets the filename and path of .htaccess to work with
    * @param string	$filename    the name of htaccess file
    */
    function setFHtaccess($filename){
        $this->fHtaccess=$filename;
    }

    /**
    * Sets the filename and path of the htgroup file for the htaccess file
    * @param string	$filename    the name of htgroup file
    */
    function setFHtgroup($filename){
        $this->fHtgroup=$filename;
    }

    /**
    * Sets the filename and path of the password file for the htaccess file
    * @param string	$filename    the name of htgroup file
    */
    function setFPasswd($filename){
        $this->fPasswd=$filename;
    }

    /**
    * Adds a user to the password file
    * @param string $username     Username
    * @param string $password     Password for Username
    * @param string $group        Groupname for User (optional)
    * @return boolean $created         Returns true if user have been created otherwise false
    */
    function addUser($username,$password,$group){
        // checking if user already exists
        $file=@fopen($this->fPasswd,"r");
        $isAlready=false;
        while($line=@fgets($file,200)){
            $lineArr=explode(":",$line);
            if($username==$lineArr[0]){
                $isAlready=true;
             }
        }

        if($isAlready==false){
            $file=fopen($this->fPasswd,"a");

            $password=crypt($password);
            $newLine=$username.":".$password."\n";

            fputs($file,$newLine);
            fclose($file);
            return true;
        }else{
            return false;
        }
    }

    /**
    * Adds a group to the htgroup file
    * @param string $groupname     Groupname
    */
    function addGroup($groupname){
        $file=fopen($this->fHtgroup,"a");
        fclose($file);
    }

    /**
    * Deletes a user in the password file
    * @param string $username     Username to delete
    * @return boolean $deleted    Returns true if user have been deleted otherwise false
    */
    function delUser($username){
        // Reading names from file
        $file=fopen($path.$this->fPasswd,"r");
        $i=0;
        while($line=fgets($file,200)){
            $lineArr=explode(":",$line);
            if($username!=$lineArr[0]){
                $newUserlist[$i][0]=$lineArr[0];
                $newUserlist[$i][1]=$lineArr[1];
                $i++;
            }else{
                $deleted=true;
            }
        }
        fclose($file);

        // Writing names back to file (without the user to delete)
        $file=fopen($path.$this->fPasswd,"w");
        for($i=0;$i<count($newUserlist);$i++){
            fputs($file,$newUserlist[$i][0].":".$newUserlist[$i][1]."\n");
        }
        fclose($file);

        if($deleted==true){
            return true;
        }else{
            return false;
        }
    }

    /**
    * Returns an array of all users in a password file
    * @return array $users         All usernames of a password file in an array
    * @see setFPasswd()
    */
    function getUsers(){
    }

    /**
    * Sets a password to the given username
    * @param string $username     The name of the User for changing password
    * @param string $password     New Password for the User
    * @return boolean $isSet      Returns true if password have been set
    */
    function setPasswd($username,$new_password){
        // Reading names from file
        $newUserlist="";

        $file=fopen($this->fPasswd,"r");
        $x=0;
        for($i=0;$line=fgets($file,200);$i++){
            $lineArr=explode(":",$line);
            if($username!=$lineArr[0] && $lineArr[0]!="" && $lineArr[1]!=""){
                $newUserlist[$i][0]=$lineArr[0];
                $newUserlist[$i][1]=$lineArr[1];
                $x++;
            }else if($lineArr[0]!="" && $lineArr[1]!=""){
                $newUserlist[$i][0]=$lineArr[0];
                $newUserlist[$i][1]=crypt($new_password)."\n";
                $isSet=true;
                $x++;
            }
        }
        fclose($file);

        unlink($this->fPasswd);

        /// Writing names back to file (with new password)
        $file=fopen($this->fPasswd,"w");
        for($i=0;$i<count($newUserlist);$i++){
            $content=$newUserlist[$i][0].":".$newUserlist[$i][1];
            fputs($file,$content);
        }
        fclose($file);

        if($isSet==true){
            return true;
        }else{
            return false;
        }
    }

    /**
    * Sets the Authentification type for Login
    * @param string $authtype     Authentification type as string
    */
    function setAuthType($authtype){
        $this->authType=$authtype;
    }

    /**
    * Sets the Authentification Name (Name of the login area)
    * @param string $authname     Name of the login area
  	*/
    function setAuthName($authname){
        $this->authName=$authname;
    }

    /**
    * Writes the htaccess file to the given Directory and protects it
    * @see setFhtaccess()
  	*/
    function addLogin(){
       $file=fopen($this->fHtaccess,"w+");
       fputs($file,"Order allow,deny\n");
       fputs($file,"Allow from all\n");
       fputs($file,"AuthType        ".$this->authType."\n");
       fputs($file,"AuthUserFile    ".$this->fPasswd."\n\n");
       fputs($file,"AuthName        \"".$this->authName."\"\n");
       fputs($file,"require valid-user\n");
       fclose($file);
    }

    /**
    * Deletes the protection of the given directory
    * @see setFhtaccess()
    */
    function delLogin(){
        unlink($this->fHtaccess);
    }
}
?>


text:
package org.pentaho.di.trans.steps.textfileoutput;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormatSymbols;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

import org.pentaho.di.core.compress.CompressionOutputStream;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.trans.step.BaseStepData;
import org.pentaho.di.trans.step.StepDataInterface;

/**
 * @author Matt
 * @since 22-jan-2005
 */
public class TextFileOutputData extends BaseStepData implements StepDataInterface {

  interface IFileStreamsCollection {
    FileStream getStream( String filename );
    void closeOldestOpenFile( boolean removeFileFromCollection ) throws IOException;
    void flushOpenFiles( boolean closeAfterFlush ) throws IOException;
    String getLastFileName(  );
    FileStream getLastStream(  );
    int getNumOpenFiles( );
    void closeFile( String filename ) throws IOException;
    void closeStream( OutputStream outputStream ) throws IOException;
    int size( );
    void add( String filename, FileStream fileStreams );
  }

  public class FileStreamsKey implements Comparable<FileStreamsKey> {
    String fileName;
    long index = 0;

    public FileStreamsKey( String fileName, long index ) {
      this.fileName = fileName;
      this.index = index;
    }

    public String getFileName() {
      return fileName;
    }

    public void setFileName( String fileName ) {
      this.fileName = fileName;
    }

    public long getIndex() {
      return index;
    }

    public void setIndex( int index ) {
      this.index = index;
    }

    @Override
    public int compareTo( FileStreamsKey o ) {
      return fileName.compareTo( o.getFileName() );
    }

    @Override
    public boolean equals( Object obj ) {
      return fileName.equals( obj );
    }
  }

  public class FileStream {
    OutputStream fileOutputStream;
    CompressionOutputStream compressedOutputStream;
    BufferedOutputStream bufferedOutputStream;
    boolean isDirty;

    public FileStream( OutputStream fileOutputStream, CompressionOutputStream compressedOutputStream, BufferedOutputStream bufferedOutputStream ) {
      this.fileOutputStream = fileOutputStream;
      this.compressedOutputStream = compressedOutputStream;
      this.bufferedOutputStream = bufferedOutputStream;
      isDirty = false;
    }

    public boolean isDirty() {
      return isDirty;
    }

    public void setDirty( boolean dirty ) {
      isDirty = dirty;
    }

    public void flush() throws IOException {
      if ( isDirty ) {
        getBufferedOutputStream().flush();
        isDirty = false;
      }
    }

    public void close() throws IOException {
      setBufferedOutputStream( null );
      getCompressedOutputStream().close();
      setCompressedOutputStream( null );
      getFileOutputStream().close();
      setFileOutputStream( null );
      isDirty = false;
    }

    public boolean isOpen() {
      return ( fileOutputStream != null ) || ( compressedOutputStream != null ) || ( bufferedOutputStream != null );
    }

    public BufferedOutputStream getBufferedOutputStream() {
      return bufferedOutputStream;
    }

    public void setBufferedOutputStream( BufferedOutputStream outputStream ) {
      this.bufferedOutputStream = outputStream;
    }

    public OutputStream getFileOutputStream() {
      return fileOutputStream;
    }

    public void setFileOutputStream( OutputStream fileOutputStream ) {
      this.fileOutputStream = fileOutputStream;
    }

    public CompressionOutputStream getCompressedOutputStream() {
      return compressedOutputStream;
    }

    public void setCompressedOutputStream( CompressionOutputStream compressedOutputStream ) {
      this.compressedOutputStream = compressedOutputStream;
    }
  }

  public class FileStreamsList implements IFileStreamsCollection {
    ArrayList<FileStream> streamsList = new ArrayList<>();
    ArrayList<String> namesList = new ArrayList<>();
    int numOpenFiles = 0;

    @Override
    public FileStream getStream( String filename ) {
      int index = namesList.indexOf( filename );
      return index == -1 ? null : streamsList.get( index );
    }

    @Override
    public void closeOldestOpenFile( boolean removeFileFromCollection ) throws IOException {
      FileStream oldestOpenStream = null;
      int i;
      for ( i = 0; i < streamsList.size(); i++ ) {
        FileStream existingStream = streamsList.get( i );
        if ( existingStream.isOpen() ) {
          oldestOpenStream = existingStream;
          break;
        }
      }
      if ( oldestOpenStream != null ) {
        oldestOpenStream.flush();
        oldestOpenStream.close();
        numOpenFiles--;
        if ( removeFileFromCollection ) {
          streamsList.remove( i );
          namesList.remove( i );
        }
      }
    }

    @Override
    public void flushOpenFiles( boolean closeAfterFlush ) throws IOException {
      for ( FileStream outputStream : streamsList ) {
        if ( outputStream.isDirty() ) {
          try {
            outputStream.flush();
            if ( closeAfterFlush && outputStream.isOpen() ) {
              outputStream.close();
              numOpenFiles--;
            }
          } catch ( IOException e ) {
            e.printStackTrace();
          }
        }
      }
    }

    @Override
    public String getLastFileName() {
      return namesList.size() > 0 ? namesList.get( namesList.size() - 1 ) : null;
    }

    @Override
    public FileStream getLastStream() {
      return streamsList.size() > 0 ? streamsList.get( streamsList.size() - 1 ) : null;
    }

    @Override
    public int getNumOpenFiles() {
      return numOpenFiles;
    }

    @Override
    public void closeFile( String filename ) throws IOException {
      int index = namesList.indexOf( filename );
      if ( index >= 0 ) {
        FileStream existingStream = streamsList.get( index );
        if ( existingStream.isOpen() ) {
          existingStream.flush();
          existingStream.close();
          numOpenFiles--;
        }
      }
    }

    @Override
    public void closeStream( OutputStream outputStream ) throws IOException {
      for ( int i = 0; i < streamsList.size(); i++ ) {
        FileStream fileStream = streamsList.get( i );
        if ( ( fileStream.getBufferedOutputStream() == outputStream ) || ( fileStream.getCompressedOutputStream() == outputStream ) || ( fileStream.getFileOutputStream() == outputStream ) ) {
          closeFile( namesList.get( i ) );
        }
      }
    }

    @Override
    public int size() {
      return streamsList.size();
    }

    @Override
    public void add( String filename, FileStream fileStreams ) {
      namesList.add( filename );
      streamsList.add( fileStreams );
      if ( fileStreams.isOpen() ) {
        numOpenFiles++;
      }
    }
  }

  public class FileStreamsMap extends TreeMap<FileStreamsKey, FileStream> implements IFileStreamsCollection  {
    int numOpenFiles = 0;

    @Override
    public void add( String filename, FileStream fileWriterOutputStream ) {
      long index = 0;
      if ( size() > 0 ) {
        index = lastKey().index + 1;
      }
      put( new FileStreamsKey( filename, index ), fileWriterOutputStream );
      if ( fileWriterOutputStream.isOpen() ) {
        numOpenFiles++;
      }

    }

    @Override
    public FileStream getStream( String filename ) {
      return get( new FileStreamsKey( filename, -1 ) );
    }

    private FileStream remove( String filename ) {
      return remove( new FileStreamsKey( filename, -1 ) );
    }

    @Override
    public String getLastFileName() {
      String filename = null;
      Map.Entry<TextFileOutputData.FileStreamsKey, FileStream> lastEntry = lastEntry();
      if ( lastEntry != null ) {
        filename = lastEntry.getKey( ).getFileName( );
      }
      return filename;
    }

    @Override
    public FileStream getLastStream() {
      FileStream lastStream = null;
      Map.Entry<TextFileOutputData.FileStreamsKey, FileStream> lastEntry = lastEntry();
      if ( lastEntry != null ) {
        lastStream = lastEntry.getValue( );
      }
      return lastStream;
    }

    @Override
    public int getNumOpenFiles() {
      return numOpenFiles;
    }

    @Override
    public void closeOldestOpenFile( boolean removeFileFromCollection ) throws IOException {
      FileStream oldestOpenStream = null;
      String oldestOpenFileName = null;
      for ( Map.Entry<TextFileOutputData.FileStreamsKey, FileStream> mapEntry : entrySet() ) {
        FileStream existingStream = mapEntry.getValue();
        if ( existingStream.isOpen() ) {
          oldestOpenStream = existingStream;
          oldestOpenFileName = mapEntry.getKey().getFileName();
          break;
        }
      }
      if ( oldestOpenStream != null ) {
        oldestOpenStream.flush();
        oldestOpenStream.close();
        numOpenFiles--;
        if ( removeFileFromCollection ) {
          remove( oldestOpenFileName );
        }
      }
    }

    @Override
    public void flushOpenFiles( boolean closeAfterFlush ) {
      for ( FileStream outputStream : values() ) {
        if ( outputStream.isDirty() ) {
          try {
            outputStream.flush();
            if ( closeAfterFlush ) {
              outputStream.close();
            }
          } catch ( IOException e ) {
            e.printStackTrace();
          }
        }
      }
    }

    @Override
    public void closeFile( String filename ) throws IOException {
      FileStream outputStreams = getStream( filename );
      if ( ( outputStreams != null ) && ( outputStreams.isOpen() ) ) {
        outputStreams.flush();
        outputStreams.close();
        numOpenFiles--;
      }
    }

    @Override
    public void closeStream( OutputStream outputStream ) throws IOException {
      for ( Map.Entry<TextFileOutputData.FileStreamsKey, FileStream> mapEntry : entrySet() ) {
        FileStream fileStream = mapEntry.getValue();
        if ( ( fileStream.getBufferedOutputStream() == outputStream ) || ( fileStream.getCompressedOutputStream() == outputStream ) || ( fileStream.getFileOutputStream() == outputStream ) ) {
          closeFile( mapEntry.getKey().getFileName() );
        }
      }
    }
  }

  public int splitnr;

  public int[] fieldnrs;

  public NumberFormat nf;
  public DecimalFormat df;
  public DecimalFormatSymbols dfs;

  public SimpleDateFormat daf;
  public DateFormatSymbols dafs;

  public CompressionOutputStream out;

  public OutputStream writer;

  public DecimalFormat defaultDecimalFormat;
  public DecimalFormatSymbols defaultDecimalFormatSymbols;

  public SimpleDateFormat defaultDateFormat;
  public DateFormatSymbols defaultDateFormatSymbols;

  public Process cmdProc;

  public OutputStream fos;

  public RowMetaInterface outputRowMeta;

  public byte[] binarySeparator;
  public byte[] binaryEnclosure;
  public byte[] binaryNewline;

  public boolean hasEncoding;

  public byte[][] binaryNullValue;

  public boolean oneFileOpened;

  public int fileNameFieldIndex;

  public ValueMetaInterface fileNameMeta;

  public IFileStreamsCollection fileStreamsCollection;

  public long lastFileFlushTime = 0;

  public String fileName;

  public int splitEvery;

  public TextFileOutputData() {
    super();

    nf = NumberFormat.getInstance();
    df = (DecimalFormat) nf;
    dfs = new DecimalFormatSymbols();

    daf = new SimpleDateFormat();
    dafs = new DateFormatSymbols();

    defaultDecimalFormat = (DecimalFormat) NumberFormat.getInstance();
    defaultDecimalFormatSymbols = new DecimalFormatSymbols();

    defaultDateFormat = new SimpleDateFormat();
    defaultDateFormatSymbols = new DateFormatSymbols();

    fileNameFieldIndex = -1;

    cmdProc = null;
    oneFileOpened = false;
  }

  public IFileStreamsCollection getFileStreamsCollection() {
    if ( fileStreamsCollection == null ) {
      if ( splitnr > 0 ) {
        fileStreamsCollection = new FileStreamsList();
      } else {
        fileStreamsCollection = new FileStreamsMap();
      }
    }
    return fileStreamsCollection;
  }
}


text:
package com.jcwhatever.nucleus.providers.mysql.datanode;

import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import com.jcwhatever.nucleus.Nucleus;
import com.jcwhatever.nucleus.collections.TreeEntryNode;
import com.jcwhatever.nucleus.managed.scheduler.IScheduledTask;
import com.jcwhatever.nucleus.managed.scheduler.Scheduler;
import com.jcwhatever.nucleus.providers.sql.ISqlDatabase;
import com.jcwhatever.nucleus.providers.sql.ISqlResult;
import com.jcwhatever.nucleus.providers.sql.ISqlTable;
import com.jcwhatever.nucleus.providers.sql.ISqlTableDefinition.ISqlTableColumn;
import com.jcwhatever.nucleus.providers.sql.datanode.ISqlDataNode;
import com.jcwhatever.nucleus.providers.sql.observer.SqlAutoCloseSubscriber;
import com.jcwhatever.nucleus.providers.sql.statement.ISqlTransaction;
import com.jcwhatever.nucleus.providers.sql.statement.update.ISqlUpdate;
import com.jcwhatever.nucleus.providers.sql.statement.update.ISqlUpdateFinal;
import com.jcwhatever.nucleus.storage.MemoryDataNode;
import com.jcwhatever.nucleus.utils.PreCon;
import com.jcwhatever.nucleus.utils.observer.future.FutureAgent;
import com.jcwhatever.nucleus.utils.observer.future.IFuture;
import com.jcwhatever.nucleus.utils.observer.future.IFuture.FutureStatus;
import org.bukkit.plugin.Plugin;

import javax.annotation.Nullable;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * Implementation of {@link ISqlDataNode}.
 */
public class SqlDataNode extends MemoryDataNode implements ISqlDataNode {

    private final Map<String, SqlNodeContext> _contextMap;
    private final Set<String> _dirtyNodes;
    private final Map<ISqlDatabase, Map<ISqlTable, Multimap<Object, SqlNodeContext>>> _contextByDb;
    private final List<FutureAgent> _saveAgents;

    private IScheduledTask _saveTask;

    /**
     * Constructor.
     *
     * @param plugin    The owning plugin.
     * @param valueMap  Map of node names to sql values.
     */
    public SqlDataNode(Plugin plugin,
                       Map<String, SqlNodeValue> valueMap) {
        super(plugin);

        PreCon.notNull(valueMap);

        _contextMap = new HashMap<>(valueMap.size() + 5);
        _dirtyNodes = new HashSet<>(valueMap.size());

        _contextByDb = new HashMap<>(5);
        _saveAgents = new ArrayList<>(10);

        for (SqlNodeValue value : valueMap.values()) {

            Map<ISqlTable, Multimap<Object, SqlNodeContext>> tableMap =
                    _contextByDb.get(value.table.getDatabase());

            if (tableMap == null) {
                tableMap = new HashMap<>(15);
                _contextByDb.put(value.table.getDatabase(), tableMap);
            }

            Multimap<Object, SqlNodeContext> keyMap = tableMap.get(value.table);

            if (keyMap == null) {
                keyMap = MultimapBuilder.hashKeys().arrayListValues().build();
                tableMap.put(value.table, keyMap);
            }

            SqlNodeContext context = new SqlNodeContext(value);

            _contextMap.put(context.nodeName, context);
            keyMap.put(value.indexValue, context);
            set(value.nodeName, value.value);
        }

        cleanAll();
    }

    @Override
    public void remove(String nodePath) {
        TreeEntryNode<String, Object> treeNode = getNodeFromPath(nodePath, false);
        if (treeNode == null)
            return;

        String fullPath = getPath(treeNode);
        if (_contextMap.containsKey(fullPath))
            _dirtyNodes.add(fullPath);

        markDirty();

        //noinspection ConstantConditions
        treeNode.getParent().removeChild(treeNode);
    }

    @Override
    @Nullable
    protected TreeEntryNode<String, Object> setNodeFromPath(String nodePath, Object value) {

        TreeEntryNode<String, Object> node = super.setNodeFromPath(nodePath, value);

        if (node != null) {
            String fullPath = getPath(node);
            if (_contextMap.containsKey(fullPath))
                _dirtyNodes.add(fullPath);
        }

        return node;
    }

    @Override
    protected void cleanAll() {

        super.cleanAll();
        _dirtyNodes.clear();
    }

    @Override
    public boolean saveSync() {
        cleanAll();
        save();
        return true;
    }

    @Override
    public IFuture save() {

        final FutureAgent agent = new FutureAgent();

        if (_dirtyNodes.size() == 0)
            return agent.cancel("Nothing to save.");

        if (_saveTask != null)
            return agent.cancel("Save is already in progress.");

        _saveAgents.add(agent);

        if (getPlugin().isEnabled()) {
            _saveTask = Scheduler.runTaskLater(Nucleus.getPlugin(), 5, new Runnable() {
                @Override
                public void run() {
                    saveToDb();
                }
            });
        } else {
            saveToDb();
        }

        return agent.getFuture();
    }

    private void saveToDb() {

        final List<ISqlTransaction> transactions = new ArrayList<>(_contextByDb.size());

        for (Entry<ISqlDatabase, Map<ISqlTable, Multimap<Object, SqlNodeContext>>>
                dbEntry : _contextByDb.entrySet()) {

            ISqlTransaction transaction = null;

            Map<ISqlTable, Multimap<Object, SqlNodeContext>> tableMap = dbEntry.getValue();
            assert tableMap != null;

            for (Entry<ISqlTable, Multimap<Object, SqlNodeContext>> tableEntry : tableMap.entrySet()) {

                Multimap<Object, SqlNodeContext> nodeContexts = tableEntry.getValue();

                for (Object indexValue : nodeContexts.keySet()) {

                    ISqlUpdate update = null;
                    ISqlUpdateFinal updateFinal = null;

                    Collection<SqlNodeContext> contexts = nodeContexts.get(indexValue);

                    for (SqlNodeContext context : contexts) {

                        if (!_dirtyNodes.contains(context.nodeName))
                            continue;

                        if (update == null) {
                            update = tableEntry.getKey().updateRows();
                        }

                        if (transaction == null) {
                            transaction = dbEntry.getKey().createTransaction();
                        }

                        updateFinal = update.set(context.columnName).value(getRoot().get(context.nodeName));
                    }

                    if (update != null) {

                        ISqlTableColumn primary = tableEntry.getKey().getDefinition().getPrimaryKey();
                        assert primary != null;

                        updateFinal.where(primary.getName()).isEqualTo(indexValue)
                                .addToTransaction(transaction);

                    }
                }
            }

            if (transaction != null) {
                transactions.add(transaction);
            }
        }

        cleanAll();

        if (transactions.size() == 0) {
            agentStatus(FutureStatus.CANCEL, "No changes.");
            return;
        }

        final Deque<ISqlTransaction> failedTransactions = new ArrayDeque<>(transactions.size());

        for (final ISqlTransaction transaction : transactions) {

            transaction.execute()
                    .onSuccess(new SqlAutoCloseSubscriber() {
                        @Override
                        public void onResult(@Nullable ISqlResult result, @Nullable String message) {

                            transactions.remove(transaction);

                            if (transactions.size() == 0) {
                                if (failedTransactions.size() == 0) {
                                    agentStatus(FutureStatus.SUCCESS);
                                } else {
                                    agentStatus(FutureStatus.ERROR,
                                            "{0} transaction(s) failed.", failedTransactions.size());
                                }
                            }
                        }
                    })
                    .onError(new SqlAutoCloseSubscriber() {
                        @Override
                        public void onResult(@Nullable ISqlResult result, @Nullable String message) {

                            transactions.remove(transaction);
                            failedTransactions.add(transaction);

                            if (transactions.size() == 0) {
                                agentStatus(FutureStatus.ERROR,
                                        "{0} transaction(s) failed.", failedTransactions.size());
                            }
                        }
                    });
        }
    }

    private void agentStatus(FutureStatus status) {
        agentStatus(status, null);
    }

    private void agentStatus(FutureStatus status, String message, Object... args) {

        for (FutureAgent agent : _saveAgents) {
            agent.sendStatus(status, message, args);
        }
        _saveAgents.clear();
        _saveTask = null;
    }

    public static class SqlNodeValue {

        private final String nodeName;
        private final String columnName;
        private final Object indexValue;
        private final ISqlTable table;
        private final Object value;

        public SqlNodeValue(String nodeName, String columnName,
                              Object indexValue, ISqlTable table, @Nullable Object value) {

            PreCon.notNull(nodeName);
            PreCon.notNullOrEmpty(columnName);
            PreCon.notNull(indexValue);
            PreCon.notNull(table);

            this.nodeName = nodeName;
            this.columnName = columnName;
            this.indexValue = indexValue;
            this.table = table;
            this.value = value;
        }

        public String getNodeName() {
            return nodeName;
        }

        public String getColumnName() {
            return columnName;
        }

        public ISqlTable getTable() {
            return table;
        }

        public Object getValue() {
            return value;
        }
    }

    private static class SqlNodeContext {

        final String nodeName;
        final String columnName;
        final Object indexValue;
        final ISqlTable table;

        SqlNodeContext(SqlNodeValue value) {

            this.nodeName = value.nodeName;
            this.columnName = value.columnName;
            this.indexValue = value.indexValue;
            this.table = value.table;
        }
    }
}


text:
<?php

class Employer extends Eloquent {
    public function User() {
        return $this->belongsTo('User');
    }
    public function Jobs()
    {
        return $this->hasMany('Jobs');
    }
    public static $rules = array(
        'name' => 'required',
        'email' => 'required|email|unique:users',
        'phone' => 'numeric',
        'username' => 'required|alpha_dash|unique:users',
        'password' => 'required|min:6',
        'image' => 'image',
        'industry' => 'required',
    );
    public static $edit_Rules = array(
        'name' => 'required',
        'email' => 'required|email',
        'phone' => 'numeric',
        'username' => 'required',
        'image' => 'image',
        'industry' => 'required',
    );
}


text:
<?php

namespace Symfony\Component\HttpKernel\Controller\ArgumentResolver;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\Controller\ValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;

/**
 * Yields the Session.
 *
 * @author Iltar van der Berg <kjarli@gmail.com>
 */
final class SessionValueResolver implements ArgumentValueResolverInterface, ValueResolverInterface
{
    /**
     * @deprecated since Symfony 6.2, use resolve() instead
     */
    public function supports(Request $request, ArgumentMetadata $argument): bool
    {
        @trigger_deprecation('symfony/http-kernel', '6.2', 'The "%s()" method is deprecated, use "resolve()" instead.', __METHOD__);

        if (!$request->hasSession()) {
            return false;
        }

        $type = $argument->getType();
        if (SessionInterface::class !== $type && !is_subclass_of($type, SessionInterface::class)) {
            return false;
        }

        return $request->getSession() instanceof $type;
    }

    public function resolve(Request $request, ArgumentMetadata $argument): array
    {
        if (!$request->hasSession()) {
            return [];
        }

        $type = $argument->getType();
        if (SessionInterface::class !== $type && !is_subclass_of($type, SessionInterface::class)) {
            return [];
        }

        return $request->getSession() instanceof $type ? [$request->getSession()] : [];
    }
}


text:
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.Logging;
using NakedFramework.Architecture.Component;
using NakedFramework.Architecture.FacetFactory;
using NakedFramework.Architecture.Reflect;
using NakedFramework.Architecture.Spec;
using NakedFramework.Architecture.SpecImmutable;
using NakedFramework.Core.Util;
using NakedFramework.Metamodel.Facet;
using NakedFramework.Metamodel.Utils;
using NakedObjects.Reflector.Utils;

namespace NakedObjects.Reflector.FacetFactory;

public sealed class CreateNewAnnotationFacetFactory : DomainObjectFacetFactoryProcessor, IAnnotationBasedFacetFactory {
    private readonly ILogger<CreateNewAnnotationFacetFactory> logger;

    public CreateNewAnnotationFacetFactory(IFacetFactoryOrder<CreateNewAnnotationFacetFactory> order, ILoggerFactory loggerFactory)
        : base(order.Order, loggerFactory, FeatureType.Actions) =>
        logger = loggerFactory.CreateLogger<CreateNewAnnotationFacetFactory>();

    private static bool IsCollectionOrVoid(Type type) =>
        type == typeof(void) ||
        CollectionUtils.IsGenericEnumerable(type) ||
        type.IsArray ||
        CollectionUtils.IsCollectionButNotArray(type);

    private static Type ToCreateType(MethodInfo method) {
        var returnType = method.ReturnType;
        return IsCollectionOrVoid(returnType) ? null : returnType;
    }

    public override IImmutableDictionary<string, ITypeSpecBuilder> Process(IReflector reflector, MethodInfo method, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary<string, ITypeSpecBuilder> metamodel) {
        if (method.IsDefined(typeof(CreateNewAttribute), false)) {
            var toCreateType = ToCreateType(method);

            if (toCreateType is not null && ObjectMethodHelpers.MatchParmsAndProperties(method, toCreateType, logger).Any()) {
                FacetUtils.AddFacet(new CreateNewFacet(toCreateType), specification);
            }
        }

        return metamodel;
    }
}


text:
<?php

namespace Propel\Generator\Model;

/**
 * The generic interface to a name generation algorithm.
 *
 * @author Hans Lellelid <hans@xmpl.org> (Propel)
 * @author Daniel Rall <dlr@finemaltcoding.com> (Torque)
 * @author Byron Foster <byron_foster@yahoo.com> (Torque)
 * @author Hugo Hamon <webmaster@apprendre-php.com> (Propel)
 */
interface NameGeneratorInterface
{
    /**
     * The character used by most implementations as the separator
     * between name elements.
     *
     * @var string
     */
    public const STD_SEPARATOR_CHAR = '_';

    /**
     * Traditional method for converting schema table and column names
     * to PHP names. The CONV_METHOD_XXX constants
     * define how names for columns and tables in the database schema
     * will be converted to PHP source names.
     *
     * @see PhpNameGenerator::underscoreMethod()
     *
     * @var string
     */
    public const CONV_METHOD_UNDERSCORE = 'underscore';

    /**
     * Heavier method for converting schema table and column names
     * to PHP names. Similar to {@link #CONV_METHOD_UNDERSCORE} but
     * this one will pass only letters and numbers through and will
     * use as separator any character that is not a letter or a number
     * inside the string to be converted. The CONV_METHOD_XXX
     * constants define how names for columns and tales in the
     * database schema will be converted to PHP source names.
     *
     * @var string
     */
    public const CONV_METHOD_CLEAN = 'clean';

    /**
     * Similar to {@link #CONV_METHOD_UNDERSCORE} except nothing is
     * converted to lowercase.
     *
     * @see PhpNameGenerator::phpNameMethod()
     *
     * @var string
     */
    public const CONV_METHOD_PHPNAME = 'phpname';

    /**
     * Specifies no modification when converting from a schema column
     * or table name to a PHP name.
     *
     * @var string
     */
    public const CONV_METHOD_NOCHANGE = 'nochange';

    /**
     * Given a list of String objects, implements an
     * algorithm which produces a name.
     *
     * @param array<string> $inputs Inputs used to generate a name.
     *
     * @throws \Propel\Generator\Exception\EngineException
     *
     * @return string The generated name.
     */
    public function generateName(array $inputs): string;
}


text:
require 'minitest/autorun'
require 'easy_weixin'

describe 'AccessToken' do
  before do
    @client = EasyWeixin::Api.new('app_id', 'app_secret')
  end

  it 'ssss' do
    puts @client.get_access_token
    # @client.get_access_token.must_equal "OHAI!"
  end
end


text:
/**
 * Gerado pela ferramenta Amaterasu Tool
 */
package br.com.amaterasu.bo.validator;

import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import br.com.amaterasu.util.LogUtil;

@FacesValidator("required")
public class RequiredValidator implements Validator {

	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		Map<String, String> param = context.getExternalContext()
				.getRequestParameterMap();
		if (param.get("skipRequired") == null
				|| param.get("skipRequired").equals("false")) {
			UIInput input = (UIInput) component;
			if (value == null || value.toString().trim().isEmpty()) {
				FacesMessage msg = new FacesMessage(input.getRequiredMessage());
				msg.setSeverity(FacesMessage.SEVERITY_ERROR);
				LogUtil.debug(input.getRequiredMessage());
				throw new ValidatorException(msg);
			}
		}
	}

}


text:
<EditorStyle name="Base16 Atelier Seaside Dark"
             _description="Color schemes for hackers.">
  <!--
     - https://github.com/chriskempson/base16
     - Scheme: Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/seaside/)
     -->
  <Color name="base00" value="#131513"/>
  <Color name="base01" value="#242924"/>
  <Color name="base02" value="#5e6e5e"/>
  <Color name="base03" value="#687d68"/>
  <Color name="base04" value="#809980"/>
  <Color name="base05" value="#8ca68c"/>
  <Color name="base06" value="#cfe8cf"/>
  <Color name="base07" value="#f4fbf4"/>
  <Color name="base08" value="#e6193c"/>
  <Color name="base09" value="#87711d"/>
  <Color name="base0A" value="#98981b"/>
  <Color name="base0B" value="#29a329"/>
  <Color name="base0C" value="#1999b3"/>
  <Color name="base0D" value="#3d62f5"/>
  <Color name="base0E" value="#ad2bee"/>
  <Color name="base0F" value="#e619c3"/>

  <!-- Text -->
  <Style name="text" color="base05" bgColor="base00"/>
  <Style name="text.background.readonly" color="base00"/>
  <Style name="text.background.searchresult" color="base0F"/>
  <Style name="text.background.searchresult-main" color="base09"/>
  <Style name="text.preprocessor" color="base0C"/>
  <Style name="text.selection" bgColor="base02"/>

  <!-- Keywords -->
  <Style name="keyword" color="base0E"/>
  <Style name="keyword.access" color="base08" weight="Bold"/>
  <Style name="keyword.exceptions" color="base08"/>
  <Style name="keyword.jump" color="base08" weight="Bold"/>
  <Style name="keyword.misc" color="base0A"/>
  <Style name="keyword.operator" color="base08" weight="Bold"/>
  <Style name="keyword.semantic.error" color="base07" bgColor="base08"/>
  <Style name="keyword.semantic.field" color="base05"/>
  <Style name="keyword.semantic.method" color="base05"/>
  <Style name="keyword.semantic.property" color="base05"/>
  <Style name="keyword.semantic.type" color="base0A"/>
  <Style name="keyword.type" color="base0A"/>

  <!-- Miscellaneous -->
  <Style name="comment" color="base03"/>
  <Style name="comment.keyword.todo" color="base0A" bgColor="base01"/>
  <Style name="constant" color="base09"/>
  <Style name="constant.language.void" color="base0A"/>
  <Style name="iconbar" color="base01"/>
  <Style name="iconbar.separator" color="base02"/>
  <Style name="linenumber" color="base03" bgColor="base00"/>
  <Style name="marker.bracket" color="base03" bgColor="base02"/>
  <Style name="marker.line" color="base01"/>
  <Style name="marker.ruler" color="base01"/>
  <Style name="string" color="base0B"/>
  <Style name="string.escape" color="base0F"/>
  <Style name="tooltip" color="base03" bgColor="base01"/>
  <Style name="tooltip.pager.text" color="base06"/>
  <Style name="tooltip.pager.triangle" color="base06"/>
  <Style name="xml" color="base05"/>
  <Style name="xml.cdata" color="base0B"/>
  <Style name="xml.name" color="base0D"/>
  <Style name="xml.attribute" color="base0A"/>

  <!-- Diff -->
  <Style name="diff.header" color="base0D" weight="Bold"/>
  <Style name="diff.header-newfile" color="base0B" weight="Bold"/>
  <Style name="diff.header-oldfile" color="base08" weight="Bold"/>
  <Style name="diff.line-added" color="base0B"/>
  <Style name="diff.line-removed" color="base08"/>
  <Style name="diff.location" color="base0A"/>
</EditorStyle>


text:
import resource from 'resource-router-middleware';
import huisnummers from '../models/huisnummers';

// export default ({ config, db }) => resource({
export default () => resource({
  id : 'huisnummer',
  load(req, id, callback) {
    const huisnummer = huisnummers.find(x => x.id == id);
    const err = huisnummer ? null : 'Not found';
    callback(err, huisnummer);
  },
  index({ params }, res) {
    res.json(huisnummers);
  },
  create({ body }, res) {
    body.id = huisnummers.length.toString(36);
    huisnummers.push(body);
    res.json(body);
  },
  read({ huisnummer }, res) {
    res.json(huisnummer);
  },
  update({ huisnummer, body }, res) {
    for (let key in body) {
      if (key !== 'id') huisnummer[key] = body[key];
    }
    res.sendStatus(204);
  },
  delete({ huisnummer }, res) {
    huisnummers.splice(huisnummers.indexOf(huisnummer), 1);
    res.sendStatus(204);
  }
});


text:
from .Paprika3List import Paprika3List
from .BringList import BringList
from .wunderlist import WuList


text:
namespace StatTag.Controls
{
    partial class DateTimeValueProperties
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
            this.chkShowTime = new System.Windows.Forms.CheckBox();
            this.chkShowDate = new System.Windows.Forms.CheckBox();
            this.cboDate = new System.Windows.Forms.ComboBox();
            this.cboTime = new System.Windows.Forms.ComboBox();
            tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
            tableLayoutPanel1.SuspendLayout();
            this.SuspendLayout();
            //
            // tableLayoutPanel1
            //
            tableLayoutPanel1.AutoSize = true;
            tableLayoutPanel1.ColumnCount = 2;
            tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle());
            tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            tableLayoutPanel1.Controls.Add(this.chkShowTime, 0, 1);
            tableLayoutPanel1.Controls.Add(this.chkShowDate, 0, 0);
            tableLayoutPanel1.Controls.Add(this.cboDate, 1, 0);
            tableLayoutPanel1.Controls.Add(this.cboTime, 1, 1);
            tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
            tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
            tableLayoutPanel1.Margin = new System.Windows.Forms.Padding(3, 3, 3, 10);
            tableLayoutPanel1.Name = "tableLayoutPanel1";
            tableLayoutPanel1.Padding = new System.Windows.Forms.Padding(0, 0, 3, 0);
            tableLayoutPanel1.RowCount = 2;
            tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
            tableLayoutPanel1.Size = new System.Drawing.Size(259, 80);
            tableLayoutPanel1.TabIndex = 4;
            //
            // chkShowTime
            //
            this.chkShowTime.AutoSize = true;
            this.chkShowTime.Dock = System.Windows.Forms.DockStyle.Fill;
            this.chkShowTime.Location = new System.Drawing.Point(3, 44);
            this.chkShowTime.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
            this.chkShowTime.Name = "chkShowTime";
            this.chkShowTime.Size = new System.Drawing.Size(130, 32);
            this.chkShowTime.TabIndex = 1;
            this.chkShowTime.Text = "Show time";
            this.chkShowTime.UseVisualStyleBackColor = true;
            this.chkShowTime.CheckedChanged += new System.EventHandler(this.chkShowTime_CheckedChanged);
            //
            // chkShowDate
            //
            this.chkShowDate.AutoSize = true;
            this.chkShowDate.Dock = System.Windows.Forms.DockStyle.Fill;
            this.chkShowDate.Location = new System.Drawing.Point(3, 4);
            this.chkShowDate.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
            this.chkShowDate.Name = "chkShowDate";
            this.chkShowDate.Size = new System.Drawing.Size(130, 32);
            this.chkShowDate.TabIndex = 0;
            this.chkShowDate.Text = "Show date";
            this.chkShowDate.UseVisualStyleBackColor = true;
            this.chkShowDate.CheckedChanged += new System.EventHandler(this.chkShowDate_CheckedChanged);
            //
            // cboDate
            //
            this.cboDate.Dock = System.Windows.Forms.DockStyle.Fill;
            this.cboDate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboDate.Enabled = false;
            this.cboDate.FormattingEnabled = true;
            this.cboDate.Location = new System.Drawing.Point(139, 4);
            this.cboDate.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
            this.cboDate.Name = "cboDate";
            this.cboDate.Size = new System.Drawing.Size(114, 36);
            this.cboDate.TabIndex = 2;
            this.cboDate.SelectedIndexChanged += new System.EventHandler(this.cboDate_SelectedIndexChanged);
            //
            // cboTime
            //
            this.cboTime.Dock = System.Windows.Forms.DockStyle.Fill;
            this.cboTime.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cboTime.Enabled = false;
            this.cboTime.FormattingEnabled = true;
            this.cboTime.Location = new System.Drawing.Point(139, 44);
            this.cboTime.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
            this.cboTime.Name = "cboTime";
            this.cboTime.Size = new System.Drawing.Size(114, 36);
            this.cboTime.TabIndex = 3;
            this.cboTime.SelectedIndexChanged += new System.EventHandler(this.cboTime_SelectedIndexChanged);
            //
            // DateTimeValueProperties
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(11F, 28F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.AutoSize = true;
            this.Controls.Add(tableLayoutPanel1);
            this.Font = new System.Drawing.Font("Segoe UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.Margin = new System.Windows.Forms.Padding(3, 4, 3, 4);
            this.Name = "DateTimeValueProperties";
            this.Size = new System.Drawing.Size(259, 80);
            this.Load += new System.EventHandler(this.DateTimeValueProperties_Load);
            tableLayoutPanel1.ResumeLayout(false);
            tableLayoutPanel1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.CheckBox chkShowDate;
        private System.Windows.Forms.CheckBox chkShowTime;
        private System.Windows.Forms.ComboBox cboDate;
        private System.Windows.Forms.ComboBox cboTime;
    }
}


text:
import { logger } from "@truffle/db/logger";
const debug = logger("db:process");

import gql from "graphql-tag";
import * as graphql from "graphql";
import { pascalCase } from "change-case";
import { singular } from "pluralize";

import type {
  CollectionName,
  Collections,
  Input,
  Resource
} from "@truffle/db/meta/collections";
import { IdObject, toIdObject } from "@truffle/db/meta/id";
import type { Definitions, Process } from "./types";

export interface ResourceProcessorsOptions<C extends Collections> {
  definitions: Definitions<C>;
}

export interface ResourceProcessors<C extends Collections> {
  load: <N extends CollectionName<C>>(
    collectionName: N,
    inputs: (Input<C, N> | undefined)[]
  ) => Process<C, (IdObject<C, N> | undefined)[]>;

  get: <N extends CollectionName<C>>(
    collectionName: N,
    id: string,
    document: graphql.DocumentNode
  ) => Process<C, Resource<C, N> | undefined>;

  find: <N extends CollectionName<C>>(
    collectionName: N,
    ids: (string | undefined)[],
    document: graphql.DocumentNode
  ) => Process<C, (Resource<C, N> | undefined)[]>;

  all: <N extends CollectionName<C>>(
    collectionName: N,
    document: graphql.DocumentNode
  ) => Process<C, Resource<C, N>[]>;
}

export const resourceProcessorsForDefinitions = <C extends Collections>(
  definitions: Definitions<C>
): ResourceProcessors<C> => {
  const names = <N extends CollectionName<C>>(collectionName: N) => {
    const { mutable } = definitions[collectionName];

    const resources = collectionName;
    const Resources = pascalCase(resources);

    const resource = singular(resources);
    const Resource = pascalCase(resource);

    const Mutate = mutable ? "Assign" : "Add";
    const resourcesMutate = `${resources}${Mutate}`;

    const ResourcesMutate = pascalCase(resourcesMutate);

    return {
      resource,
      resources,
      Resource,
      Resources,
      resourcesMutate,
      ResourcesMutate
    };
  };

  return {
    *load<N extends CollectionName<C>>(
      collectionName: N,
      inputs: Input<C, N>[]
    ): Process<C, IdObject<C, N>[]> {
      const { Resource, Resources, resources, resourcesMutate } = names(
        collectionName
      );

      const response = yield {
        type: "graphql",
        request: gql`
          mutation Load${Resources}(
            $inputs: [${Resource}Input]!
          ) {
            ${resourcesMutate}(input: { ${resources}: $inputs }) {
              ${resources} {
                id
              }
            }
          }
        `,
        variables: { inputs }
      };

      debug("response %o", response);
      return response.data[resourcesMutate][resources].map(toIdObject);
    },

    *get<N extends CollectionName<C>>(
      collectionName: N,
      id: string,
      document: graphql.DocumentNode
    ): Process<C, Resource<C, N>> {
      debug("get");
      const { Resource, resource } = names(collectionName);

      const fragments = document.definitions
        .filter(({ kind }) => kind === "FragmentDefinition")
        .filter(
          ({ typeCondition }: graphql.FragmentDefinitionNode) =>
            typeCondition.name.value === Resource
        )
        .map(
          ({ name: { value } }: graphql.FragmentDefinitionNode) => `...${value}`
        )
        .join("\n");

      const response = yield {
        type: "graphql",
        request: gql`
          ${document}
          query Get${Resource}($id: ID!) {
            ${resource}(id: $id) {
              ${fragments}
            }
          }
        `,
        variables: {
          id
        }
      };

      debug("response %o", response);

      return response.data[resource];
    },

    *find<N extends CollectionName<C>>(
      collectionName: N,
      ids: string[],
      document: graphql.DocumentNode
    ): Process<C, Resource<C, N>[]> {
      debug("find collectionName %o, ids: %o", collectionName, ids);
      const { Resource, Resources, resources } = names(collectionName);

      const fragments = document.definitions
        .filter(({ kind }) => kind === "FragmentDefinition")
        .filter(
          ({ typeCondition }: graphql.FragmentDefinitionNode) =>
            typeCondition.name.value === Resource
        )
        .map(
          ({ name: { value } }: graphql.FragmentDefinitionNode) => `...${value}`
        )
        .join("\n");

      const request = gql`
        ${document}
        query Find${Resources}($ids: [ID!]!) {
          ${resources}(filter: { ids: $ids }) {
            ${fragments}
          }
        }
      `;

      debug("request: %s", graphql.print(request));

      const response = yield {
        type: "graphql",
        request,
        variables: {
          ids
        }
      };
      debug("response %o", response);

      return response.data[resources];
    },

    *all<N extends CollectionName<C>>(
      collectionName: N,
      document: graphql.DocumentNode
    ): Process<C, Resource<C, N>[]> {
      const { Resource, Resources, resources } = names(collectionName);

      const fragments = document.definitions
        .filter(({ kind }) => kind === "FragmentDefinition")
        .filter(
          ({ typeCondition }: graphql.FragmentDefinitionNode) =>
            typeCondition.name.value === Resource
        )
        .map(
          ({ name: { value } }: graphql.FragmentDefinitionNode) => `...${value}`
        )
        .join("\n");

      const response = yield {
        type: "graphql",
        request: gql`
          ${document}
          query All${Resources} {
            ${resources} {
              ${fragments}
            }
          }
        `,
        variables: {}
      };

      return response.data[resources];
    }
  };
};


text:
title: First week:
contexts: office365,microsoft365
source: Microsoft public sites
translation: en
tools:
---


text:
<!doctype html>

    <meta charset="utf-8">
    <title>CSUG2014 - JMSDiExtraBundle</title>

    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <link rel="stylesheet" href="css/reveal.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/theme/night.css" id="theme">

    <link rel="stylesheet" href="lib/css/zenburn.css">

JMSDiExtraBundle

Why and how

                Source: http://jmsyst.com/bundles/JMSDiExtraBundle/1.1

The challenge

Configuration of services for project

location

format

structure

Location

/app/config

/yourBundle/Resources/config

Format

INI - limited

Advantages of using XML:

http://symfony.com/schema/dic/services/services-1.0.xsd

IDE autocomplete, etc

Structure

One huge file

Plenty of small files

The amount of configuration can overload

PHP 5.5 EE

Is there any hope?

There is...

JMSDiExtraBundle adds more powerful dependency injection features to Symfony2 and let's you:

configure dependency injection via annotations

convention-based dependency injection in controllers and services

Examples:

define service

constructor injection

property injection

method/getter injection

- define service

    class ProblemSolver
    {
        public function doTheMagic() {
            return 42;
        }
    }

standard way

    services:
        mrok.service.id:
            class: Mrok\PressBundle\Service\ProblemSolver

diextra way

    use JMS\DiExtraBundle\Annotation\Service;

    /** @Service("some.service.id") */
    class ProblemSolver
    {
        public function doTheMagic() {
            return 42;
        }
    }

- constructor injection

        /** @Service("some.service.id") */
        class ProblemSolver
        {
            private $em;

            public function __construct(EntityManager $em)
            {
                $this->em = $em;
            }

            public function doTheMagic() { ... }
        }

standard way

    services:
        mrok.service.id:
            class: Mrok\PressBundle\Service\ProblemSolver
            arguments: [@doctrine.orm.entity_manager]

diextra way

        use JMS\DiExtraBundle\Annotation as DI;

        /** @Service("some.service.id") */
        class ProblemSolver
        {
            private $em;

            /**
            * @DI\InjectParams({"em" = @DI\Inject("doctrine.orm.entity_manager")})
            * @param EntityManager $em
            */
            public function __construct(EntityManager $em)
            {
                $this->em = $em;
            }
        }

- property injection

        /** @Service("some.service.id") */
        class ProblemSolver
        {
            private $em;

            private $cacheDir;

            public function __construct(EntityManager $em)
            {
                $this->em = $em;
            }

            public function doTheMagic() { ... }
        }

standard way

    services:
        mrok.service.id:
            class: Mrok\PressBundle\Service\ProblemSolver
            properties:
                mailer: "@doctrine.orm.entity_manager"
                cacheDir: "%kernel.cache_dir%"

diextra way

        use JMS\DiExtraBundle\Annotation\Inject;

        class ProblemSolver
        {
            /** @Inject("doctrine.orm.entity_manager") */
            public $em;

            /** @Inject("%kernel.cache_dir%") */
            public $cacheDir;

            public function doTheMagic() { ... }
        }

- method/getter injection, lazy initialization

        class DefaultController extends Controller
        {

            /** @Route("/") */
            public function indexAction()
            {
                $out = ';(';
                if ($this->getMailer() instanceof \Swift_Mailer) {
                    $out = ';)';
                }

                return new Response($out);
            }

            /** @DI\LookupMethod("mailer") */
            protected function getMailer() { /* Nothing here */}

works only in controller

no benefits over $this->get('mailer')

Possibilities

        @Inject("security.context", required = false)

        @Inject("request", strict = false)

        @Service("some.service.id", parent="another.service.id", public=false)

        @Tag("doctrine.event_listener", attributes = {"event" = "postGenerateSchema"})

        @Observe("kernel.request", priority = 255) - Automatically registers a method
                                                     as listener to a certain event:

        @Observe(KernelEvents::REQUEST, priority = 255)

Possibilities 2

        @Validator("my_alias")

        @FormType

        @DoctrineListener or @DoctrineMongoDBListener

        class Controller
        {
            /** @Inject */
            private $session;

Worth to know:

lack of support of lazy services - think twice your services hierarchy

SSD is a must for huge projects in dev mode

development of this bundle seems to be ended

property injection - must be public, free access

... but there is constructor injection ... if you like

Tests

        /**
        * @DI\Service("mrok.problem_solver")
        */
        class ProblemSolver
        {

            /** @DI\Inject(required = false) */
            public $mailer;

            public function doTheMagic()
            {
                return (isset($this->mailer)) ? 42 : -1;
            }
        }

        class ProblemSolverTest extends \PHPUnit_Framework_TestCase
        {
            public function testDoTheMagic()
            {
                $ps = new ProblemSolver();
                $mock = \Mockery::mock('swift_mailer');
                $mock->shouldReceive('send')->times(0);

                $ps->mailer = $mock;

                $this->assertEquals(42, $ps->doTheMagic());
            }

            public function doTheMagicNoMailer()
            {
                $ps = new ProblemSolver();
                $this->assertEquals(-1, $ps->doTheMagic());
            }

        /**
        * @test
        * Obtain services from container, jmsdi in use
        */
        public function doTheMagicWithContainer()
        {
            $kernel = self::createKernel();
            $kernel->boot();

            $this->problemSolver = $kernel->getContainer()
                                   ->get('mrok.problem_solver');
            $this->assertEquals(42, $this->problemSolver->doTheMagic());
        }

More info:

            Project page: http://jmsyst.com/bundles/JMSDiExtraBundle/1.1

            Github: https://github.com/schmittjoh/JMSDiExtraBundle

Bonus - info for new jedi:

            A Year With Symfony by Matthias Noback

Feedback

The end


text:
An automatic presentation generator from a TreeSheets hierarchy.

Turn this TreeSheets hierarchy:

![TreeSheets](ts.png?raw=true "TreeSheets")

Into this presentation (.gif file - wait for load):

![Demo](TreeSlides.gif?raw=true "Demo")

# Intro:
[TreeSheets](http://strlen.com/treesheets) is a superb tool for editing & describing hierarchies.

TreeSlides automatically generates an hierarchical presentation from a TreeSheets file exported to XML.
The presentation can be navigated using the keyboard.

# Instructions:
1. Design your presentation in a linear-hierarchical manner:
  1. Each node (cell) can have text, and an optional child grid.
  2. Each child grid can have an arbitrary number of rows.
  3. Each row can have an arbitrary number of columns, but only the first column is displayed.
  4. Unlimited nesting is supported.
2. Export the treesheet to an XML file named topics.xml.
3. After compiling TreeSlides, place the xml near the TreeSlides.exe binary.
4. Optionally replace the bg.png file near the binary with another background image, having the same name.
5. To start the presetation, simply launch TreeSlides.exe.

# Presentation control:
* Right/Left buttons: go to next/previous node; traverses the tree in depth-first order
* Esc: go up one level
* Down/Up: go to next/previous sibling
* Home: restart presentation (go to root)
* F11: toggle full screen
* F5: reload from xml

# Example
An example presentation is provided in example.cts.


text:
package fragbag

import (
	"github.com/TuftsBCB/seq"
	"github.com/TuftsBCB/structure"
)

// Library defines the base methods necessary for any value to be considered
// a fragment library. All libraries that do *not* wrap another library should
// implement either the Structure or Sequence library interfaces and never
// both.
type Library interface {
	// Name returns a canonical name for this fragment library.
	Name() string

	// Size returns the number of fragments in the library.
	Size() int

	// FragmentSize returns the size of every fragment in the library.
	// All fragments in a library must have the same size.
	FragmentSize() int

	// Tag returns a uniquely identifying string for this type of fragment
	// library. It is used to dispatch on when opening a fragment library.
	Tag() string

	// SubLibrary returns a library contained inside of this one and returns
	// nil otherwise. When non-nil, this library is a wrapper library which
	// may implement both the StructureLibrary and SequenceLibrary interfaces.
	// When nil, it is guaranteed that only one of the interfaces will be
	// satisfied.
	SubLibrary() Library

	// String returns a custom string representation of the library.
	// This may be anything.
	String() string

	// FragmentString returns a custom string representation of the
	// given fragment.
	FragmentString(fragNum int) string

	// Fragment returns a representation of the sequence fragment
	// corresponding to fragNum. The representation is specific to the
	// library.
	Fragment(fragNum int) interface{}
}

// StructureLibrary adds methods specific to the operations defined on a
// library of structure fragments.
type StructureLibrary interface {
	Library

	// BestStructureFragment returns the fragment number of the best matching
	// fragment against the alpha-carbon coordinates given. Note that there
	// must be N coordinates where N is the size of each fragment in this
	// library.
	//
	// If no "good" fragments can be found, then `-1` is returned.
	BestStructureFragment([]structure.Coords) int

	// Atoms returns a list of alpha-carbon coordinates for a particular
	// fragment.
	Atoms(fragNum int) []structure.Coords
}

// SequenceLibrary adds methods specific to the operations defined on a
// library of sequence fragments.
type SequenceLibrary interface {
	Library

	// BestSequenceFragment returns the fragment number of the best matching
	// fragment against the sequence given. Note that the sequence given must
	// have length N where N is the size of each fragment in this library.
	//
	// If no "good" fragments can be found, then `-1` is returned.
	BestSequenceFragment(seq.Sequence) int

	// AlignmentProb returns the probability (as a negative log-odds) that
	// a query sequence matches a particular fragment.
	AlignmentProb(fragNum int, query seq.Sequence) seq.Prob
}

// WeightedLibrary adds methods specific to the operations defined on a
// library of weighted fragments.
type WeightedLibrary interface {
	Library

	// AddWeights turns a raw frequency into a weighted frequency. The
	// frequency given should be related to the fragment given. (e.g., The
	// frequency is the number of times the fragment appeared in a particular
	// query.)
	AddWeights(fragNum int, frequency float32) float32
}


text:
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
Object.defineProperty(exports, "__esModule", { value: true });
exports.IFormatterHelper = Symbol('IFormatterHelper');
//# sourceMappingURL=types.js.map


text:
package com.cloudibpm.blo.om.organization;

import com.cloudibpm.core.officecalendar.Holiday;
import com.cloudibpm.core.officecalendar.OfficeCalendar;
import com.cloudibpm.core.officecalendar.OfficeDay;
import com.cloudibpm.core.officecalendar.OfficeHours;
import com.cloudibpm.eso.om.organization.CalenderEso;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @Titel: 日历
 * @Description: 日历操作类
 * @Author: 作者
 * @CreateDate: 2019/4/15 10:14
 * @Version: 1.0
 */
@Service
//@Transactional
public class CalenderBlo {

    private final CalenderEso calenderEso;

    @Autowired
    public CalenderBlo(CalenderEso calenderEso){
        this.calenderEso =  calenderEso;
    }

    /**
     * 创建一个日历
     * @param calender
     */
    public int addCalender(OfficeCalendar calender){
        return calenderEso.addCalender(calender);
    }

    /**
     * 根据组织ID 查询所有日历
     * @param oid
     * @return
     */
    public List<OfficeCalendar> queryAllCalender(String oid){
        return calenderEso.queryAllCalender(oid);
    }

    /**
     * 设置某一天是否是假期  2019-09-10 是周几,今天是假期
     * @param holiday
     */
    public int setIsHoliday(Holiday holiday){
        Holiday hd = null;
        try {
            hd = calenderEso.queryIsHoliday(holiday.getHoliday(), holiday.getOwner());
        } catch (Exception e) {
            System.out.println("查询数据为空");
        }
        if(hd == null){
            return  calenderEso.setIsHoliday(holiday);
        }else {
            return 0;
        }
    }

    /**
     * 设置周几 是否是工作日   周一 是工作日
     * @param officeDay
     * @return
     */
    public int setYIsWorkDay(OfficeDay officeDay){
        return calenderEso.setYIsWorkDay(officeDay);
    }

    /**
     * 设置周一对应的工作时间段  8:00-12:00
     * @param officeHours
     * @return
     */
    public int setYPeriod(OfficeHours officeHours){
        return calenderEso.setYPeriod(officeHours);
    }

    /**
     * 查看某一天是否是假期
     * @param date
     * @param weekDay
     * @param oid
     * @return
     */
    public Boolean isHoliday(Date date,int weekDay,String calenderId,String oid){
        Holiday holiday = null;
        try {
            //如果假期表存在日期,即为假期
            holiday = calenderEso.queryIsHoliday(date,oid);
        } catch (Exception e) {
            System.out.println("查询数据为空");
        }
        if(holiday != null && holiday.getIsHoliday() == 1){
            return true;
        }else {
            //假期表不存在,查看是否工作日
            OfficeDay officeDay = calenderEso.queryIdByDayOfWeek(weekDay,calenderId,oid);
            if(officeDay != null && officeDay.getIsWorkDay() == 1){ //是工作日
                return false;
            }else {//不是工作日
                return true;
            }
        }
    }

    /**
     *根据周几查询对应ID
     * @param weekday
     * @param oid
     */
    public OfficeDay queryIdByDayOfWeek(int weekday,String parentId,String oid){
        return calenderEso.queryIdByDayOfWeek(weekday,parentId,oid);
    }

    /**
     * 列出某个日历下星期列表
     * @param parentId
     * @param oid
     * @return
     */
    public List<OfficeDay>  getWeekList(String parentId,String oid){
        return calenderEso.getWeekList(parentId,oid);
    }

    /**
     * 列出某个公司下假期表数据
     * @param oid
     * @return
     */
    public List<Holiday> getHolidayList(String oid){
        return calenderEso.getHolidayList(oid);
    }

    /**
     * 删除某公司假期表下的某个数据
     * @param ownerId  组织ID
     * @param id
     * @return
     */
    public void delHoliday(String ownerId, String id) {
        calenderEso.delHoliday(ownerId,id);
    }

    /**
     * 条件查询假期表数据
     * @param parentId
     * @param oid
     * @return
     */
    public List<Holiday>  searchHoliday(String startTime,String toTime,String oid) throws ParseException {
        Date st = null;
        Date tt = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtils.isNotBlank(startTime)){
            st = simpleDateFormat.parse(startTime);
        }
        if(StringUtils.isNotBlank(toTime)){
            tt = simpleDateFormat.parse(toTime);
        }
        if(st != null && tt != null){
            if(st.after(tt)){
                return null;
            }
        }
        return calenderEso.searchHoliday(st,tt,oid);

    }

    /**
     * 查询日历对应的周期
     * @param cid  日历id
     * @param oid
     * @return
     */
    public List<OfficeDay> getCalenderOfficeDay(String cid, String oid){
        return calenderEso.getCalenderOfficeDay(cid,oid);
    }

    /**
     * 根据日历周期id  周一id 查询周一对应时间段
     * @param officeDayId  周几id
     * @param oid
     * @return
     */
    public List<OfficeHours> getCalenderOfficeDayHours(String officeDayId, String oid){
        return calenderEso.getCalenderOfficeDayHours(officeDayId,oid);
    }

    /**
     * 查询日历下周一对应的时间段
     * @param cid  日历id
     * @param oid
     * @return
     */
    public List<OfficeHours> getOnMondayTime(String cid, String oid){
        return calenderEso.getOnMondayTime(cid,oid);
    }

    /**
     * 根据时间段id删除对应时间段
     * @param pid  日时间段id
     */
    public void delPeriod(String pid){
        calenderEso.delPeriod(pid);
    }

    /**
     * 重命名日历 根据日历id
     * @param cid  日历id
     * @param cname  日历名字
     * @param oid
     */
    public void renameCalender(String cid,String cname,String oid){
        calenderEso.renameCalender(cid,cname,oid);
    }

    /**
     * 根据日历id 删除日历 并删除对应周期和时间
     * @param cid  日历id
     * @param oid
     */
    public void delCalender(String cid,String oid){
        //1.根据日历id 删除日历
        calenderEso.delCalender(cid,oid);
        //2.根据日历Id 查询对应周期,并删除
        List<OfficeDay> officeDays = calenderEso.getCalenderOfficeDay(cid, oid);
        calenderEso.delOfficeDay(cid,oid);
        //3.根据周期id 删除对应时间段
        for (OfficeDay officeDay : officeDays) {
            calenderEso.delOfficeHours(officeDay.getId(),oid);
        }
    }

    /**
     * 查询公司下所有日历
     * @param oid   组织id
     */
    public List<OfficeCalendar> getAllCalender(String oid){
        return calenderEso.getAllCalender(oid);
    }
}


text:
package edu.pw.elka.gtna.graph.interfaces;

public interface WeightedGraph<N extends Node,E extends WeightedEdge<N>> extends Graph<N, E> {

}


text:
The `Context` is at the core of request processing in Ratpack applications.

It provides access to the HTTP Request and Response, allows flow control and has convenience methods for common handler operations.
More than that though, the Context is also a `Registry` of objects.  It provides access to these contextual objects via type-lookup
and allows arbitrary objects to be "pushed" into the context for use by downstream handlers.

To complete this lab:

1. Register `DefaultBookService` as the implementation of `BookService` to the context so it is available to all downstream handlers.
1. Simply refactor the common logic of the two handlers in `Lab03.java` into a new handler.  And make the resulting object available
to the now downstream handlers using the context to do so.
1. Make sure `BookSpec` passes.

This time the hints are in the TODO within `Lab03.java`

## This lab covers

* Registering objects in the registry
* Dynamically adding contextual objects
* Looking up contextual objects from the registry
* Injecting contextual objects into handlers

## Sign Posts

`ratpack.handling.Context`

`ratpack.registry.Registry`