text:
package org.easycassandra.persistence.cassandra;

import java.util.List;

import com.datastax.driver.core.ConsistencyLevel;
import com.datastax.driver.core.Session;

/**
 * @see {@link PersistenceAsync}
 * @author otaviojava
 *
 */
public class PersistenceSimpleAsyncImpl extends PersistenceBuilderImpl implements PersistenceAsync {

    private Session session;

    private RunCassandraCommandAsync command;

    PersistenceSimpleAsyncImpl(Session session, String keySpace) {
        super(session, keySpace);
        this.session = session;
        command = new RunCassandraCommandAsync(keySpace);
    }

    @Override
    public <T> boolean insert(T bean) {
        command.insert(bean, session);
        return true;
    }

    @Override
    public <T> boolean insert(T bean, ConsistencyLevel consistency) {
        command.insert(bean, session, consistency);
        return true;
    }

    @Override
    public <T> boolean insert(Iterable<T> beans) {
        command.insert(beans, session);
        return true;
    }

    @Override
    public <T> boolean insert(Iterable<T> beans, ConsistencyLevel consistency) {
        command.insert(beans, session, consistency);
        return true;
    }

    @Override
    public <T> boolean delete(T bean) {
        command.delete(bean, session);
        return true;
    }

    @Override
    public <T> boolean delete(T bean, ConsistencyLevel consistency) {
        command.delete(bean, session, consistency);
        return true;
    }

    @Override
    public <T> boolean delete(Iterable<T> beans) {
        command.delete(beans, session);
        return false;
    }

    @Override
    public <T> boolean delete(Iterable<T> beans, ConsistencyLevel consistency) {
        command.delete(beans, session, consistency);
        return false;
    }

    @Override
    public <K, T> boolean deleteByKey(K key, Class<T> bean) {
        command.deleteByKey(key, bean, session);
        return true;
    }

    @Override
    public <K, T> boolean deleteByKey(K key, Class<T> bean,
            ConsistencyLevel consistency) {
        command.deleteByKey(key, bean, session, consistency);
        return true;
    }

    @Override
    public <T> boolean update(T bean) {

        return insert(bean);
    }

    @Override
    public <T> boolean update(T bean, ConsistencyLevel consistency) {
        return insert(bean, consistency);
    }

    @Override
    public <T> boolean update(Iterable<T> beans) {
        return insert(beans);
    }

    @Override
    public <T> boolean update(Iterable<T> beans, ConsistencyLevel consistency) {
        return insert(beans, consistency);
    }

    @Override
    public boolean executeUpdate(String query) {
        session.executeAsync(query);
        return true;
    }

    @Override
    public <T> void removeAll(Class<T> bean) {
        command.removeAll(bean, session);
    }

    @Override
    public <T> void findAll(Class<T> bean,
            ResultAsyncCallBack<List<T>> resultCallBack) {
        command.findAll(bean, session, resultCallBack);
    }

    @Override
    public <T> void findAll(Class<T> bean, ConsistencyLevel consistency,
            ResultAsyncCallBack<List<T>> resultCallBack) {

        command.findAll(bean, session, resultCallBack, consistency);
    }

    @Override
    public <K, T> void findByKeys(Iterable<K> keys, Class<T> bean,
            ResultAsyncCallBack<List<T>> resultCallBack) {
        command.findByKeys(keys, bean, session, resultCallBack);
    }

    @Override
    public <K, T> void findByKeys(Iterable<K> keys, Class<T> bean,
            ConsistencyLevel consistency,
            ResultAsyncCallBack<List<T>> resultCallBack) {
        command.findByKeys(keys, bean, session, consistency, resultCallBack);

    }

    @Override
    public <K, T> void findByKey(K key, Class<T> bean,
            ResultAsyncCallBack<T> resultCallBack) {
        command.findByKey(key, bean, session, resultCallBack);
    }

    @Override
    public <K, T> void findByKey(K key, Class<T> bean,
            ConsistencyLevel consistency, ResultAsyncCallBack<T> resultCallBack) {

        command.findByKey(key, bean, session, resultCallBack, consistency);
    }

    @Override
    public <T, I> void findByIndex(String indexName, I index, Class<T> bean,
            ResultAsyncCallBack<List<T>> resultCallBack) {

        command.findByIndex(indexName, index, bean, session, resultCallBack);
    }

    @Override
    public <T, I> void findByIndex(String indexName, I index, Class<T> bean,
                       ConsistencyLevel consistency, ResultAsyncCallBack<List<T>> resultCallBack) {
        command.findByIndex(indexName, index, bean, session, consistency,
                resultCallBack);
    }

    @Override
    public <T, I> void findByIndex(I index, Class<T> bean,
            ResultAsyncCallBack<List<T>> resultCallBack) {

        command.findByIndex(index, bean, session, resultCallBack);
    }

    @Override
    public <T, I> void findByIndex(I index, Class<T> bean,
            ResultAsyncCallBack<List<T>> resultCallBack,
            ConsistencyLevel consistency) {
        command.findByIndex(index, bean, session, resultCallBack);
    }

    @Override
    public <T> void count(Class<T> bean,
            ResultAsyncCallBack<Long> resultCallBack) {
        command.count(bean, session, resultCallBack);
    }

    @Override
    public <T> void count(Class<T> bean,
             ConsistencyLevel consistency, ResultAsyncCallBack<Long> resultCallBack) {
        command.count(bean, session, consistency, resultCallBack);
    }

}


text:
# Meteor Collection Backup

Most systems in production allow for some sort of data backup. Meteor, however, does not
yet provide data backup of collections besides MongoDB's native export/import calls.

`$ meteor add conceptmate:backup`

This package does an initial stab to offer data export and import within Meteor. One
advantage of this package over native MongoDB calls is its independence of the underlying
database.

The backup package offers logic and UI to export data from Mongo.Collection and FS.Collection.
Each collection is exported into its JSON file. All JSON files are then zipped into a
single file, which can be downloaded from the server. FS.File data from FS.Collection
is stored in binary format in subfolders named as collection name and stored along
with JSON files in the zip archive.

Exported zip files can be uploaded to the server and imported afterwards. Before data is
imported into a collection, all existing data will be removed beforehand.

This package is not yet feature complete but it works in its core functionality. I will
be busy with other projects over the next few weeks and not be able to do incremental
changes. Therefore, I am searching for help of other Meteor geeks like me :).

**Feedback Welcome.** Please create an issue.

## Demo App (Meteor Todos List App)

An example app extending Meteor's todos list app demonstrates the conceptmate:backup
package. The app is deployed on [http://conceptmate-backup.meteor.com](http://conceptmate-backup.meteor.com).
The source code can be found [here](https://github.com/conceptmate/meteor-backup-example).
A screencast demonstrating the app is on [YouTube](https://youtu.be/omd8bKaQn5s).

## Set Up Collections for Export

To add a collection to a backup it needs to be added to ConceptMate.Collections.BackupCollections.
A Meteor method is provided.

```javascript
Meteor.call('addBackupCollection', collectionName);
```

Collections can be removed from a backup by calling the following Meteor function.

```javascript
Meteor.call('deleteBackupCollection', backupCollectionId);
```

All set backup collections will be exported when the following function is called
on the server. An archive with all collection data is then stored in the FS.Collection
accessible through ConceptMate.Collections.Backups.

```javascript
ConceptMate.Backup.exportAllCollections();
```

## Blaze UI Templates

This package also provides Blaze UI components hiding some of the complexity behind
a 'simpler' UI. In the following, screenshots of an app and sample code is provided.

### Backups List (client-side)

The `cmBackup_BackupList` template displays a table of all existing and ongoing exports.
Each row in the table is a backup. Backups can be downloaded by clicking on the arrow
down icon. A backup can be imported by clicking on the arrow up icon. The trash can icon
deletes a backup.

A backup can be triggered by clicking on the `Start Backup` button. To upload a backup
click on the `Choose File` button and choose a backup file from the file system. A file
is uploaded immediately!

![Screenshot Backups](/images/backups.png "Backups Screenshot")

An example on how to embed the `cmBackup_BackupList` as follows.

```html
<template name="BackupList">
  <div class="backup-list">
    {{#if Template.subscriptionsReady}}
      <div class="card">
        <div class="cc-button" action="open-backup-collection">
          {{i18n 'backup.collection.list'}}
        </div>

        {{> cmBackup_BackupList}}
      </div>
    {{else}}
      {{> DefaultLoading}}
    {{/if}}
  </div>
</template>
```

```javascript
Template.BackupList.events({

  /**
   *
   */
  'click *[action="open-backup-collection"]': function(e, tmpl) {
    FlowRouter.go('backup.collections');
  }
});
```

### Backup Collections List (client-side)

The backup collection table shows all collections that will be exported when an backup
is triggered. The order defines the order in which collections are exported, starting
with the lowest number.

![Screenshot Backup Collections](/images/backup-collections.png "Backup Collections Screenshot")

An example on how to embed the `cmBackup_BackupCollectionList` as follows.

```html
<template name="BackupCollectionList">
  <div class="backup-collection-list">
    {{#if Template.subscriptionsReady}}
      <div class="card">
        <div class="cc-button" action="add-backup-collection">
          {{i18n 'backup.collection.add'}}
        </div>

        {{> cmBackup_BackupCollectionList}}
      </div>
    {{else}}
      {{> DefaultLoading}}
    {{/if}}
  </div>
</template>
```

```javascript
Template.BackupCollectionList.events({

  /**
   *
   */
  'click *[action="add-backup-collection"]': function(e, tmpl) {
    FlowRouter.go('backup.collection.add');
  },

  /**
   *
   */
  'click .reactive-table tbody > tr': function(e, tmpl) {
    let backupCollectionId = this._id;

    FlowRouter.go('backup.collection.edit', {
      backupCollectionId: backupCollectionId
    });
  }
});
```

### Backup Collection Edit (client-side)

```html
<template name="BackupCollectionEdit">
  <div class="backup-collection-edit">
    {{#if Template.subscriptionsReady}}
      <div class="card">
        {{#with backupCollection}}
          {{> quickForm collection="ConceptMate.Collections.BackupCollections" id="backup-collection-form" buttonContent=(i18n 'apply') type=insertOrUpdate doc=this}}
        {{/with}}
      </div>
    {{else}}
      {{> DefaultLoading}}
    {{/if}}
  </div>
</template>
```

```javascript
/* global AutoForm */
/* global Template */
Template.BackupCollectionEdit.onCreated(function() {
  this.autorun(() => {
    let backupCollectionId = FlowRouter.getParam('backupCollectionId');

    if (backupCollectionId) {
      this.subscribe('backup-collection', backupCollectionId);
    }
  });
});

Template.BackupCollectionEdit.helpers({

  insertOrUpdate: function() {
    return !this._id ? 'insert' : 'update';
  },

  /**
   *
   */
  backupCollection: function() {
    let backupCollectionId = FlowRouter.getParam('backupCollectionId');
    return ConceptMate.Collections.BackupCollections.findOne({ _id: backupCollectionId }) || {};
  }
});

/**
 *
 */
Template.BackupCollectionEdit.events({

  /**
   *
   */
  'submit': function (e, tmpl) {
    e.preventDefault();

    if (AutoForm.validateForm("backup-collection-form")) {
      FlowRouter.go('backup.collections');
    }
  },
});
```

## Rights Management

This package also deals with rights managements, although at a very basic level. By
default all backups and backup collections are published to clients. In order to publish
that data only to users with specific roles, e.g., use alanning:roles package.

```javascript
ConceptMate = typeof ConceptMate !== 'undefined' ? ConceptMate : {};

/**
 * Only users with super-admin role can subscribe to ConceptMate.Collections.Backups
 * and ConceptMate.Collections.BackupCollections data.
 */
ConceptMate.BackupConfig = {
  allowed: function() {
    return Roles.userIsInRole(this.userId, ['super-admin'], Roles.GLOBAL_GROUP);
  }
};
```

Further, read and write access should be restricted in a production system.

```javascript
if (Meteor.isServer) {
  ConceptMate.Collections.Backups.allow({
    insert: function (userId, doc) {
      return Roles.userIsInRole(userId, ['super-admin']);
    },
    update: function (userId, doc, fields, modifier) {
      return Roles.userIsInRole(userId, ['super-admin']);
    },
    remove: function (userId, doc) {
      return Roles.userIsInRole(userId, ['super-admin']);
    }
  });

  ConceptMate.Collections.BackupCollections.allow({
    insert: function (userId, doc) {
      return Roles.userIsInRole(userId, ['super-admin']);
    },
    update: function (userId, doc, fields, modifier) {
      return Roles.userIsInRole(userId, ['super-admin']);
    },
    remove: function (userId, doc) {
      return Roles.userIsInRole(userId, ['super-admin']);
    }
  });
}
```

# Improvements

This code was written as part of a bigger project and extracted later into its
own package. Therefore, it might not be feature complete and not bug free. Please
file an issue or submit a PR and contribute to this project.

# License
This software is released under MIT license. Copyright is held by ConceptMate and refers to the author of this package, namely Roman Rädle.

The MIT License (MIT)

Copyright (c) 2016 ConceptMate

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

redpajama_set_name: RedPajamaGithub


text:
var cfg = require("./config.json");
var rsa = require("cryptico");
var net = require("net");
var hat = require("hat");
var md5 = require("MD5");
var col = require("colors");
var sql = require("mysql");

var packet_delimiter = String.fromCharCode(0);

var PacketHandler = require("./packethandler.js");
var ChatHandler   = require("./chathandler.js");

global.startsWith = function (needle, haystack) {
    return haystack.substring(0, needle.length) === needle;
};

global.log = function (msg, source) {
    source = source || "-";
    var date = new Date();

    var tD = function (num) {
        if(num < 10)
            return "0"+num;
        return num;
    }

    console.log((tD(date.getHours()) + ":" + tD(date.getMinutes()) + ":" +
                tD(date.getSeconds())).grey + (" [" + source.toString().toLowerCase() + "] ").magenta + msg);
};

log("generating security rsa key with " + cfg.general["rsa-length"].toString().red + " bits, this might take a while ...");
global.crypt = rsa.generateRSAKey(hat(), cfg.general["rsa-length"]);
log("... done.");

global.db;
global.clients = {};

var mysqlConnect = function () {
    global.db = sql.createConnection({
            host : cfg.mysql.host,
            user : cfg.mysql.user,
        password : cfg.mysql.pass,
        database : cfg.mysql.database
    });

    global.db.connect(function(err) {
        if(err) {
            log("error while connecting to database, waiting for 2000 ms".red);
            setTimeout(mysqlConnect, 2000);
        } else {
            log("connected to database".green);
        }
    });

    global.db.on("error", function(err) {
        log("database disconnected".red);
        if(err.code === "PROTOCOL_CONNECTION_LOST") {
            mysqlConnect();
        } else {
            throw err;
        }
    });
};

mysqlConnect();

process.argv.forEach(function (val, index, array) {
    if(val === "--fresh") {
        db.query("DROP TABLE IF EXISTS cgroup_has_history, cgroup_has_users, cgroup, cdirect_has_history, cdirect, users ;");
    }
});

db.query("CREATE TABLE IF NOT EXISTS users ( id INTEGER ( 8 ) AUTO_INCREMENT , name VARCHAR ( 64 ) NOT NULL , mail VARCHAR ( 255 ) NOT NULL , pass VARCHAR ( 32 ) NOT NULL, PRIMARY KEY ( id ) , UNIQUE KEY ( mail ) ) ENGINE = INNODB DEFAULT CHARSET = utf8 ;");
db.query("CREATE TABLE IF NOT EXISTS cdirect ( id INTEGER ( 10 ) AUTO_INCREMENT , usr_id_a INTEGER ( 8 ) NOT NULL , usr_id_b INTEGER ( 8 ) NOT NULL , PRIMARY KEY ( id ) , FOREIGN KEY ( usr_id_a ) REFERENCES users ( id ) ON DELETE CASCADE , FOREIGN KEY ( usr_id_b ) REFERENCES users ( id ) ON DELETE CASCADE , CHECK ( usr_id_a < usr_id_b ) , UNIQUE KEY ( usr_id_a , usr_id_b ) ) ENGINE = INNODB DEFAULT CHARSET = utf8 ;");
db.query("CREATE TABLE IF NOT EXISTS cdirect_has_history ( id INTEGER ( 16 ) AUTO_INCREMENT , did INTEGER ( 10 ) NOT NULL , uid INTEGER ( 8 ) NOT NULL , `timestamp` BIGINT ( 20 ) NOT NULL , data TEXT NOT NULL , PRIMARY KEY ( id ) , FOREIGN KEY ( did ) REFERENCES cdirect ( id ) ON DELETE CASCADE , FOREIGN KEY ( uid ) REFERENCES users ( id ) ON DELETE CASCADE ) ENGINE = INNODB DEFAULT CHARSET = utf8 ;");
db.query("CREATE TABLE IF NOT EXISTS cgroup ( id INTEGER ( 12 ) AUTO_INCREMENT , name VARCHAR ( 128 ) NOT NULL , PRIMARY KEY ( id ) ) ENGINE = INNODB DEFAULT CHARSET = utf8 ;");
db.query("CREATE TABLE IF NOT EXISTS cgroup_has_users ( gid INTEGER ( 12 ) NOT NULL , uid INTEGER ( 8 ) NOT NULL , PRIMARY KEY ( gid, uid ) , FOREIGN KEY ( gid ) REFERENCES cgroup ( id ) ON DELETE CASCADE , FOREIGN KEY ( uid ) REFERENCES users ( id ) ON DELETE CASCADE ) ENGINE = INNODB DEFAULT CHARSET = utf8 ;");
db.query("CREATE TABLE IF NOT EXISTS cgroup_has_history ( id INTEGER ( 16 ) AUTO_INCREMENT, gid INTEGER ( 12 ) NOT NULL , uid INTEGER ( 8 ) NOT NULL , `timestamp` BIGINT ( 20 ) NOT NULL , data TEXT NOT NULL , PRIMARY KEY ( id ) , FOREIGN KEY ( gid ) REFERENCES cgroup ( id ) ON DELETE CASCADE , FOREIGN KEY ( uid ) REFERENCES users ( id ) ON DELETE CASCADE ) ENGINE = INNODB DEFAULT CHARSET = utf8 ;");

global.send = function (data, scope) {
    var socket = scope.socket || scope;

    if(socket.write) {
        if(!(data instanceof String)) {
            data = JSON.stringify(data);

            if(scope.publickey) {
                data = rsa.encrypt(data, scope.publickey).cipher;
            }
        }

        socket.write(data + packet_delimiter);
    } else {
        log("scope doesn't have a write function");
    }
}

var packethandler = new PacketHandler();
var chathandler   = new ChatHandler();

packethandler.on(0, "low-level", function (packet, context) {
    // low-level
    // { t : 0 , p : <public-key> }

    if(packet.p) {
        context.publickey = packet.p;
        log("got publickey, now sending encrypted", context.hostname);
    } else return false;

}).on(1, "authentication", function (packet, context) {
    // authentication
    // { t : 1 , m : <mail> , p : <password> }

    if(packet.m && packet.p) {
        db.query("SELECT * FROM users WHERE pass=? AND mail=? ;", [md5(packet.p), packet.m], function (err, rows, fields) {
            if(rows.length > 0) {
                if(rows[0].id in clients) {
                    send({ "t" : 1, "s" : false , "r" : "That user is already logged in !" }, context);
                } else {
                    context.loggedin = true;
                    context.clientid = rows[0].id;
                    context.hostname = rows[0].mail;
                    send({ "t" : 1, "s" : true }, context);

                    clients[rows[0].id] = context;

                    packethandler.handle({ t : 4 }, context);
                    packethandler.handle({ t : 5 }, context);

                    log("authenticated as [id=" + rows[0].id + ", mail=" + rows[0].mail + "]", context.hostname);

                    db.query("SELECT cdirect.usr_id_a, cdirect.usr_id_b FROM cdirect WHERE cdirect.usr_id_a = ? OR cdirect.usr_id_b = ? ;", [context.clientid, context.clientid], function (err, rows, fields) {
                        for (var i = 0; i < rows.length; i++) {
                            var self = rows[i].usr_id_a,
                                friend = rows[i].usr_id_b;

                            if(friend === context.clientid) {
                                friend = self;
                                self = context.clientid;
                            }

                            send({ "t" : 10 , "p" : friend , "s" : ((friend in clients) ? 1 : 0) }, context);

                            if(friend in clients) {
                                send({ "t" : 10 , "p" : self , "s" : 1 }, clients[friend]);
                            }
                        };
                    });
                }
            } else {
                send({ "t" : 1, "s" : false , "r" : "Wrong password or username !" + (err || "") }, context);
            }
        });
    } else return false;

}).on(2, "registration", function (packet, context) {
    // registration request
    // { t : 2 , n : <name> , m : <mail> , p : <password> }

    if(packet.n && packet.m && packet.p) {
        db.query("INSERT INTO users ( name , mail , pass ) VALUES ( ? , ? , ? ) ;" [packet.n, packet.m, md5(packet.p)], function (err, rows, fields) {
            var success = true;
            if(err)
                success = false;

            send({ "t" : 2 , "s" : success }, context);
        });
    } else return false;

}).on(3, "ping-pong", function (packet, context) {
    // pong after a ping
    // { t : 3 , s : <salt> }

    if(packet.s && context.pingsalt && packet.s == context.pingsalt) {
        context.lastpong = Date.now();
        log("'pong!'", context.hostname)
    }
}).on(4, "list all direct chats", function (packet, context) {
    // list all direct chats
    // { t : 4 }

    db.query("SELECT cdirect.id, cdirect.usr_id_a, cdirect.usr_id_b FROM cdirect WHERE cdirect.usr_id_a = ? OR cdirect.usr_id_b = ? ;", [context.clientid, context.clientid], function (err, rows, fields) {
        var d = [];

        for (var i = 0; i < rows.length; i++) {
            var partner = rows[0].usr_id_a;
            if(partner == context.clientid)
                partner = rows[0].usr_id_b;

            d.push({ "i" : rows[i].id , "p" : partner });
        };

        send({ "t" : 4 , "d" : d }, context);
    });

}).on(5, "list all groups", function (packet, context) {
    // list all groups
    // { t : 5 }

    db.query("SELECT cgroup_has_users.gid FROM cgroup_has_users WHERE cgroup_has_users.uid = ? ;", [context.clientid], function (err, rows, fields) {
        var g = [];

        for (var i = 0; i < rows.length; i++) {
            g.push(rows[i].gid);
        };

        send({ "t" : 5 , "g" : g }, context);
    });

}).on(6, "fetch user info", function (packet, context) {
    // fetch info for user
    // { t : 6 , i : <user-id> }

    if(!isNaN(packet.i)) {
        db.query("SELECT users.name, users.mail FROM users WHERE users.id = ? ;", [packet.i], function (err, rows, fields) {
            if(rows.length > 0)
                send({ "t" : 6 , "i" : packet.i, "n" : rows[0].name , "m" : rows[0].mail }, context);
        });
    } else return false;

}).on(7, "fetch group info", function (packet, context) {
    // fetch info for group
    // { t : 7 , i : <group-id> }

    if(!isNaN(packet.i)) {
        db.query("SELECT cgroup.name, cgroup_has_users.uid FROM cgroup, cgroup_has_users WHERE cgroup.id = cgroup_has_users.gid AND cgroup.id = ? ;", [packet.i], function (err, rows, fields) {
            if(rows.length > 0) {
                var u = [];

                for (var i = 0; i < rows.length; i++) {
                    u.push(rows[i].uid);
                };

                send({ "t" : 7 , "n" : rows[0].name , "u" : u }, context);
            }
        });
    } else return false;

}).on(16, "directchat request", function (packet, context) {
    // request chat [direct]
    // { t : 16 , p : <partner-id> }

    if(!isNaN(packet.p)) {
        chathandler.getDirectForUsers(context.clientid, packet.p, function (chat) {
            send({ "t" : 16 , "i" : chat.chatid }, context);
        });
    } else return false;

}).on(17, "groupchat request", function (packet, context) {
    // request chat [group]
    // { t : 17 , n : <name> , (u : [<user1>, <user2>, ...]) }

    if(packet.n) {
        packet.u = packet.u || [];
        packet.u.push(context.clientid);
        chathandler.createGroup(packet.n, packet.u, function (chat) {
            send({ "t" : 17 , "i" : chat.chatid }, context);
        });
    } else return false;

}).on(18, "directchat message", function (packet, context) {
    // message [direct]
    // { t : 18 , i : <chat-id> , d : <data> }

    if(!isNaN(packet.i) && packet.d) {
        chathandler.getDirectForId(packet.i, function (chat) {
            chat.send(context.clientid, packet.d);
        });
    } else return false;

}).on(19, "groupchat message", function (packet, context) {
    // message [group]
    // { t : 19 , i : <group-id> , d : <data> }

    if(!isNaN(packet.i) && packet.data) {
        chathandler.getGroupForId(packet.i, function (chat) {
            chat.send(context.clientid, packet.d);
        });
    } else return false;

}).on(20, "fetch previous direct messages", function (packet, context) {
    // { t : 20 , i : <chat-id> , j : <from-id> }

    if(!isNaN(packet.i) && !isNaN(packet.j)) {
        db.query("SELECT * FROM cdirect_has_history WHERE cdirect_has_history.did = ? AND cdirect_has_history.id > ? ;", [packet.i, packet.j], function (err, rows, fields) {
            var h = [];

            for (var i = 0; i < rows.length; i++) {
                h.push({ "o" : rows[i].uid , "j" : rows[i].id , "l" : rows[i].timestamp , "d" : rows[i].data });
            };

            send({ "t" : 20 , "i" : packet.i , "h" : h }, context);
        });
    } else return false;

});

var conn_count = 0;

net.createServer(function (socket) {
    var context = {};
    var buffer = "";

    context.hostname = socket.remoteAddress + ":" + socket.remotePort;

    conn_count++;
    log("connection established", context.hostname);

    if(cfg.general.maxclients > 0 && conn_count > cfg.general.maxclients) {
        socket.destroy();
        log("kicked, because server has reached limit of " + cfg.general.maxclients, context.hostname);
        conn_count--;
    } else {
        context.socket = socket;
        context.loggedin = false;
        context.clientid;
        context.publickey = false;
        context.lastpong = Date.now();

        socket.setEncoding("utf8");

        send({ "t" : 0 , "p" : rsa.publicKeyString(global.crypt) }, context.socket);

        socket.on("data", function (data) {
            buffer += data;
            var ind = buffer.indexOf(packet_delimiter);

            while (ind > -1) {
                context.socket.emit("message", buffer.substring(0, ind));
                buffer = buffer.substring(ind+1);

                ind = buffer.indexOf(packet_delimiter);
            }
        }).on("message", function (data) {
            data = data.toString();

            if(!startsWith("{", data)) {
                data = rsa.decrypt(data, crypt).plaintext;
            }

            try {
                data = JSON.parse(data);
                packethandler.handle(data, context);
            } catch (e) {
                log(("invalid JSON " + data).red);
            }
        });

        socket.on("close", function (data) {
            log("Connection lost", context.hostname);
            conn_count--;

            db.query("SELECT cdirect.usr_id_a, cdirect.usr_id_b FROM cdirect WHERE cdirect.usr_id_a = ? OR cdirect.usr_id_b = ? ;", [context.clientid, context.clientid], function (err, rows, fields) {
                for (var i = 0; i < rows.length; i++) {
                    var self = rows[i].usr_id_a,
                        friend = rows[i].usr_id_b;

                    if(friend === context.clientid) {
                        friend = self;
                        self = context.clientid;
                    }

                    if(friend in clients) {
                        send({ "t" : 10 , "p" : self , "s" : 0 }, clients[friend]);
                    }
                };
            });

            if(context.clientid) {
                delete clients[context.clientid];
            }
        });

        socket.on("end", function (data) {
            log("end", context.hostname);
        })

        socket.on("error", function (data) {
            log("error " + data, context.hostname);
        });
    }

}).listen(cfg.general.port, cfg.general.host);

//  ping
setInterval(function () {
    log("invoking ping, to check if clients are reachable");

    var now = Date.now();

    for(var key in clients) {
        var client = clients[key];

        if(now - client.lastpong > cfg.client.timeout + cfg.client.ping) {
            log("client timed out", client.hostname);
            client.socket.destroy();
        } else {
            client.pingsalt = hat();
            send({ "t" : 3 , "s" : client.pingsalt }, client);
        }

    };
}, cfg.client.ping);

log("listening on " + cfg.general.host.cyan + ":" + cfg.general.port.toString().cyan);


text:
module Graphics.Perfract.Pt where

import Graphics.Perfract.Tupelo

type Pt a = XY a

type Pt3 = XYZ Rational

type Ln a = AB (Pt a)


text:
package net.sf.jailer.ui.databrowser.sqlconsole;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import javax.swing.JComponent;

import net.sf.jailer.database.Session;
import net.sf.jailer.datamodel.Association;
import net.sf.jailer.datamodel.Column;
import net.sf.jailer.datamodel.Table;
import net.sf.jailer.ui.databrowser.metadata.MDSchema;
import net.sf.jailer.ui.databrowser.metadata.MDTable;
import net.sf.jailer.ui.databrowser.metadata.MetaDataSource;
import net.sf.jailer.ui.syntaxtextarea.SQLCompletionProvider;

/**
 * A {@link SQLCompletionProvider} based on {@link SQLCompletionProvider}.
 *
 * @author Ralf Wisser
 */
public class MetaDataBasedSQLCompletionProvider extends SQLCompletionProvider<MetaDataSource, MDSchema, MDTable> {

	public MetaDataBasedSQLCompletionProvider(Session session, MetaDataSource metaDataSource) throws SQLException {
		super(session, metaDataSource);
	}

	@Override
	protected List<String> getColumns(MDTable table, long timeOut, JComponent waitCursorSubject) {
		try {
			return table.getColumns(timeOut, waitCursorSubject);
		} catch (SQLException e) {
			return Collections.emptyList();
		}
	}

	@Override
	protected MDSchema getDefaultSchema(MetaDataSource metaDataSource) {
		return metaDataSource.isInitialized()? metaDataSource.getDefaultSchema() : null;
	}

	@Override
	protected MDSchema findSchema(MetaDataSource metaDataSource, String name) {
		return metaDataSource.isInitialized()?  metaDataSource.find(name) : null;
	}

	@Override
	protected MDTable findTable(MDSchema schema, String name) {
		if (!schema.isLoaded()) {
			getTables(schema);
		}
		if (!schema.isLoaded()) {
			return null;
    	}
		return schema.find(name);
	}

	@Override
	protected String getTableName(MDTable table) {
		return table.getName();
	}

	private Map<MDSchema, MDSchema> triedToLoad = new WeakHashMap<MDSchema, MDSchema>();

	@Override
	protected List<MDTable> getTables(MDSchema schema) {
		if (!schema.isLoaded()) {
			if (!triedToLoad.containsKey(schema)) {
				triedToLoad.put(schema, schema);
				schema.loadTables(true, null, null, null);
				for (int i = 0; i < 10; ++i) {
					if (schema.isLoaded()) {
						return schema.getTables();
					}
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						// ignore
					}
				}
			}
			return Collections.emptyList();
    	}
		return schema.getTables();
	}

	@Override
	protected String getSchemaName(MDSchema schema) {
		return schema.getName();
	}

	@Override
	protected List<MDSchema> getSchemas(MetaDataSource metaDataSource) {
		return metaDataSource.getSchemas();
	}

	@Override
	protected List<Association> getAssociations(MDTable mdSource, MDTable mdDestination) {
		List<Association> result = new ArrayList<Association>();

		Table source = null;
		Table destination = null;

		if (mdSource != null) {
			source = metaDataSource.toTable(mdSource);
			if (source == null) {
				return result;
			}
		}
		if (mdDestination != null) {
			destination = metaDataSource.toTable(mdDestination);
			if (destination == null) {
				return result;
			}
		}

		if (source != null) {
			for (Association association: source.associations) {
				if (association.destination.equals(destination) || destination == null) {
					result.add(association);
				}
			}
		}
		return result;
	}

	@Override
	protected MDTable createDummyTable(MDSchema schema, String name, List<String> columns) {
		MDTable dummy = new MDTable(name, schema, false, false);
		dummy.setColumns(columns);
		return dummy;
	}

	@Override
	protected void setColumns(MDTable table, List<String> columns) {
		table.setColumns(columns);
	}

	@Override
	protected String getColumnInfo(MDTable table, String column) {
		if (table.isLoaded()) {
			try {
				List<String> cols = table.getColumns();
				List<Column> types = table.getColumnTypes();
				if (cols != null && types != null) {
					for (int i = 0; i < cols.size(); ++i) {
						if (cols.get(i).equals(column)) {
							return types.get(i).toSQL("").substring(types.get(i).name.length()).trim();
						}
					}
				}
			} catch (SQLException e) {
				return null;
			}
		}
		return null;
	}
}


text:
r"""Fetch reference URLs from all groups for a single shard id.

Because of an SSL memory leak in Python 3.5, fetching too many URLs in the same
Python process will OOM. This script wraps get_references_web_single_group.py
and calls it through subprocess for each group in the shard, where each group is
~5k URLs.

Launch with parallel_launch.py

Each job should finish in ~5 hours with the settings below.

GCS_BUCKET=gs://my-bucket
python parallel_launch.py \
    --num_instances=1000 \
    --cpu=4 \
    --mem=4 \
    --name=get-refs-web \
    --code_dir=./ \
    --log_dir=$GCS_BUCKET/logs \
    --setup_command="pip3 install aiohttp cchardet aiodns bs4 -q --user" \
    --command_prefix="python3 wikisum/get_references_web.py --out_dir=$GCS_BUCKET/wiki_references --shard_id"
"""
# pylint: enable=line-too-long
import math
import os
import subprocess as sp

from tensor2tensor.data_generators.wikisum import get_references_web_single_group as fetch
from tensor2tensor.data_generators.wikisum import utils

import tensorflow as tf

flags = tf.flags
FLAGS = flags.FLAGS

flags.DEFINE_string(
    "command",
    "python3 -m "
    "tensor2tensor.data_generators.wikisum.get_references_web_single_group",
    "Command to run get_references_web_single_group, without flags.")

def main(_):
  shard_urls = fetch.get_urls_for_shard(FLAGS.urls_dir, FLAGS.shard_id)
  num_groups = int(math.ceil(len(shard_urls) / fetch.URLS_PER_CLIENT))
  tf.logging.info("Launching get_references_web_single_group sequentially for "
                  "%d groups in shard %d. Total URLs: %d",
                  num_groups, FLAGS.shard_id, len(shard_urls))
  command_prefix = FLAGS.command.split() + [
      "--urls_dir=%s" % FLAGS.urls_dir,
      "--shard_id=%d" % FLAGS.shard_id,
      "--debug_num_urls=%d" % FLAGS.debug_num_urls,
  ]
  with utils.timing("all_groups_fetch"):
    for i in range(num_groups):
      command = list(command_prefix)
      out_dir = os.path.join(FLAGS.out_dir, "process_%d" % i)
      command.append("--out_dir=%s" % out_dir)
      command.append("--group_id=%d" % i)
      try:
        # Even on 1 CPU, each group should finish within an hour.
        sp.check_call(command, timeout=60*60)
      except sp.TimeoutExpired:
        tf.logging.error("Group %d timed out", i)

if __name__ == "__main__":
  tf.logging.set_verbosity(tf.logging.INFO)
  tf.app.run()


text:
/* right区域的样式 */

.topBox { height:88px;background:url("../images/back/topbg.gif") repeat-x;}
.topLeft{ height:88px;background:url("../images/back/topleft.jpg") no-repeat;float: left;width: 320px;}
.functionNav{ float:left;position:absolute;left:320px;height: 88px;display: block;}
.functionNav li{ float:left;width: 86px;height: 88px;display: block;text-align: center;}
.functionNav li a { display: block;width: 87px;height: 88px;text-decoration: none;}
.functionNav img{ margin-top: 10px;}
.selected{background: url("../images/back/navbg.png") no-repeat;}
.functionFont{ font-size: 14px;color: #D6E8F1;}
.topRight{ height:88px;float:right;background: url("../images/back/topright.jpg") no-repeat right;}
.topRight ul{ float:right;padding-top: 15px;padding-right: 12px;display: block;}
.topRight ul li{float:left;padding:0 9px;background: url("../images/back/line.gif")
no-repeat scroll right center}
.topRight ul li a{ font-size: 14px; color: #E9F2F7;text-decoration: none;}
.topRight ul li:last-child { background: transparent none repeat scroll 0% 0%;}
.userDiv{ clear: both; height: 30px;background: url("../images/back/ub1.png");float:right;margin-top:10px;
border-radius: 30px;position: relative;}
.userDiv span{ display: inline-block;padding-right: 10px;background: url("../images/back/user.png") no-repeat
scroll 15px 10px;line-height: 30px;font-size: 14px;color: #B8CEDA;padding-left: 35px;}
.userDiv i{ display: inline-block;margin-right:5px;line-height: 30px;font-size: 14px;color: #B8CEDA;}
.userDiv b{display: inline-block;width: 20px;height: 18px;background: url("../images/back/msg.png");
text-align:center;margin-right:13px;font-size: 14px;color:#fff;margin-top:7px;line-height: 18px;}
.leftBox{ width:186px;height:40px;background: url("../images/back/lefttop.gif") repeat-x;color:#fff;font-size:14px;
line-height: 40px;}
.leftBox .functionico{ display:block;margin:10px 8px 0 0;background: url("../images/back/leftico.png") no-repeat; width:20px;
height:21px;float:left;}
.leftMenu { overflow: hidden;background: url("../images/back/leftline.gif") repeat-y;display:block;}
.leftMenu dd{display:block;line-height: 20px;font-size: 14px;}
.leftMenu .title{ cursor:pointer;color: #000;}
.title span {display:block;float:left; margin:8px 8px 0 12px;}
.menuson{line-height:30px;background:#D9EBF3;}
.menuson li{ cursor:pointer;}
.menuson li.active{position:relative; background:url("../images/back/libg.png") repeat-x; line-height:30px; color:#fff;}
.menuson li cite{display:block; float:left; margin-left:32px; background:url("../images/back/list.gif") no-repeat; width:16px; height:16px; margin-top:7px;}
.menuson li.active cite{background:url("../images/back/list1.gif") no-repeat;}
.menuson li.active i{display:block; background:url("../images/back/sj.png") no-repeat; width:6px; height:11px; position:absolute; right:0;z-index:10000; top:9px; right:-1px;}
.menuson li a{ display:block; *display:inline; *padding-top:5px;}
.menuson li.active a{color:#fff;}
.menuson li .header{height:30px;}
.menuson li .submenus{background:#d9ebf3;padding:10px 0;border-bottom:1px solid #b7d5df;}
.menuson li .submenus li{height:25px;line-height:25px;padding-left:48px;border-left:1px solid #d9ebf3;}
.menuson li .submenus li.active{position:relative;right:-1px;border-left:none;background:#fff;}
.menuson li .submenus li a{padding-left:9px;color:#000000; background:url("../images/back/sub-menu-icon.png") 0 12px no-repeat;}
.menuson li .submenus li a:hover{color:#238ac5;}
.menuson li .submenus li.active a{color:#238ac5;}
.menuson li.active.open cite{margin-top:12px;margin-left:37px; background:url("../images/back/jtx.png") no-repeat;}
.bq{display:block;float:right;margin-right:10px;}
.place{height:40px; background:url(../images/back/righttop.gif) repeat-x;}
.place span{line-height:40px; font-weight:bold;float:left; margin-left:12px;}
.placeul li{float:left; line-height:40px; padding-left:7px; padding-right:12px; background:url(../images/back/rlist.gif) no-repeat right;}
.placeul li:last-child{background:none;}
.maindiv{ padding:10px;}

.formtitle,.formtitle1{border-bottom:solid 1px #d0dee5; line-height:35px; position:relative; height:35px; margin-bottom:28px;}
.formtitle1{margin-bottom:15px;}
.formtitle span,.formtitle1 span{font-weight:bold;font-size:14px; border-bottom:solid 3px #66c9f3;float:left; position:absolute; z-index:100; bottom:-1px; padding:0 3px; height:30px; line-height:30px;}

.regContent{height:960px;}
.frmBox{height:auto;margin-left:30px;}
.leftContent{float:left;margin-left:50px;width:400px;height:100px;}
.leftContent img{display:block;width:106px;height:100px;}
.userTitle{height:48px;line-height:48px;font-size:16px;font-family:"΢���ź�";}
.userName{height:48px;line-height:48px;font-size:16px;font-family:"΢���ź�";padding-left:30px;}
.frmContent{float:left;width:100%;}
.space{margin-top:30px;line-height:20px;}
.menu1Box{float:left;width:200px;height:400px;}
.menu1 {list-style:none;margin:0 auto;height:100%;width:200px;}
.menu1 li{ height:30px;width:180px;margin: 10 auto; text-align:center;float:left;font-size:16px;line-height:16px;}
.menu1 li a{text-decoration:none;}
.menu1 li a:hover{color:#CC0000;}
.regLine{ border:solid 1px #eee;margin-top:2px;}
.rowTitle{ padding:4px 0 2px 2px;font-size:18px;line-height:18px;font-weight:bold;}
.row1{float:left;padding:5px;text-align:center;height:30px;line-height:30px;}
.row2{float:left;height:30px;}
.cl{clear: both;}
.row2 input,select{ margin-top:10px;}
.wd120{width:120px;}
.wd100{width:100px;}
.wd160{width:160px;}
.hg100{height:100px;}
.hg150{height:150px;}
.hg200{height:200px;}
.hg250{height:250px;}
.hg300{height:300px;}
.hg500{height:500px;}
.hg600{height:600px;}
.hg750{height:750px;}
.sellen154{ width:154px;}
.sellen100{ width:100px;}
.upload{ display:block;width:72px;height:72px;background:url(../images/upload.png)}
.tablelist{border:solid 1px #cbcbcb; width:100%; clear:both;}
.tablelist th{background:url(../images/back/th.gif) repeat-x; height:34px; line-height:34px; border-bottom:solid 1px #b6cad2; text-indent:11px; text-align:left;}
.tablelist td{line-height:35px; text-indent:11px; border-right: dotted 1px #c7c7c7;}
.tablelink{color:#056dae;}
.tablelist tbody tr.odd{background:#f5f8fa;}
.tablelist tbody tr:hover{background:#e5ebee;}


text:
<?php

namespace Admin;

use DoctrineORMModule\Service\EntityManagerFactory;
use DoctrineORMModule\Options\DBALConnection;
use DoctrineORMModule\Service\DBALConnectionFactory;
use DoctrineORMModule\Service\ConfigurationFactory as ORMConfigurationFactory;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
use Zend\Mvc\MvcEvent;
use Zend\Session\Container;

class Module implements ServiceProviderInterface {
	public function getAutoloaderConfig() {
		return array (
				'Zend\Loader\ClassMapAutoloader' => array (
						__DIR__ . '/autoload_classmap.php'
				),
				'Zend\Loader\StandardAutoloader' => array (
						'namespaces' => array (
								__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__
						)
				)
		);
	}
	public function getConfig() {
		return include __DIR__ . '/config/module.config.php';
	}

	/**
	 * Retorna a configuração do service manager do módulo
	 *
	 * @return array
	 */
	public function getServiceConfig() {
		return array(
			'factories' => array(
// 				'doctrine.entitymanager.orm_default'	=> new EntityManagerFactory('orm_default'),
// 				'doctrine.connection.orm_default'		=> new DBALConnectionFactory('orm_default'),
// 				'doctrine.configuration.orm_default'	=> new ORMConfigurationFactory('orm_default'),
			),
		);
	}

	/**
	 * Executada no bootstrap do módulo
	 *
	 * @param MvcEvent $e
	 */
	public function onBootstrap(MvcEvent $e) {

		/**
		 * @var \Zend\ModuleManager\ModuleManager $moduleManager
		 */
		$moduleManager = $e->getApplication ()->getServiceManager ()->get ( 'modulemanager' );
		/**
		 * @var \Zend\EventManager\SharedEventManager $sharedEvents
		 */
		$sharedEvents = $moduleManager->getEventManager ()->getSharedManager ();

	//	adiciona eventos ao módulo
		$sharedEvents->attach ( 'Zend\Mvc\Controller\AbstractActionController', \Zend\Mvc\MvcEvent::EVENT_DISPATCH, array (
				$this,
				'mvcPreDispatch'
		), 100 );

	}

	/**
	 * Verifica se precisa fazer a autorização do acesso
	 *
	 * @param MvcEvent $event
	 *        	Evento
	 * @return boolean
	 */
	public function mvcPreDispatch($event) {
		$di = $event->getTarget ()->getServiceLocator ();
		$routeMatch = $event->getRouteMatch ();
		$moduleName = $routeMatch->getParam ( 'module' );
		$controllerName = $routeMatch->getParam ( 'controller' );
		$actionName = $routeMatch->getParam ( 'action' );

		$authService = $di->get ( 'Admin\Service\Auth' );
		if (! $authService->authorize ( $moduleName, $controllerName, $actionName )) {
			throw new \Exception ( 'Você não tem permissão para acessar este recurso.' );
		}
		return true;
	}
}
//Commit


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_loop_12.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml
Template File: sources-sink-12.tmpl.cpp
*/
/*
 * @description
 * CWE: 122 Heap Based Buffer Overflow
 * BadSource:  Allocate using new[] and set data pointer to a small buffer
 * GoodSource: Allocate using new[] and set data pointer to a large buffer
 * Sink: loop
 *    BadSink : Copy TwoIntsClass array to data using a loop
 * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse())
 *
 * */

#include "std_testcase.h"

namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_loop_12
{

#ifndef OMITBAD

void bad()
{
    TwoIntsClass * data;
    data = NULL;
    if(globalReturnsTrueOrFalse())
    {
        /* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */
        data = new TwoIntsClass[50];
    }
    else
    {
        /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
        data = new TwoIntsClass[100];
    }
    {
        TwoIntsClass source[100];
        {
            size_t i;
            /* Initialize array */
            for (i = 0; i < 100; i++)
            {
                source[i].intOne = 0;
                source[i].intTwo = 0;
            }
        }
        {
            size_t i;
            /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
            for (i = 0; i < 100; i++)
            {
                data[i] = source[i];
            }
            printIntLine(data[0].intOne);
            delete [] data;
        }
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() - use goodsource and badsink by changing the "if" so that
   both branches use the GoodSource */
static void goodG2B()
{
    TwoIntsClass * data;
    data = NULL;
    if(globalReturnsTrueOrFalse())
    {
        /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
        data = new TwoIntsClass[100];
    }
    else
    {
        /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
        data = new TwoIntsClass[100];
    }
    {
        TwoIntsClass source[100];
        {
            size_t i;
            /* Initialize array */
            for (i = 0; i < 100; i++)
            {
                source[i].intOne = 0;
                source[i].intTwo = 0;
            }
        }
        {
            size_t i;
            /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */
            for (i = 0; i < 100; i++)
            {
                data[i] = source[i];
            }
            printIntLine(data[0].intOne);
            delete [] data;
        }
    }
}

void good()
{
    goodG2B();
}

#endif /* OMITGOOD */

} /* close namespace */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */

#ifdef INCLUDEMAIN

using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_class_loop_12; /* so that we can use good and bad easily */

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
<?php

/**
 *	Check if user is authorized
 *
 *
 *	@return boolean true if access granted, false if no access
 */
function auth() {
  // You can insert your own code over here to check if the user is authorized.
  // If you use a session variable, you've got to start the session first (session_start())
  return true;
}

// @todo Work on plugins registration
// if (isset($config['plugin']) && !empty($config['plugin'])) {
// 	$pluginPath = 'plugins' . DIRECTORY_SEPARATOR . $config['plugin'] . DIRECTORY_SEPARATOR;
// 	require_once($pluginPath . 'filemanager.' . $config['plugin'] . '.config.php');
// 	require_once($pluginPath . 'filemanager.' . $config['plugin'] . '.class.php');
// 	$className = 'Filemanager'.strtoupper($config['plugin']);
// 	$fm = new $className($config);
// } else {
// 	$fm = new Filemanager($config);
// }

// we instantiate the Filemanager
$fm = new Filemanager();
?>


text:
import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { EntryService } from '../shared/entry.service';

@Component({
  selector: 'app-entry-comment-form',
  templateUrl: 'entry-comment-form.component.html'
})

export class EntryCommentFormComponent {
  name: string = "";
  comment: string = "";
  @Input() entryId: number;
  @Output() onCommentAdded = new EventEmitter<{ name: string; comment: string; }>();
  @ViewChild('commentForm') commentForm: NgForm;

  constructor(private entryService: EntryService) {

  }

  onSubmit(commentForm: NgForm) {
    if(this.commentForm.invalid) return;
    let comment = { name: this.name, comment: this.comment };
    this.entryService.addComment(this.entryId, comment)
        .then(() => {
          this.onCommentAdded.emit(comment);
            this.commentForm.resetForm();
        })
  }
}


text:
module.exports = {
  plugins: {
    'autoprefixer': process.env === 'production' ? options.autoprefixer : false,
    'precss': require('precss'),
  },
};