text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_listen_socket_33.cpp
Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml
Template File: source-sinks-33.tmpl.cpp
*/
/*
 * @description
 * CWE: 761 Free Pointer not at Start of Buffer
 * BadSource: listen_socket Read data using a listen socket (server side)
 * Sinks:
 *    GoodSink: free() memory correctly at the start of the buffer
 *    BadSink : free() memory not at the start of the buffer
 * Flow Variant: 33 Data flow: use of a C++ reference to data within the same function
 *
 * */

#include "std_testcase.h"

#include <wchar.h>

#ifdef _WIN32
#include <winsock2.h>
#include <windows.h>
#include <direct.h>
#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */
#define CLOSE_SOCKET closesocket
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define CLOSE_SOCKET close
#define SOCKET int
#endif

#define TCP_PORT 27015
#define LISTEN_BACKLOG 5

#define SEARCH_CHAR L'S'

namespace CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_listen_socket_33
{

#ifndef OMITBAD

void bad()
{
    wchar_t * data;
    wchar_t * &dataRef = data;
    data = (wchar_t *)malloc(100*sizeof(wchar_t));
    if (data == NULL) {exit(-1);}
    data[0] = L'\0';
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        wchar_t *replace;
        SOCKET listenSocket = INVALID_SOCKET;
        SOCKET acceptSocket = INVALID_SOCKET;
        size_t dataLen = wcslen(data);
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a listen socket */
            listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (listenSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = INADDR_ANY;
            service.sin_port = htons(TCP_PORT);
            if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
            {
                break;
            }
            acceptSocket = accept(listenSocket, NULL, NULL);
            if (acceptSocket == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed */
            recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* Append null terminator */
            data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
            /* Eliminate CRLF */
            replace = wcschr(data, L'\r');
            if (replace)
            {
                *replace = L'\0';
            }
            replace = wcschr(data, L'\n');
            if (replace)
            {
                *replace = L'\0';
            }
        }
        while (0);
        if (listenSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(listenSocket);
        }
        if (acceptSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(acceptSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    {
        wchar_t * data = dataRef;
        /* FLAW: We are incrementing the pointer in the loop - this will cause us to free the
         * memory block not at the start of the buffer */
        for (; *data != L'\0'; data++)
        {
            if (*data == SEARCH_CHAR)
            {
                printLine("We have a match!");
                break;
            }
        }
        free(data);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2G()
{
    wchar_t * data;
    wchar_t * &dataRef = data;
    data = (wchar_t *)malloc(100*sizeof(wchar_t));
    if (data == NULL) {exit(-1);}
    data[0] = L'\0';
    {
#ifdef _WIN32
        WSADATA wsaData;
        int wsaDataInit = 0;
#endif
        int recvResult;
        struct sockaddr_in service;
        wchar_t *replace;
        SOCKET listenSocket = INVALID_SOCKET;
        SOCKET acceptSocket = INVALID_SOCKET;
        size_t dataLen = wcslen(data);
        do
        {
#ifdef _WIN32
            if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR)
            {
                break;
            }
            wsaDataInit = 1;
#endif
            /* POTENTIAL FLAW: Read data using a listen socket */
            listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
            if (listenSocket == INVALID_SOCKET)
            {
                break;
            }
            memset(&service, 0, sizeof(service));
            service.sin_family = AF_INET;
            service.sin_addr.s_addr = INADDR_ANY;
            service.sin_port = htons(TCP_PORT);
            if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR)
            {
                break;
            }
            if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR)
            {
                break;
            }
            acceptSocket = accept(listenSocket, NULL, NULL);
            if (acceptSocket == SOCKET_ERROR)
            {
                break;
            }
            /* Abort on error or the connection was closed */
            recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0);
            if (recvResult == SOCKET_ERROR || recvResult == 0)
            {
                break;
            }
            /* Append null terminator */
            data[dataLen + recvResult / sizeof(wchar_t)] = L'\0';
            /* Eliminate CRLF */
            replace = wcschr(data, L'\r');
            if (replace)
            {
                *replace = L'\0';
            }
            replace = wcschr(data, L'\n');
            if (replace)
            {
                *replace = L'\0';
            }
        }
        while (0);
        if (listenSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(listenSocket);
        }
        if (acceptSocket != INVALID_SOCKET)
        {
            CLOSE_SOCKET(acceptSocket);
        }
#ifdef _WIN32
        if (wsaDataInit)
        {
            WSACleanup();
        }
#endif
    }
    {
        wchar_t * data = dataRef;
        {
            size_t i;
            /* FIX: Use a loop variable to traverse through the string pointed to by data */
            for (i=0; i < wcslen(data); i++)
            {
                if (data[i] == SEARCH_CHAR)
                {
                    printLine("We have a match!");
                    break;
                }
            }
            free(data);
        }
    }
}

void good()
{
    goodB2G();
}

#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 CWE761_Free_Pointer_Not_at_Start_of_Buffer__wchar_t_listen_socket_33; /* 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:
/*
 * special event API with Hammer.JS
 * version 0.9
 * author: Damien Antipa
 * https://github.com/dantipa/hammer.js
 */
(function ($) {
    var hammerEvents = [//'hold',
                        // 'tap',
                        // 'doubletap',
                        // 'transformstart',
                        // 'transform',
                        // 'transformend',
                        // 'dragstart',
                        // 'drag',
                        // 'dragend',
                        'swipe',
                        // 'release',
                        'pinch',
                        'pinchin',
                        'pinchout'];

    /*
     * HammerSEFunctions
     * maintains which function should be used to handle
     * events.
     *
     * _fn : is the original function used to handle events.
     *  Faster than _delegateFn, but it does not support delegated
     *  or bubbled events through jQuery.
     *
     * _delegateFn : a function that supports delegated/bubbled events
     *  in jQuery, but it is slower than _fn as it doesn't use a cached
     *  jQuery call ($target) to trigger from and must construct a new
     *  jQuery object based on the event target each time the event triggers.
     *
     * addDelegate : adds the handler guid created by jQuery to _delegateGuids.
     *
     * removeDelegate : removes the handler guid (if found) in _delegateGuids.
     *
     * getFn : returns either _fn or _delegateFn based on there being any handler
     *  guids saved in _delegateGuids. If there are no guids saved, then the faster
     *  function (_fn) is used. Otherwise, _delegateFn must be used and will be
     *  returned.
     *
     * destroy : destroys all dynamically generated properties in the object. This
     *  may be overkill, but it will help to reduce the chances of any sneaky
     *  memory leaks cropping up.
     */

    function HammerSEFunctions(/*event,$target*/){
        var event = arguments[0],
            $target = arguments[1];

        this._delegateGuids = [];

        this._fn = function(ev){
            $target.trigger($.Event(ev));

        };

        this._delegateFn = function(ev){

            var jqevt = $.Event(ev);
            $(jqevt.originalEvent.gesture.srcEvent.target).trigger(jqevt);

        };
    }
    HammerSEFunctions.prototype = {

        addDelegate : function(guid){

            this._delegateGuids.push(guid);
            return this;

        },

        removeDelegate : function(guid){
            var index = this._delegateGuids.indexOf(guid);

            if(index >= 0){

                this._delegateGuids.splice(index);

            }

            return this;
        },

        getFn : function(){

            return this._delegateGuids.length > 0 ? this._delegateFn : this._fn;

        },

        destroy : function(){

            this._fn = null;
            this._delegateFn = null;
            this._delegateGuids = null;

            delete this._fn;
            delete this._delegateFn;
            delete this._delegateGuids;

        }

    };

    $.each(hammerEvents, function(i, event) {

        $.event.special[event] = {

            setup: function(data, namespaces, eventHandle) {
                var $target = $(this),
                    hammer = $target.data('hammerjs');

                if (!hammer) {
                    hammer = new Hammer(this, data);
                    hammer.__Fns = {};
                    $target.data('hammerjs', hammer);
                }

                hammer.__Fns[event] = new HammerSEFunctions(event,$target);
            },
            add : function(handleObj) {
                var hammer = $(this).data('hammerjs');

                if (!!handleObj.selector) {
                    hammer.__Fns[event].addDelegate(handleObj.guid);
                }

                hammer.on(event,hammer.__Fns[event].getFn());
            },
            remove : function(handleObj) {
                var hammer = $(this).data('hammerjs');

                if (!!handleObj.selector) {
                    hammer.__Fns[event].removeDelegate(handleObj.guid);
                }

                hammer.off(event,hammer.__Fns[event].getFn());
            },
            teardown: function(namespaces) {
                var hammer = $(this).data('hammerjs');

                hammer.__Fns[event].destroy();
                delete hammer.__Fns[event];
            }
        };
    });
}(jQuery));

redpajama_set_name: RedPajamaGithub


text:
jQuery(document).ready(function(){
    var sticky = jQuery('.main-header');
    if (sticky.length > 0) {
        var navHeight = sticky.height();
        jQuery(window).scroll(function(){
            if (jQuery(window).scrollTop() > navHeight) {
                sticky.addClass('sticky-nav');
            }
            else {
                sticky.removeClass('sticky-nav');
            }
        });
    }
});


text:
"""Tests for proactor_events.py"""

import socket
import unittest
from unittest import mock

import asyncio
from asyncio.proactor_events import BaseProactorEventLoop
from asyncio.proactor_events import _ProactorSocketTransport
from asyncio.proactor_events import _ProactorWritePipeTransport
from asyncio.proactor_events import _ProactorDuplexPipeTransport
from asyncio import test_utils

class ProactorSocketTransportTests(test_utils.TestCase):

    def setUp(self):
        self.loop = self.new_test_loop()
        self.proactor = mock.Mock()
        self.loop._proactor = self.proactor
        self.protocol = test_utils.make_test_protocol(asyncio.Protocol)
        self.sock = mock.Mock(socket.socket)

    def test_ctor(self):
        fut = asyncio.Future(loop=self.loop)
        tr = _ProactorSocketTransport(
            self.loop, self.sock, self.protocol, fut)
        test_utils.run_briefly(self.loop)
        self.assertIsNone(fut.result())
        self.protocol.connection_made(tr)
        self.proactor.recv.assert_called_with(self.sock, 4096)

    def test_loop_reading(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._loop_reading()
        self.loop._proactor.recv.assert_called_with(self.sock, 4096)
        self.assertFalse(self.protocol.data_received.called)
        self.assertFalse(self.protocol.eof_received.called)

    def test_loop_reading_data(self):
        res = asyncio.Future(loop=self.loop)
        res.set_result(b'data')

        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)

        tr._read_fut = res
        tr._loop_reading(res)
        self.loop._proactor.recv.assert_called_with(self.sock, 4096)
        self.protocol.data_received.assert_called_with(b'data')

    def test_loop_reading_no_data(self):
        res = asyncio.Future(loop=self.loop)
        res.set_result(b'')

        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)

        self.assertRaises(AssertionError, tr._loop_reading, res)

        tr.close = mock.Mock()
        tr._read_fut = res
        tr._loop_reading(res)
        self.assertFalse(self.loop._proactor.recv.called)
        self.assertTrue(self.protocol.eof_received.called)
        self.assertTrue(tr.close.called)

    def test_loop_reading_aborted(self):
        err = self.loop._proactor.recv.side_effect = ConnectionAbortedError()

        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._fatal_error = mock.Mock()
        tr._loop_reading()
        tr._fatal_error.assert_called_with(
                            err,
                            'Fatal read error on pipe transport')

    def test_loop_reading_aborted_closing(self):
        self.loop._proactor.recv.side_effect = ConnectionAbortedError()

        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._closing = True
        tr._fatal_error = mock.Mock()
        tr._loop_reading()
        self.assertFalse(tr._fatal_error.called)

    def test_loop_reading_aborted_is_fatal(self):
        self.loop._proactor.recv.side_effect = ConnectionAbortedError()
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._closing = False
        tr._fatal_error = mock.Mock()
        tr._loop_reading()
        self.assertTrue(tr._fatal_error.called)

    def test_loop_reading_conn_reset_lost(self):
        err = self.loop._proactor.recv.side_effect = ConnectionResetError()

        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._closing = False
        tr._fatal_error = mock.Mock()
        tr._force_close = mock.Mock()
        tr._loop_reading()
        self.assertFalse(tr._fatal_error.called)
        tr._force_close.assert_called_with(err)

    def test_loop_reading_exception(self):
        err = self.loop._proactor.recv.side_effect = (OSError())

        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._fatal_error = mock.Mock()
        tr._loop_reading()
        tr._fatal_error.assert_called_with(
                            err,
                            'Fatal read error on pipe transport')

    def test_write(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._loop_writing = mock.Mock()
        tr.write(b'data')
        self.assertEqual(tr._buffer, None)
        tr._loop_writing.assert_called_with(data=b'data')

    def test_write_no_data(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr.write(b'')
        self.assertFalse(tr._buffer)

    def test_write_more(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._write_fut = mock.Mock()
        tr._loop_writing = mock.Mock()
        tr.write(b'data')
        self.assertEqual(tr._buffer, b'data')
        self.assertFalse(tr._loop_writing.called)

    def test_loop_writing(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._buffer = bytearray(b'data')
        tr._loop_writing()
        self.loop._proactor.send.assert_called_with(self.sock, b'data')
        self.loop._proactor.send.return_value.add_done_callback.\
            assert_called_with(tr._loop_writing)

    @mock.patch('asyncio.proactor_events.logger')
    def test_loop_writing_err(self, m_log):
        err = self.loop._proactor.send.side_effect = OSError()
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._fatal_error = mock.Mock()
        tr._buffer = [b'da', b'ta']
        tr._loop_writing()
        tr._fatal_error.assert_called_with(
                            err,
                            'Fatal write error on pipe transport')
        tr._conn_lost = 1

        tr.write(b'data')
        tr.write(b'data')
        tr.write(b'data')
        tr.write(b'data')
        tr.write(b'data')
        self.assertEqual(tr._buffer, None)
        m_log.warning.assert_called_with('socket.send() raised exception.')

    def test_loop_writing_stop(self):
        fut = asyncio.Future(loop=self.loop)
        fut.set_result(b'data')

        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._write_fut = fut
        tr._loop_writing(fut)
        self.assertIsNone(tr._write_fut)

    def test_loop_writing_closing(self):
        fut = asyncio.Future(loop=self.loop)
        fut.set_result(1)

        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._write_fut = fut
        tr.close()
        tr._loop_writing(fut)
        self.assertIsNone(tr._write_fut)
        test_utils.run_briefly(self.loop)
        self.protocol.connection_lost.assert_called_with(None)

    def test_abort(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._force_close = mock.Mock()
        tr.abort()
        tr._force_close.assert_called_with(None)

    def test_close(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr.close()
        test_utils.run_briefly(self.loop)
        self.protocol.connection_lost.assert_called_with(None)
        self.assertTrue(tr._closing)
        self.assertEqual(tr._conn_lost, 1)

        self.protocol.connection_lost.reset_mock()
        tr.close()
        test_utils.run_briefly(self.loop)
        self.assertFalse(self.protocol.connection_lost.called)

    def test_close_write_fut(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._write_fut = mock.Mock()
        tr.close()
        test_utils.run_briefly(self.loop)
        self.assertFalse(self.protocol.connection_lost.called)

    def test_close_buffer(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._buffer = [b'data']
        tr.close()
        test_utils.run_briefly(self.loop)
        self.assertFalse(self.protocol.connection_lost.called)

    @mock.patch('asyncio.base_events.logger')
    def test_fatal_error(self, m_logging):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._force_close = mock.Mock()
        tr._fatal_error(None)
        self.assertTrue(tr._force_close.called)
        self.assertTrue(m_logging.error.called)

    def test_force_close(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._buffer = [b'data']
        read_fut = tr._read_fut = mock.Mock()
        write_fut = tr._write_fut = mock.Mock()
        tr._force_close(None)

        read_fut.cancel.assert_called_with()
        write_fut.cancel.assert_called_with()
        test_utils.run_briefly(self.loop)
        self.protocol.connection_lost.assert_called_with(None)
        self.assertEqual(None, tr._buffer)
        self.assertEqual(tr._conn_lost, 1)

    def test_force_close_idempotent(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._closing = True
        tr._force_close(None)
        test_utils.run_briefly(self.loop)
        self.assertFalse(self.protocol.connection_lost.called)

    def test_fatal_error_2(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._buffer = [b'data']
        tr._force_close(None)

        test_utils.run_briefly(self.loop)
        self.protocol.connection_lost.assert_called_with(None)
        self.assertEqual(None, tr._buffer)

    def test_call_connection_lost(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        tr._call_connection_lost(None)
        self.assertTrue(self.protocol.connection_lost.called)
        self.assertTrue(self.sock.close.called)

    def test_write_eof(self):
        tr = _ProactorSocketTransport(
            self.loop, self.sock, self.protocol)
        self.assertTrue(tr.can_write_eof())
        tr.write_eof()
        self.sock.shutdown.assert_called_with(socket.SHUT_WR)
        tr.write_eof()
        self.assertEqual(self.sock.shutdown.call_count, 1)
        tr.close()

    def test_write_eof_buffer(self):
        tr = _ProactorSocketTransport(self.loop, self.sock, self.protocol)
        f = asyncio.Future(loop=self.loop)
        tr._loop._proactor.send.return_value = f
        tr.write(b'data')
        tr.write_eof()
        self.assertTrue(tr._eof_written)
        self.assertFalse(self.sock.shutdown.called)
        tr._loop._proactor.send.assert_called_with(self.sock, b'data')
        f.set_result(4)
        self.loop._run_once()
        self.sock.shutdown.assert_called_with(socket.SHUT_WR)
        tr.close()

    def test_write_eof_write_pipe(self):
        tr = _ProactorWritePipeTransport(
            self.loop, self.sock, self.protocol)
        self.assertTrue(tr.can_write_eof())
        tr.write_eof()
        self.assertTrue(tr._closing)
        self.loop._run_once()
        self.assertTrue(self.sock.close.called)
        tr.close()

    def test_write_eof_buffer_write_pipe(self):
        tr = _ProactorWritePipeTransport(self.loop, self.sock, self.protocol)
        f = asyncio.Future(loop=self.loop)
        tr._loop._proactor.send.return_value = f
        tr.write(b'data')
        tr.write_eof()
        self.assertTrue(tr._closing)
        self.assertFalse(self.sock.shutdown.called)
        tr._loop._proactor.send.assert_called_with(self.sock, b'data')
        f.set_result(4)
        self.loop._run_once()
        self.loop._run_once()
        self.assertTrue(self.sock.close.called)
        tr.close()

    def test_write_eof_duplex_pipe(self):
        tr = _ProactorDuplexPipeTransport(
            self.loop, self.sock, self.protocol)
        self.assertFalse(tr.can_write_eof())
        with self.assertRaises(NotImplementedError):
            tr.write_eof()
        tr.close()

    def test_pause_resume_reading(self):
        tr = _ProactorSocketTransport(
            self.loop, self.sock, self.protocol)
        futures = []
        for msg in [b'data1', b'data2', b'data3', b'data4', b'']:
            f = asyncio.Future(loop=self.loop)
            f.set_result(msg)
            futures.append(f)
        self.loop._proactor.recv.side_effect = futures
        self.loop._run_once()
        self.assertFalse(tr._paused)
        self.loop._run_once()
        self.protocol.data_received.assert_called_with(b'data1')
        self.loop._run_once()
        self.protocol.data_received.assert_called_with(b'data2')
        tr.pause_reading()
        self.assertTrue(tr._paused)
        for i in range(10):
            self.loop._run_once()
        self.protocol.data_received.assert_called_with(b'data2')
        tr.resume_reading()
        self.assertFalse(tr._paused)
        self.loop._run_once()
        self.protocol.data_received.assert_called_with(b'data3')
        self.loop._run_once()
        self.protocol.data_received.assert_called_with(b'data4')
        tr.close()

class BaseProactorEventLoopTests(test_utils.TestCase):

    def setUp(self):
        self.sock = mock.Mock(socket.socket)
        self.proactor = mock.Mock()

        self.ssock, self.csock = mock.Mock(), mock.Mock()

        class EventLoop(BaseProactorEventLoop):
            def _socketpair(s):
                return (self.ssock, self.csock)

        self.loop = EventLoop(self.proactor)
        self.set_event_loop(self.loop, cleanup=False)

    @mock.patch.object(BaseProactorEventLoop, '_call_soon')
    @mock.patch.object(BaseProactorEventLoop, '_socketpair')
    def test_ctor(self, socketpair, _call_soon):
        ssock, csock = socketpair.return_value = (
            mock.Mock(), mock.Mock())
        loop = BaseProactorEventLoop(self.proactor)
        self.assertIs(loop._ssock, ssock)
        self.assertIs(loop._csock, csock)
        self.assertEqual(loop._internal_fds, 1)
        _call_soon.assert_called_with(loop._loop_self_reading, (),
                                      check_loop=False)

    def test_close_self_pipe(self):
        self.loop._close_self_pipe()
        self.assertEqual(self.loop._internal_fds, 0)
        self.assertTrue(self.ssock.close.called)
        self.assertTrue(self.csock.close.called)
        self.assertIsNone(self.loop._ssock)
        self.assertIsNone(self.loop._csock)

    def test_close(self):
        self.loop._close_self_pipe = mock.Mock()
        self.loop.close()
        self.assertTrue(self.loop._close_self_pipe.called)
        self.assertTrue(self.proactor.close.called)
        self.assertIsNone(self.loop._proactor)

        self.loop._close_self_pipe.reset_mock()
        self.loop.close()
        self.assertFalse(self.loop._close_self_pipe.called)

    def test_sock_recv(self):
        self.loop.sock_recv(self.sock, 1024)
        self.proactor.recv.assert_called_with(self.sock, 1024)

    def test_sock_sendall(self):
        self.loop.sock_sendall(self.sock, b'data')
        self.proactor.send.assert_called_with(self.sock, b'data')

    def test_sock_connect(self):
        self.loop.sock_connect(self.sock, 123)
        self.proactor.connect.assert_called_with(self.sock, 123)

    def test_sock_accept(self):
        self.loop.sock_accept(self.sock)
        self.proactor.accept.assert_called_with(self.sock)

    def test_socketpair(self):
        self.assertRaises(
            NotImplementedError, BaseProactorEventLoop, self.proactor)

    def test_make_socket_transport(self):
        tr = self.loop._make_socket_transport(self.sock, asyncio.Protocol())
        self.assertIsInstance(tr, _ProactorSocketTransport)

    def test_loop_self_reading(self):
        self.loop._loop_self_reading()
        self.proactor.recv.assert_called_with(self.ssock, 4096)
        self.proactor.recv.return_value.add_done_callback.assert_called_with(
            self.loop._loop_self_reading)

    def test_loop_self_reading_fut(self):
        fut = mock.Mock()
        self.loop._loop_self_reading(fut)
        self.assertTrue(fut.result.called)
        self.proactor.recv.assert_called_with(self.ssock, 4096)
        self.proactor.recv.return_value.add_done_callback.assert_called_with(
            self.loop._loop_self_reading)

    def test_loop_self_reading_exception(self):
        self.loop.close = mock.Mock()
        self.proactor.recv.side_effect = OSError()
        self.assertRaises(OSError, self.loop._loop_self_reading)
        self.assertTrue(self.loop.close.called)

    def test_write_to_self(self):
        self.loop._write_to_self()
        self.csock.send.assert_called_with(b'\0')

    def test_process_events(self):
        self.loop._process_events([])

    @mock.patch('asyncio.base_events.logger')
    def test_create_server(self, m_log):
        pf = mock.Mock()
        call_soon = self.loop.call_soon = mock.Mock()

        self.loop._start_serving(pf, self.sock)
        self.assertTrue(call_soon.called)

        # callback
        loop = call_soon.call_args[0][0]
        loop()
        self.proactor.accept.assert_called_with(self.sock)

        # conn
        fut = mock.Mock()
        fut.result.return_value = (mock.Mock(), mock.Mock())

        make_tr = self.loop._make_socket_transport = mock.Mock()
        loop(fut)
        self.assertTrue(fut.result.called)
        self.assertTrue(make_tr.called)

        # exception
        fut.result.side_effect = OSError()
        loop(fut)
        self.assertTrue(self.sock.close.called)
        self.assertTrue(m_log.error.called)

    def test_create_server_cancel(self):
        pf = mock.Mock()
        call_soon = self.loop.call_soon = mock.Mock()

        self.loop._start_serving(pf, self.sock)
        loop = call_soon.call_args[0][0]

        # cancelled
        fut = asyncio.Future(loop=self.loop)
        fut.cancel()
        loop(fut)
        self.assertTrue(self.sock.close.called)

    def test_stop_serving(self):
        sock = mock.Mock()
        self.loop._stop_serving(sock)
        self.assertTrue(sock.close.called)
        self.proactor._stop_serving.assert_called_with(sock)

if __name__ == '__main__':
    unittest.main()


text:
require 'spec_helper'

RSpec.describe GitlabSchema.types['DiffRefs'] do
  specify { expect(described_class.graphql_name).to eq('DiffRefs') }

  specify { expect(described_class).to have_graphql_fields(:head_sha, :base_sha, :start_sha).only }

  specify { expect(described_class.fields['headSha'].type).to be_non_null }
  specify { expect(described_class.fields['baseSha'].type).not_to be_non_null }
  specify { expect(described_class.fields['startSha'].type).to be_non_null }
end


text:
from django.conf.urls.defaults import *
from wiki.views import wv

urlpatterns = patterns('',
    url('^$',             wv.redirect_to_index,   name='wiki_index'),
    url('^(.*)/edit/$',   wv.page_edit,           name='page_edit'),
    url('^(.*)/submit/$', wv.page_submit,         name='page_submit'),
    url('^(.*)/$',        wv.wiki_page,           name='wiki_page'),
)


text:
namespace OpenGLViewSample {

	// Should subclass MonoMac.AppKit.NSResponder
	[MonoMac.Foundation.Register("AppDelegate")]
	public partial class AppDelegate {
	}
}


text:
using Gelf4Net.Util;
using log4net.Core;
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Threading;

namespace Gelf4Net.Appender
{
    public class AsyncGelfAmqpAppender : GelfAmqpAppender
    {
        private BufferedLogSender _sender;

        public int Threads { get; set; }
        public int BufferSize { get; set; }

        public override void ActivateOptions()
        {
            base.ActivateOptions();

            var options = new BufferedSenderOptions
            {
                BufferSize = BufferSize,
                NumTasks = Threads,
            };
            _sender = new BufferedLogSender(options, SendMessageAsync, WaitToSendOnConnectionAsync, IsWaiting);
        }

        protected override void Append(LoggingEvent[] loggingEvents)
        {
            foreach (var loggingEvent in loggingEvents)
            {
                Append(loggingEvent);
            }
        }

        protected override void Append(LoggingEvent loggingEvent)
        {
            if (FilterEvent(loggingEvent))
            {
                _sender.QueueSend(this.RenderLoggingEvent(loggingEvent));
            }
        }

        protected override void OnClose()
        {
            Debug.WriteLine("Closing Async Appender");
            _sender.Stop();
            base.OnClose();
        }
    }
}


text:
package io.skysail.ext.oauth2

import io.skysail.ext.oauth2.config.OAuth2ConfigDescriptor

class OAuth2ClientParameters(val config: OAuth2ConfigDescriptor) {

  def clientId() = config.clientId()
  def clientSecret() = config.clientSecret()
  def scope() = config.scope()
  def redirectUri() = config.redirectUri()

}


text:
package org.springframework.boot.autoconfigure.cache;

import org.springframework.data.redis.cache.RedisCacheManager.RedisCacheManagerBuilder;

/**
 * Callback interface that can be used to customize a {@link RedisCacheManagerBuilder}.
 *
 * @author Dmytro Nosan
 * @since 2.2.0
 */
@FunctionalInterface
public interface RedisCacheManagerBuilderCustomizer {

	/**
	 * Customize the {@link RedisCacheManagerBuilder}.
	 * @param builder the builder to customize
	 */
	void customize(RedisCacheManagerBuilder builder);

}


text:
from module_kits.vtk_kit.mixins import SimpleVTKClassModuleBase
import vtk

class vtkSplineFilter(SimpleVTKClassModuleBase):
    def __init__(self, module_manager):
        SimpleVTKClassModuleBase.__init__(
            self, module_manager,
            vtk.vtkSplineFilter(), 'Processing.',
            ('vtkPolyData',), ('vtkPolyData',),
            replaceDoc=True,
            inputFunctions=None, outputFunctions=None)


text:
import { computed } from '@ember/object';
import { alias } from '@ember/object/computed';
import { inject as service } from '@ember/service';
import Controller from '@ember/controller';
import C from 'ui/utils/constants';

export default Controller.extend({
  settings: service(),
  scope: service(),

  modelError: false,
  modelResolved: false,
  hasHosts: true,
  forumsLink: C.EXT_REFERENCES.FORUM,
  companyLink: C.EXT_REFERENCES.COMPANY,
  githubLink: C.EXT_REFERENCES.GITHUB,
  docsLink: alias('settings.docsBase'),

  latestAnnouncement: computed('model.announcements', function() {
    if (this.get('model.announcements.topics')) {
      let sorted = this.get('model.announcements.topics').sortBy('id');
      var announcement = sorted[sorted.length-1];
      return {
        title: announcement.title,
        link: `${this.get('forumsLink')}/t/${announcement.slug}`,
        created: announcement.created_at
      };
    }
  }),

  modelObserver: function() {
    if (this.get('model.resolved')) {

      // @@TODO@@ - need to add some error handling
      this.set('modelResolved', true);
    }

    if (this.get('model.error') ) {

      this.set('modelError', true);
    }

  }.observes('model'),

});


text:
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans   http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
        <property name="driverClass" value="org.h2.Driver"/>
        <property name="url" value="jdbc:h2:mem:flowable;DB_CLOSE_DELAY=1000"/>
        <property name="username" value="sa"/>
        <property name="password" value=""/>
    </bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="processEngineConfiguration" class="org.flowable.spring.SpringProcessEngineConfiguration">
        <property name="dataSource" ref="dataSource"/>
        <property name="transactionManager" ref="transactionManager"/>
        <property name="databaseSchemaUpdate" value="true"/>
        <property name="flowable5CompatibilityEnabled" value="true" />
        <property name="flowable5CompatibilityHandlerFactory" ref="flowable5CompabilityFactory" />
        <property name="asyncExecutorActivate" value="false"/>
        <property name="deploymentMode" value="single-resource"/>
        <property name="deploymentResources"
                  value="classpath*:/org/activiti/spring/test/autodeployment/autodeploy.*.bpmn20.xml"/>
    </bean>

    <bean id="processEngine" class="org.flowable.spring.ProcessEngineFactoryBean">
        <property name="processEngineConfiguration" ref="processEngineConfiguration"/>
    </bean>

    <bean id="repositoryService" factory-bean="processEngine" factory-method="getRepositoryService"/>
    <bean id="runtimeService" factory-bean="processEngine" factory-method="getRuntimeService"/>
    <bean id="taskService" factory-bean="processEngine" factory-method="getTaskService"/>
    <bean id="historyService" factory-bean="processEngine" factory-method="getHistoryService"/>
    <bean id="managementService" factory-bean="processEngine" factory-method="getManagementService"/>

    <bean id="flowable5CompabilityFactory" class="org.activiti.compatibility.spring.SpringFlowable5CompatibilityHandlerFactory" />

</beans>


text:
require "fog/openstack"
require "log4r"
require 'promise'

module VagrantPlugins
  module OpenStack
    module Action
      # This action connects to OpenStack, verifies credentials work, and
      # puts the OpenStack connection object into the `:openstack_compute` key
      # in the environment.
      class ConnectOpenStack
        def initialize(app, env)
          @app    = app
          @logger = Log4r::Logger.new("vagrant_openstack::action::connect_openstack")
        end

        def call(env)
          config = env[:machine].provider_config

          openstack_options = {
              :provider => :openstack,
              :openstack_region => config.region,
              :openstack_username => config.username,
              :openstack_api_key => config.api_key,
              :openstack_auth_url => config.endpoint,
              :openstack_tenant => config.tenant
          }

          $openstack_compute ||= get_fog_promise('Compute', openstack_options)
          $openstack_network ||= get_fog_promise('Network', openstack_options)

          env[:openstack_compute] = $openstack_compute
          env[:openstack_network] = $openstack_network

          @app.call(env)
        end

        private

        def get_fog_promise(service_name, openstack_options)
          Kernel.promise {
            @logger.info("Initializing OpenStack #{service_name}...")
            Fog.const_get(service_name).new(openstack_options)
          }
        end
      end
    end
  end
end


text:
<?php
namespace tea\docs;

const UNIT_PATH = __DIR__ . DIRECTORY_SEPARATOR;

$super_path = dirname(__DIR__, 3) . DIRECTORY_SEPARATOR; // the workspace/vendor path
require_once $super_path . 'tea/builtin/dist/__public.php'; // the builtins

function demo_function2(string $message = 'with a default value') {
	echo 'this function can be called by local or foriegn units', LF;
}

function demo_function_with_a_return_type(string $some): int {
	return strlen($some);
}

function demo_function_with_callbacks(string $some, callable $success, callable $failure): string {
	$success_callback_result = null;
	if ($success) {
		$success_callback_result = $success('Success!');
	}

	if ($failure) {
		$failure('Some errors.');
	}

	return "the success callback result is: {$success_callback_result}";
}

// program end

// autoloads
const __AUTOLOADS = [
	'tea\docs\IDemo' => 'summary.php',
	'tea\docs\IDemoTrait' => 'summary.php',
	'tea\docs\DemoInterface' => 'summary.php',
	'tea\docs\DemoInterfaceTrait' => 'summary.php',
	'tea\docs\DemoBaseClass' => 'summary.php',
	'tea\docs\DemoPublicClass' => 'summary.php'
];

spl_autoload_register(function ($class) {
	isset(__AUTOLOADS[$class]) && require UNIT_PATH . __AUTOLOADS[$class];
});

// end


text:
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
import pymysql
from github_analysis_tool import secret_config

def main():
    mysql_config = secret_config['mysql']
    db = pymysql.connect(host=mysql_config['host'], port=mysql_config['port'], db=mysql_config['db'],
                                user=mysql_config['user'],
                                passwd=mysql_config['passwd'])

    msg = "CAUTION! This will drop all tables and probably going to cause loss of data. Are you sure want to continue?"
    approved = input("%s (y/N) " % msg).lower() == 'y'

    if not approved:
        return

    print("-->Dropping tables from \"" + mysql_config['db'] + "\"...")
    clear_db(db)
    print("-->Tables dropped")
    print("-->Creating tables on \"" + mysql_config['db'] + "\"...")
    init_db(db)
    print("-->Tables created.")

def clear_db(db):
    cursor = db.cursor()
    cursor.execute("""
            DROP TABLE IF EXISTS
            `filestats`, `monthly_repositorystats`, `repositorystats`, `contributings`, `filechanges`, `commits`, `filesofproject`,`issues`, `repositories`, `users`;
    """)

    db.commit()

def init_db(db):
    cursor = db.cursor()
    cursor.execute("""
      -- tables
        -- Table: commits
        CREATE TABLE commits (
            id bigint NOT NULL AUTO_INCREMENT,
            sha varchar(191) NULL,
            url varchar(191) NOT NULL,
            repo_id int NOT NULL,
            author_id int NULL,
            committer_id int NULL,
            message text NULL DEFAULT NULL,
            created_at timestamp NULL DEFAULT CURRENT_TIMESTAMP,
            additions int NULL,
            deletions int NULL,
            UNIQUE INDEX sha (sha),
            CONSTRAINT commits_pk PRIMARY KEY (id)
        ) ENGINE InnoDB CHARACTER SET utf8mb4;

        CREATE INDEX committer_id ON commits (committer_id);

        CREATE INDEX project_id ON commits (repo_id);

        CREATE INDEX author_id ON commits (author_id);

        -- Table: contributings
        CREATE TABLE contributings (
            user_id int NOT NULL,
            repo_id int NOT NULL,
            contributions int NULL
        ) ENGINE InnoDB CHARACTER SET utf8mb4;

        -- Table: filechanges
        CREATE TABLE filechanges (
            id bigint NOT NULL AUTO_INCREMENT,
            sha varchar(191) NOT NULL,
            repo_id int NOT NULL,
            file_path varchar(191) NULL,
            status varchar(191) NULL,
            additions int NULL,
            deletions int NULL,
            changes int NULL,
            commit_id bigint NOT NULL,
            commit_sha varchar(191) NULL,
            file_id bigint NOT NULL,
            CONSTRAINT filechanges_pk PRIMARY KEY (id)
        ) ENGINE InnoDB CHARACTER SET utf8mb4;

        -- Table: filesofproject
        CREATE TABLE filesofproject (
            id bigint NOT NULL AUTO_INCREMENT,
            repo_id int NOT NULL,
            file_path varchar(191) NOT NULL,
            CONSTRAINT filesofproject_pk PRIMARY KEY (id)
        ) ENGINE InnoDB CHARACTER SET utf8mb4;

        CREATE  UNIQUE INDEX filesofproject_idx_1 ON filesofproject (repo_id,file_path);

        -- Table: filestats
        CREATE TABLE filestats (
            id int NOT NULL AUTO_INCREMENT,
            repo_id int NOT NULL,
            project_full_name varchar(191) NOT NULL,
            file_path varchar(191) NOT NULL,
            no_of_commits int NULL,
            first_commit_date timestamp NULL,
            last_commit_date timestamp NULL,
            commit_frequency float NULL,
            no_of_developers int NULL,
            top_developer_id int NULL,
            file_id bigint NOT NULL,
            CONSTRAINT filestats_pk PRIMARY KEY (id)
        ) ENGINE InnoDB CHARACTER SET utf8mb4;

        CREATE  UNIQUE INDEX filestats_idx_1 ON filestats (repo_id,file_path);

        -- Table: issues
        CREATE TABLE issues (
            id int NOT NULL,
            url varchar(191) NOT NULL,
            number int NULL,
            title text NULL,
            repo_id int NOT NULL,
            reporter_id int NOT NULL,
            assignee_id int NULL,
            state varchar(191) NULL,
            comments int NULL,
            created_at timestamp NULL,
            updated_at timestamp NULL,
            closed_at timestamp NULL,
            closedbyid int NULL,
            CONSTRAINT issues_pk PRIMARY KEY (id)
        ) ENGINE InnoDB CHARACTER SET utf8mb4;

        -- Table: monthly_repositorystats
        CREATE TABLE monthly_repositorystats (
            id int NOT NULL AUTO_INCREMENT,
            repo_id int NOT NULL,
            start_date timestamp NULL,
            end_date timestamp NULL,
            no_of_commits int NULL,
            no_of_contributors int NULL,
            no_of_changed_files int NULL,
            no_of_file_changes int NULL,
            CONSTRAINT monthly_repositorystats_pk PRIMARY KEY (id)
        ) ENGINE InnoDB CHARACTER SET utf8mb4;

        -- Table: repositories
        CREATE TABLE repositories (
            id int NOT NULL,
            url varchar(191) NULL DEFAULT NULL,
            name varchar(191) NOT NULL,
            full_name varchar(191) NOT NULL,
            description text NULL DEFAULT NULL,
            owner_id int NOT NULL,
            language varchar(191) NULL DEFAULT NULL,
            created_at timestamp NULL DEFAULT CURRENT_TIMESTAMP,
            updated_at timestamp NULL DEFAULT NULL,
            stargazers_count int NULL DEFAULT NULL,
            watchers_count int NULL DEFAULT NULL,
            forks_count int NULL DEFAULT NULL,
            filled_at timestamp NULL DEFAULT NULL,
            UNIQUE INDEX name (name,owner_id),
            CONSTRAINT projects_pk PRIMARY KEY (id)
        ) ENGINE InnoDB CHARACTER SET utf8mb4;

        CREATE INDEX owner_id ON repositories (owner_id);

        -- Table: repositorystats
        CREATE TABLE repositorystats (
            id int NOT NULL AUTO_INCREMENT,
            repo_id int NOT NULL,
            no_of_commits int NULL,
            no_of_contributors int NULL,
            no_of_changed_files int NULL,
            no_of_file_changes int NULL,
            CONSTRAINT repositorystats_pk PRIMARY KEY (id)
        ) ENGINE InnoDB CHARACTER SET utf8mb4;

        CREATE  UNIQUE INDEX repositorystats_idx_1 ON repositorystats (repo_id);

        -- Table: users
        CREATE TABLE users (
            user_id int NOT NULL AUTO_INCREMENT,
            github_user_id int NULL,
            url varchar(191) NULL,
            login varchar(191) NULL,
            name varchar(191) NULL DEFAULT NULL,
            company varchar(191) NULL DEFAULT NULL,
            email varchar(191) NULL DEFAULT NULL,
            bio text NULL DEFAULT NULL,
            is_github_user bool NOT NULL,
            CONSTRAINT users_pk PRIMARY KEY (user_id)
        ) CHARACTER SET utf8mb4;

        -- foreign keys
        -- Reference: contributings_repositories (table: contributings)
        ALTER TABLE contributings ADD CONSTRAINT contributings_repositories FOREIGN KEY contributings_repositories (repo_id)
            REFERENCES repositories (id);

        -- Reference: contributings_users (table: contributings)
        ALTER TABLE contributings ADD CONSTRAINT contributings_users FOREIGN KEY contributings_users (user_id)
            REFERENCES users (user_id);

        -- Reference: filechanges_filesofproject (table: filechanges)
        ALTER TABLE filechanges ADD CONSTRAINT filechanges_filesofproject FOREIGN KEY filechanges_filesofproject (file_id)
            REFERENCES filesofproject (id);

        -- Reference: fk_commits_authors (table: commits)
        ALTER TABLE commits ADD CONSTRAINT fk_commits_authors FOREIGN KEY fk_commits_authors (committer_id)
            REFERENCES users (user_id);

        -- Reference: fk_commits_committers (table: commits)
        ALTER TABLE commits ADD CONSTRAINT fk_commits_committers FOREIGN KEY fk_commits_committers (author_id)
            REFERENCES users (user_id);

        -- Reference: fk_commits_repositories (table: commits)
        ALTER TABLE commits ADD CONSTRAINT fk_commits_repositories FOREIGN KEY fk_commits_repositories (repo_id)
            REFERENCES repositories (id);

        -- Reference: fk_filechanges_commits (table: filechanges)
        ALTER TABLE filechanges ADD CONSTRAINT fk_filechanges_commits FOREIGN KEY fk_filechanges_commits (commit_id)
            REFERENCES commits (id);

        -- Reference: fk_filechanges_repositories (table: filechanges)
        ALTER TABLE filechanges ADD CONSTRAINT fk_filechanges_repositories FOREIGN KEY fk_filechanges_repositories (repo_id)
            REFERENCES repositories (id);

        -- Reference: fk_filesofproject_repositories (table: filesofproject)
        ALTER TABLE filesofproject ADD CONSTRAINT fk_filesofproject_repositories FOREIGN KEY fk_filesofproject_repositories (repo_id)
            REFERENCES repositories (id)
            ON DELETE CASCADE
            ON UPDATE CASCADE;

        -- Reference: fk_filestats_filesofproject (table: filestats)
        ALTER TABLE filestats ADD CONSTRAINT fk_filestats_filesofproject FOREIGN KEY fk_filestats_filesofproject (file_id)
            REFERENCES filesofproject (id)
            ON DELETE CASCADE
            ON UPDATE CASCADE;

        -- Reference: fk_filestats_repositories (table: filestats)
        ALTER TABLE filestats ADD CONSTRAINT fk_filestats_repositories FOREIGN KEY fk_filestats_repositories (repo_id)
            REFERENCES repositories (id);

        -- Reference: fk_filestats_users (table: filestats)
        ALTER TABLE filestats ADD CONSTRAINT fk_filestats_users FOREIGN KEY fk_filestats_users (top_developer_id)
            REFERENCES users (user_id);

        -- Reference: fk_monthly_repositorystats_repositories (table: monthly_repositorystats)
        ALTER TABLE monthly_repositorystats ADD CONSTRAINT fk_monthly_repositorystats_repositories FOREIGN KEY fk_monthly_repositorystats_repositories (repo_id)
            REFERENCES repositories (id)
            ON DELETE CASCADE
            ON UPDATE CASCADE;

        -- Reference: fk_repositories_users (table: repositories)
        ALTER TABLE repositories ADD CONSTRAINT fk_repositories_users FOREIGN KEY fk_repositories_users (owner_id)
            REFERENCES users (user_id)
            ON DELETE CASCADE
            ON UPDATE CASCADE;

        -- Reference: fk_repositorystats_repositories (table: repositorystats)
        ALTER TABLE repositorystats ADD CONSTRAINT fk_repositorystats_repositories FOREIGN KEY fk_repositorystats_repositories (repo_id)
            REFERENCES repositories (id)
            ON DELETE CASCADE
            ON UPDATE CASCADE;

        -- Reference: issues_repositories (table: issues)
        ALTER TABLE issues ADD CONSTRAINT issues_repositories FOREIGN KEY issues_repositories (repo_id)
            REFERENCES repositories (id);

        -- Reference: issues_users (table: issues)
        ALTER TABLE issues ADD CONSTRAINT issues_users FOREIGN KEY issues_users (assignee_id)
            REFERENCES users (user_id);

    """)

    db.commit()

main()


text:
title: Logging Docker Container Output to journald
author: dwalsh
date: 2015-04-28 17:26:27 UTC
tags: Docker, logging, journald
comments: true
published: true
---

[Docker](https://www.docker.com/) has added a new feature to allow alternate logging drivers, and soon you'll be able to use `journald` as a supported driver.

With Docker 1.6 they support json-file, which is the old default, syslog, or no logging at all.

READMORE

If you ran your docker daemon with the `--log-driver=syslog` option, any output from a container would go directly to system syslog daemon, and usually end up in /var/log/messages.

I added a patch to support journald as a logging driver, and it was [recently merged](https://github.com/docker/docker/pull/12557).

In docker-1.7 you will have the option to use `--log-driver=journald` on either your docker daemon to cause all of your container logging to go directly to the journal, or you could use the --log-driver=journald on a docker run/create line, so you could get individual containers running with different logging drivers.

To test this I set up my docker daemon to run with the following options.

```docker -d --selinux-enabled --log-driver=journald```

Now I run a simple container.

```docker run fedora echo "Dan Walsh was here"```

Then I look up the container ID for the newly created container, and I can use journalctl to examine the content.

```
journalctl MESSAGE_ID=cdf02c627e27
-- Logs begin at Mon 2015-04-06 16:06:42 EDT, end at Fri 2015-04-24 08:40:38 EDT. --
Apr 20 15:06:39 dhcp-10-19-62-196.boston.devel.redhat.com docker[27792]: Dan Walsh was here
```

Currently the `docker logs` command only works with the json-file backend. But I hope to eventually get the docker daemon to communicate with the journald to get this information. Of course if anyone wants to take a stab at this, we would welcome your effort.

As mentioned, the journald backend for `--log-driver` is not shipping in Docker today, but should be available in the 1.7 release. Keep reading here or follow [@projectatomic](https://twitter.com/projectatomic) for updates on new and interesting features in Docker.


text:
Money::Money(int dollars, int cents) : dollars{dollars}, cents{cents} {}

Money::Money(int total) : dollars {total/100}, cents{total%100}  {}

//----DO NOT MODIFY THE CODE ABOVE THIS LINE----
//----WRITE YOUR METHOD DEFINITIONS BELOW THIS LINE----
Money operator+(const Money &lhs, const Money &rhs) {
    int tmpDollars = (lhs.dollars + rhs.dollars) + (lhs.cents + rhs.cents)/100;
    int tmpCents = (lhs.cents + rhs.cents)%100;
    Money temp(tmpDollars, tmpCents);
    return temp;
}

//----WRITE YOUR METHOD DEFINITIONS ABOVE THIS LINE----


text:
namespace supersonic {using std::string; }

#include "supersonic/utils/integral_types.h"
#include <glog/logging.h>
#include "supersonic/utils/logging-inl.h"
#include "supersonic/utils/macros.h"
#include "supersonic/utils/exception/failureor.h"
#include "supersonic/base/infrastructure/block.h"
#include "supersonic/base/infrastructure/tuple_schema.h"
#include "supersonic/cursor/base/cursor.h"
#include "supersonic/cursor/infrastructure/basic_operation.h"
#include "supersonic/cursor/infrastructure/view_cursor.h"
#include "supersonic/utils/strings/join.h"

namespace supersonic {

class BufferAllocator;
class Operation;

namespace {
// An operation class that can be bound to a cursor over the given view, with
// the given selection vector.
// If the selection_vector is NULL, the row_count and buffer_row_capacity
// arguments are ignored, and the operation simply scans the view.
class ScanViewOperation : public BasicOperation {
 public:
  ScanViewOperation(const View& view,
                    const size_t row_count,
                    const int64* selection_vector,
                    size_t buffer_row_capacity)
      : BasicOperation(),
        view_(view),
        row_count_(row_count),
        selection_vector_(selection_vector),
        buffer_row_capacity_(buffer_row_capacity) {}

  virtual ~ScanViewOperation() {}

  virtual FailureOrOwned<Cursor> CreateCursor() const {
    if (selection_vector_ != NULL) {
      return BoundScanViewWithSelection(view_,
                                        row_count_,
                                        selection_vector_,
                                        buffer_allocator(),
                                        buffer_row_capacity_);
    } else {
      return Success(BoundScanView(view_));
    }
  }

  virtual string DebugDescription() const {
    string name = (selection_vector_ != NULL) ? "ScanViewWithSelection"
                                              : "ScanView";
    return StrCat(name, "(", view_.schema().GetHumanReadableSpecification(),
                  ")");
  }

 private:
  // The view over which the operation is.
  const View& view_;
  // The row_count of the output (equal to the number of entries in the
  // selection vector).
  size_t row_count_;
  // The selection vector. The i-th row of the output is equal to the
  // selection_vector_[i]-th row of the input view.
  const int64* selection_vector_;
  // The buffer capacity we expect from the created cursor (this is the
  // maximum size of a returned block).
  size_t buffer_row_capacity_;

  DISALLOW_COPY_AND_ASSIGN(ScanViewOperation);
};

}  // namespace

// The actual implementation of cursors over views is in
// cursor/infrastructure/view_cursor.{cc,h}.
Cursor* BoundScanView(const View& view) {
  return CreateCursorOverView(view);
}

FailureOrOwned<Cursor> BoundScanViewWithSelection(
    const View& view,
    const rowcount_t row_count,
    const rowid_t* selection_vector,
    BufferAllocator* allocator,
    rowcount_t buffer_row_capacity) {
  return CreateCursorOverViewWithSelection(
      view, row_count, selection_vector, allocator, buffer_row_capacity);
}

Operation* ScanView(const View& view) {
  return new ScanViewOperation(view, 0, NULL, 0);
}

Operation* ScanViewWithSelection(
    const View& view,
    const rowcount_t row_count,
    const rowid_t* selection_vector,
    rowcount_t buffer_row_capacity) {
  CHECK_NOTNULL(selection_vector);
  return new ScanViewOperation(
      view, row_count, selection_vector, buffer_row_capacity);
}

}  // namespace supersonic


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var pointSchema = new Schema({
    name: String,
    inside: { type: Boolean, default: false },
    date: { type: Date, default: Date.now },
    coordinates: { type: [Number], index: '2dsphere' }
});

module.exports = mongoose.model('Point', pointSchema);