text:
import { identity, isSubtypeOf, isValueDefined, logError, nameof } from './helpers';
import { JsonObjectMetadata } from './metadata';
import { getOptionValue, mergeOptions } from './options-base';
import { AnyT, ArrayTypeDescriptor, ConcreteTypeDescriptor, MapTypeDescriptor, SetTypeDescriptor, } from './type-descriptor';
export function defaultTypeResolver(sourceObject, knownTypes) {
    if (sourceObject.__type != null) {
        return knownTypes.get(sourceObject.__type);
    }
}
var Deserializer = (function () {
    function Deserializer() {
        this.typeResolver = defaultTypeResolver;
        this.errorHandler = logError;
        this.deserializationStrategy = new Map([
            [AnyT.ctor, identity],
            [Number, deserializeDirectly],
            [String, deserializeDirectly],
            [Boolean, deserializeDirectly],
            [Date, deserializeDate],
            [ArrayBuffer, stringToArrayBuffer],
            [DataView, stringToDataView],
            [Array, convertAsArray],
            [Set, convertAsSet],
            [Map, convertAsMap],
            [Float32Array, convertAsFloatArray],
            [Float64Array, convertAsFloatArray],
            [Uint8Array, convertAsUintArray],
            [Uint8ClampedArray, convertAsUintArray],
            [Uint16Array, convertAsUintArray],
            [Uint32Array, convertAsUintArray],
        ]);
    }
    Deserializer.prototype.setDeserializationStrategy = function (type, deserializer) {
        this.deserializationStrategy.set(type, deserializer);
    };
    Deserializer.prototype.setNameResolver = function (nameResolverCallback) {
        this.nameResolver = nameResolverCallback;
    };
    Deserializer.prototype.setTypeResolver = function (typeResolverCallback) {
        if (typeof typeResolverCallback !== 'function') {
            throw new TypeError('\'typeResolverCallback\' is not a function.');
        }
        this.typeResolver = typeResolverCallback;
    };
    Deserializer.prototype.getTypeResolver = function () {
        return this.typeResolver;
    };
    Deserializer.prototype.setErrorHandler = function (errorHandlerCallback) {
        if (typeof errorHandlerCallback !== 'function') {
            throw new TypeError('\'errorHandlerCallback\' is not a function.');
        }
        this.errorHandler = errorHandlerCallback;
    };
    Deserializer.prototype.getErrorHandler = function () {
        return this.errorHandler;
    };
    Deserializer.prototype.convertSingleValue = function (sourceObject, typeDescriptor, knownTypes, memberName, memberOptions) {
        if (memberName === void 0) { memberName = 'object'; }
        if (this.retrievePreserveNull(memberOptions) && sourceObject === null) {
            return null;
        }
        else if (!isValueDefined(sourceObject)) {
            return;
        }
        var deserializer = this.deserializationStrategy.get(typeDescriptor.ctor);
        if (deserializer !== undefined) {
            return deserializer(sourceObject, typeDescriptor, knownTypes, memberName, this, memberOptions);
        }
        if (typeof sourceObject === 'object') {
            return convertAsObject(sourceObject, typeDescriptor, knownTypes, memberName, this);
        }
        var error = "Could not deserialize '" + memberName + "'; don't know how to deserialize type";
        if (typeDescriptor.hasFriendlyName()) {
            error += " '" + typeDescriptor.ctor.name + "'";
        }
        this.errorHandler(new TypeError(error + "."));
    };
    Deserializer.prototype.instantiateType = function (ctor) {
        return new ctor();
    };
    Deserializer.prototype.mergeKnownTypes = function () {
        var _this = this;
        var knownTypeMaps = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            knownTypeMaps[_i] = arguments[_i];
        }
        var result = new Map();
        knownTypeMaps.forEach(function (knownTypes) {
            knownTypes.forEach(function (ctor, name) {
                if (_this.nameResolver === undefined) {
                    result.set(name, ctor);
                }
                else {
                    result.set(_this.nameResolver(ctor), ctor);
                }
            });
        });
        return result;
    };
    Deserializer.prototype.createKnownTypesMap = function (knowTypes) {
        var _this = this;
        var map = new Map();
        knowTypes.forEach(function (ctor) {
            if (_this.nameResolver === undefined) {
                var knownTypeMeta = JsonObjectMetadata.getFromConstructor(ctor);
                var customName = (knownTypeMeta === null || knownTypeMeta === void 0 ? void 0 : knownTypeMeta.isExplicitlyMarked) === true
                    ? knownTypeMeta.name
                    : null;
                map.set(customName !== null && customName !== void 0 ? customName : ctor.name, ctor);
            }
            else {
                map.set(_this.nameResolver(ctor), ctor);
            }
        });
        return map;
    };
    Deserializer.prototype.retrievePreserveNull = function (memberOptions) {
        return getOptionValue('preserveNull', mergeOptions(this.options, memberOptions));
    };
    return Deserializer;
}());
export { Deserializer };
function throwTypeMismatchError(targetType, expectedSourceType, actualSourceType, memberName) {
    throw new TypeError("Could not deserialize " + memberName + " as " + targetType + ":"
        + (" expected " + expectedSourceType + ", got " + actualSourceType + "."));
}
function makeTypeErrorMessage(expectedType, actualType, memberName) {
    var expectedTypeName = typeof expectedType === 'function'
        ? nameof(expectedType)
        : expectedType;
    var actualTypeName = typeof actualType === 'function' ? nameof(actualType) : actualType;
    return "Could not deserialize " + memberName + ": expected '" + expectedTypeName + "',"
        + (" got '" + actualTypeName + "'.");
}
function srcTypeNameForDebug(sourceObject) {
    return sourceObject == null ? 'undefined' : nameof(sourceObject.constructor);
}
function deserializeDirectly(sourceObject, typeDescriptor, knownTypes, objectName) {
    if (sourceObject.constructor !== typeDescriptor.ctor) {
        throw new TypeError(makeTypeErrorMessage(nameof(typeDescriptor.ctor), sourceObject.constructor, objectName));
    }
    return sourceObject;
}
function convertAsObject(sourceObject, typeDescriptor, knownTypes, memberName, deserializer) {
    if (typeof sourceObject !== 'object' || sourceObject === null) {
        deserializer.getErrorHandler()(new TypeError("Cannot deserialize " + memberName + ": 'sourceObject' must be a defined object."));
        return undefined;
    }
    var expectedSelfType = typeDescriptor.ctor;
    var sourceObjectMetadata = JsonObjectMetadata.getFromConstructor(expectedSelfType);
    var knownTypeConstructors = knownTypes;
    var typeResolver = deserializer.getTypeResolver();
    if (sourceObjectMetadata !== undefined) {
        sourceObjectMetadata.processDeferredKnownTypes();
        knownTypeConstructors = deserializer.mergeKnownTypes(knownTypeConstructors, deserializer.createKnownTypesMap(sourceObjectMetadata.knownTypes));
        if (sourceObjectMetadata.typeResolver != null) {
            typeResolver = sourceObjectMetadata.typeResolver;
        }
    }
    var typeFromTypeHint = typeResolver(sourceObject, knownTypeConstructors);
    if (typeFromTypeHint != null) {
        if (isSubtypeOf(typeFromTypeHint, expectedSelfType)) {
            expectedSelfType = typeFromTypeHint;
            sourceObjectMetadata = JsonObjectMetadata.getFromConstructor(typeFromTypeHint);
            if (sourceObjectMetadata !== undefined) {
                knownTypeConstructors = deserializer.mergeKnownTypes(knownTypeConstructors, deserializer.createKnownTypesMap(sourceObjectMetadata.knownTypes));
            }
        }
    }
    if ((sourceObjectMetadata === null || sourceObjectMetadata === void 0 ? void 0 : sourceObjectMetadata.isExplicitlyMarked) === true) {
        var sourceMetadata_1 = sourceObjectMetadata;
        var sourceObjectWithDeserializedProperties_1 = {};
        var classOptions_1 = mergeOptions(deserializer.options, sourceMetadata_1.options);
        sourceMetadata_1.dataMembers.forEach(function (objMemberMetadata, propKey) {
            var objMemberValue = sourceObject[propKey];
            var objMemberDebugName = nameof(sourceMetadata_1.classType) + "." + propKey;
            var objMemberOptions = mergeOptions(classOptions_1, objMemberMetadata.options);
            var revivedValue;
            if (objMemberMetadata.deserializer != null) {
                revivedValue = objMemberMetadata.deserializer(objMemberValue);
            }
            else if (objMemberMetadata.type == null) {
                throw new TypeError("Cannot deserialize " + objMemberDebugName + " there is"
                    + " no constructor nor deserialization function to use.");
            }
            else {
                revivedValue = deserializer.convertSingleValue(objMemberValue, objMemberMetadata.type(), knownTypeConstructors, objMemberDebugName, objMemberOptions);
            }
            if (isValueDefined(revivedValue)
                || (deserializer.retrievePreserveNull(objMemberOptions)
                    && revivedValue === null)) {
                sourceObjectWithDeserializedProperties_1[objMemberMetadata.key] = revivedValue;
            }
            else if (objMemberMetadata.isRequired === true) {
                deserializer.getErrorHandler()(new TypeError("Missing required member '" + objMemberDebugName + "'."));
            }
        });
        var targetObject = void 0;
        if (typeof sourceObjectMetadata.initializerCallback === 'function') {
            try {
                targetObject = sourceObjectMetadata.initializerCallback(sourceObjectWithDeserializedProperties_1, sourceObject);
                if (targetObject == null) {
                    throw new TypeError("Cannot deserialize " + memberName + ":"
                        + " 'initializer' function returned undefined/null"
                        + (", but '" + nameof(sourceObjectMetadata.classType) + "' was expected."));
                }
                else if (!(targetObject instanceof sourceObjectMetadata.classType)) {
                    throw new TypeError("Cannot deserialize " + memberName + ":"
                        + ("'initializer' returned '" + nameof(targetObject.constructor) + "'")
                        + (", but '" + nameof(sourceObjectMetadata.classType) + "' was expected")
                        + (", and '" + nameof(targetObject.constructor) + "' is not a subtype of")
                        + (" '" + nameof(sourceObjectMetadata.classType) + "'"));
                }
            }
            catch (e) {
                deserializer.getErrorHandler()(e);
                return undefined;
            }
        }
        else {
            targetObject = deserializer.instantiateType(expectedSelfType);
        }
        Object.assign(targetObject, sourceObjectWithDeserializedProperties_1);
        var methodName = sourceObjectMetadata.onDeserializedMethodName;
        if (methodName != null) {
            if (typeof targetObject[methodName] === 'function') {
                targetObject[methodName]();
            }
            else if (typeof targetObject.constructor[methodName] === 'function') {
                targetObject.constructor[methodName]();
            }
            else {
                deserializer.getErrorHandler()(new TypeError("onDeserialized callback"
                    + ("'" + nameof(sourceObjectMetadata.classType) + "." + methodName + "' is not a method.")));
            }
        }
        return targetObject;
    }
    else {
        var targetObject_1 = {};
        Object.keys(sourceObject).forEach(function (sourceKey) {
            targetObject_1[sourceKey] = deserializer.convertSingleValue(sourceObject[sourceKey], new ConcreteTypeDescriptor(sourceObject[sourceKey].constructor), knownTypes, sourceKey);
        });
        return targetObject_1;
    }
}
function convertAsArray(sourceObject, typeDescriptor, knownTypes, memberName, deserializer, memberOptions) {
    if (!(typeDescriptor instanceof ArrayTypeDescriptor)) {
        throw new TypeError("Could not deserialize " + memberName + " as Array: incorrect TypeDescriptor detected,"
            + ' please use proper annotation or function for this type');
    }
    if (!Array.isArray(sourceObject)) {
        deserializer.getErrorHandler()(new TypeError(makeTypeErrorMessage(Array, sourceObject.constructor, memberName)));
        return [];
    }
    if (typeDescriptor.elementType == null) {
        deserializer.getErrorHandler()(new TypeError("Could not deserialize " + memberName + " as Array: missing constructor reference of"
            + " Array elements."));
        return [];
    }
    return sourceObject.map(function (element, i) {
        try {
            return deserializer.convertSingleValue(element, typeDescriptor.elementType, knownTypes, memberName + "[" + i + "]", memberOptions);
        }
        catch (e) {
            deserializer.getErrorHandler()(e);
            return undefined;
        }
    });
}
function convertAsSet(sourceObject, typeDescriptor, knownTypes, memberName, deserializer, memberOptions) {
    if (!(typeDescriptor instanceof SetTypeDescriptor)) {
        throw new TypeError("Could not deserialize " + memberName + " as Set: incorrect TypeDescriptor detected,"
            + " please use proper annotation or function for this type");
    }
    if (!Array.isArray(sourceObject)) {
        deserializer.getErrorHandler()(new TypeError(makeTypeErrorMessage(Array, sourceObject.constructor, memberName)));
        return new Set();
    }
    if (typeDescriptor.elementType == null) {
        deserializer.getErrorHandler()(new TypeError("Could not deserialize " + memberName + " as Set: missing constructor reference of"
            + " Set elements."));
        return new Set();
    }
    var resultSet = new Set();
    sourceObject.forEach(function (element, i) {
        try {
            resultSet.add(deserializer.convertSingleValue(element, typeDescriptor.elementType, knownTypes, memberName + "[" + i + "]", memberOptions));
        }
        catch (e) {
            deserializer.getErrorHandler()(e);
        }
    });
    return resultSet;
}
function isExpectedMapShape(source, expectedShape) {
    return (expectedShape === 0 && Array.isArray(source))
        || (expectedShape === 1 && typeof source === 'object');
}
function convertAsMap(sourceObject, typeDescriptor, knownTypes, memberName, deserializer, memberOptions) {
    if (!(typeDescriptor instanceof MapTypeDescriptor)) {
        throw new TypeError("Could not deserialize " + memberName + " as Map: incorrect TypeDescriptor detected,"
            + 'please use proper annotation or function for this type');
    }
    var expectedShape = typeDescriptor.getCompleteOptions().shape;
    if (!isExpectedMapShape(sourceObject, expectedShape)) {
        var expectedType = expectedShape === 0 ? Array : Object;
        deserializer.getErrorHandler()(new TypeError(makeTypeErrorMessage(expectedType, sourceObject.constructor, memberName)));
        return new Map();
    }
    if (typeDescriptor.keyType == null) {
        deserializer.getErrorHandler()(new TypeError("Could not deserialize " + memberName + " as Map: missing key constructor."));
        return new Map();
    }
    if (typeDescriptor.valueType == null) {
        deserializer.getErrorHandler()(new TypeError("Could not deserialize " + memberName + " as Map: missing value constructor."));
        return new Map();
    }
    var keyMemberName = memberName + "[].key";
    var valueMemberName = memberName + "[].value";
    var resultMap = new Map();
    if (expectedShape === 1) {
        Object.keys(sourceObject).forEach(function (key) {
            try {
                var resultKey = deserializer.convertSingleValue(key, typeDescriptor.keyType, knownTypes, keyMemberName, memberOptions);
                if (isValueDefined(resultKey)) {
                    resultMap.set(resultKey, deserializer.convertSingleValue(sourceObject[key], typeDescriptor.valueType, knownTypes, valueMemberName, memberOptions));
                }
            }
            catch (e) {
                deserializer.getErrorHandler()(e);
            }
        });
    }
    else {
        sourceObject.forEach(function (element) {
            try {
                var key = deserializer.convertSingleValue(element.key, typeDescriptor.keyType, knownTypes, keyMemberName, memberOptions);
                if (isValueDefined(key)) {
                    resultMap.set(key, deserializer.convertSingleValue(element.value, typeDescriptor.valueType, knownTypes, valueMemberName, memberOptions));
                }
            }
            catch (e) {
                deserializer.getErrorHandler()(e);
            }
        });
    }
    return resultMap;
}
function deserializeDate(sourceObject, typeDescriptor, knownTypes, memberName) {
    if (typeof sourceObject === 'number') {
        var isInteger = sourceObject % 1 === 0;
        if (!isInteger) {
            throw new TypeError("Could not deserialize " + memberName + " as Date:"
                + " expected an integer, got a number with decimal places.");
        }
        return new Date(sourceObject);
    }
    else if (typeof sourceObject === 'string') {
        return new Date(sourceObject);
    }
    else if (sourceObject instanceof Date) {
        return sourceObject;
    }
    else {
        throwTypeMismatchError('Date', 'an ISO-8601 string', srcTypeNameForDebug(sourceObject), memberName);
    }
}
function stringToArrayBuffer(sourceObject, typeDescriptor, knownTypes, memberName) {
    if (typeof sourceObject !== 'string') {
        throwTypeMismatchError('ArrayBuffer', 'a string source', srcTypeNameForDebug(sourceObject), memberName);
    }
    return createArrayBufferFromString(sourceObject);
}
function stringToDataView(sourceObject, typeDescriptor, knownTypes, memberName) {
    if (typeof sourceObject !== 'string') {
        throwTypeMismatchError('DataView', 'a string source', srcTypeNameForDebug(sourceObject), memberName);
    }
    return new DataView(createArrayBufferFromString(sourceObject));
}
function createArrayBufferFromString(input) {
    var buf = new ArrayBuffer(input.length * 2);
    var bufView = new Uint16Array(buf);
    for (var i = 0, strLen = input.length; i < strLen; i++) {
        bufView[i] = input.charCodeAt(i);
    }
    return buf;
}
function convertAsFloatArray(sourceObject, typeDescriptor, knownTypes, memberName) {
    var constructor = typeDescriptor.ctor;
    if (Array.isArray(sourceObject) && sourceObject.every(function (elem) { return !isNaN(elem); })) {
        return new constructor(sourceObject);
    }
    return throwTypeMismatchError(constructor.name, 'a numeric source array', srcTypeNameForDebug(sourceObject), memberName);
}
function convertAsUintArray(sourceObject, typeDescriptor, knownTypes, memberName) {
    var constructor = typeDescriptor.ctor;
    if (Array.isArray(sourceObject) && sourceObject.every(function (elem) { return !isNaN(elem); })) {
        return new constructor(sourceObject.map(function (value) { return ~~value; }));
    }
    return throwTypeMismatchError(typeDescriptor.ctor.name, 'a numeric source array', srcTypeNameForDebug(sourceObject), memberName);
}
//# sourceMappingURL=deserializer.js.map


text:
using LyvinDataStoreLib.Models;

namespace LyvinDataStoreLib.LyvinLayoutData
{
    /// <summary>
    /// Represents the room data of a device
    /// </summary>
    [TableName("deviceinroom")]
    [PrimaryKey("DeviceInRoomID")]
    public class DeviceInRoom
    {
        /// <summary>
        ///
        /// </summary>
        public ulong DeviceInRoomID { get; set; }

        /// <summary>
        ///
        /// </summary>
        public ulong RoomID { get; set; }

        /// <summary>
        ///
        /// </summary>
        public float Probability { get; set; }

        /// <summary>
        ///
        /// </summary>
        public ulong DeviceID { get; set; }

        /// <summary>
        ///
        /// </summary>
        public DeviceInRoom()
        {

        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="roomid"></param>
        /// <param name="probability"></param>
        /// <param name="deviceid"></param>
        public DeviceInRoom(ulong roomid, float probability, ulong deviceid)
        {
            RoomID = roomid;
            Probability = probability;
            DeviceID = deviceid;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Login | Receipt Roundup</title>
<link rel="shortcut icon" href="img/favicon.png" type="image/x-icon" />

<link
  rel="stylesheet"
  href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
  integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
  crossorigin="anonymous"
/>
<link href="https://fonts.googleapis.com/css2?family=Ewert&display=swap" rel="stylesheet" />

<link rel="stylesheet" href="css/common.css" />
<link rel="stylesheet" href="css/login.css" />

Receipt Roundup

      Receipt storage has never been simpler.

      Sign In with Google


text:
from ovirtcli.command.command import OvirtCommand
from cli.messages import Messages

class StatusCommand(OvirtCommand):

    name = 'status'
    description = 'shows last command status'
    helptext = """\
        == Usage ==

        status

        == Description ==

        Shows the exist status of the last command.
        """

    def execute(self):
        context = self.context
        status = context.status
        if status is not None:
            sstatus = str(status)
            for sym in dir(context):
                if sym[0].isupper() and getattr(context, sym) == status:
                    sstatus += ' (%s)' % sym
        else:
            sstatus = 'N/A'
        self.write(Messages.Info.STATUS % sstatus + '\n')


text:
/**
 *
 * App.react.js
 *
 * This component is the skeleton around the actual pages, and should only
 * contain code that should be seen on all pages. (e.g. navigation bar)
 *
 * NOTE: while this component should technically be a stateless functional
 * component (SFC), hot reloading does not currently support SFCs. If hot
 * reloading is not a neccessity for you then you can refactor it and remove
 * the linting exception.
 */

import React from 'react';

import 'sanitize.css/sanitize.css';

import 'velocity-animate';
import 'velocity-animate/velocity.ui';

import styles from './styles.css';

export default class App extends React.Component { // eslint-disable-line react/prefer-stateless-function

  static propTypes = {
    children: React.PropTypes.node,
  };

  render() {
    return (
      <div className={styles.container}>
        {this.props.children}
      </div>
    );
  }
}


text:
var baseFlatten = require('./_baseFlatten'),
    baseUniq = require('./_baseUniq'),
    rest = require('./rest');

/**
 * Creates an array of unique values, in order, from all given arrays using
 * [`SameValueZero`](http://ecma-international.org/ecma-262/6.0/#sec-samevaluezero)
 * for equality comparisons.
 *
 * @static
 * @memberOf _
 * @category Array
 * @param {...Array} [arrays] The arrays to inspect.
 * @returns {Array} Returns the new array of combined values.
 * @example
 *
 * _.union([2, 1], [4, 2], [1, 2]);
 * // => [2, 1, 4]
 */
var union = rest(function(arrays) {
  return baseUniq(baseFlatten(arrays, 1, true));
});

module.exports = union;


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="library_name">DDay.Collections.Android</string>
</resources>


text:
#ifndef CONNECTION_UART
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#else
#include <termios.h>
#endif

#include <arpa/inet.h>
#include <unistd.h>
#include <getopt.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>
#include <strings.h>

#include "runtime_lib.h"
#include "runtime_timer.h"
#include "native_interface.h"
#include "app_manager_export.h"
#include "bh_platform.h"
#include "runtime_sensor.h"
#include "bi-inc/attr_container.h"
#include "module_wasm_app.h"
#include "wasm_export.h"

#define MAX 2048

#ifndef CONNECTION_UART
#define SA struct sockaddr
static char *host_address = "127.0.0.1";
static int port = 8888;
#else
static char *uart_device = "/dev/ttyS2";
static int baudrate = B115200;
#endif

extern bool
init_sensor_framework();
extern void
exit_sensor_framework();
extern void
exit_connection_framework();
extern int
aee_host_msg_callback(void *msg, uint32_t msg_len);
extern bool
init_connection_framework();

#ifndef CONNECTION_UART
int listenfd = -1;
int sockfd = -1;
static pthread_mutex_t sock_lock = PTHREAD_MUTEX_INITIALIZER;
#else
int uartfd = -1;
#endif

#ifndef CONNECTION_UART
static bool server_mode = false;

// Function designed for chat between client and server.
void *
func(void *arg)
{
    char buff[MAX];
    int n;
    struct sockaddr_in servaddr;

    while (1) {
        if (sockfd != -1)
            close(sockfd);
        // socket create and verification
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd == -1) {
            printf("socket creation failed...\n");
            return NULL;
        }
        else
            printf("Socket successfully created..\n");
        bzero(&servaddr, sizeof(servaddr));
        // assign IP, PORT
        servaddr.sin_family = AF_INET;
        servaddr.sin_addr.s_addr = inet_addr(host_address);
        servaddr.sin_port = htons(port);

        // connect the client socket to server socket
        if (connect(sockfd, (SA *)&servaddr, sizeof(servaddr)) != 0) {
            printf("connection with the server failed...\n");
            sleep(10);
            continue;
        }
        else {
            printf("connected to the server..\n");
        }

        // infinite loop for chat
        for (;;) {
            bzero(buff, MAX);

            // read the message from client and copy it in buffer
            n = read(sockfd, buff, sizeof(buff));
            // print buffer which contains the client contents
            // fprintf(stderr, "recieved %d bytes from host: %s", n, buff);

            // socket disconnected
            if (n <= 0)
                break;

            aee_host_msg_callback(buff, n);
        }
    }

    // After chatting close the socket
    close(sockfd);
}

static bool
host_init()
{
    return true;
}

int
host_send(void *ctx, const char *buf, int size)
{
    int ret;

    if (pthread_mutex_trylock(&sock_lock) == 0) {
        if (sockfd == -1) {
            pthread_mutex_unlock(&sock_lock);
            return 0;
        }

        ret = write(sockfd, buf, size);

        pthread_mutex_unlock(&sock_lock);
        return ret;
    }

    return -1;
}

void
host_destroy()
{
    if (server_mode)
        close(listenfd);

    pthread_mutex_lock(&sock_lock);
    close(sockfd);
    pthread_mutex_unlock(&sock_lock);
}

/* clang-format off */
host_interface interface = {
    .init = host_init,
    .send = host_send,
    .destroy = host_destroy
};
/* clang-format on */

/* Change it to 1 when fuzzing test */
#define WASM_ENABLE_FUZZ_TEST 0

void *
func_server_mode(void *arg)
{
    int clilent;
    struct sockaddr_in serv_addr, cli_addr;
    int n;
    char buff[MAX];
    struct sigaction sa;

    sa.sa_handler = SIG_IGN;
    sa.sa_flags = 0;
    sigemptyset(&sa.sa_mask);
    sigaction(SIGPIPE, &sa, 0);

    /* First call to socket() function */
    listenfd = socket(AF_INET, SOCK_STREAM, 0);

    if (listenfd < 0) {
        perror("ERROR opening socket");
        exit(1);
    }

    /* Initialize socket structure */
    bzero((char *)&serv_addr, sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(port);

    /* Now bind the host address using bind() call.*/
    if (bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        perror("ERROR on binding");
        exit(1);
    }

    listen(listenfd, 5);
    clilent = sizeof(cli_addr);

    while (1) {
        pthread_mutex_lock(&sock_lock);

        sockfd = accept(listenfd, (struct sockaddr *)&cli_addr, &clilent);

        pthread_mutex_unlock(&sock_lock);

        if (sockfd < 0) {
            perror("ERROR on accept");
            exit(1);
        }

        printf("connection established!\n");

        for (;;) {
            bzero(buff, MAX);

            // read the message from client and copy it in buffer
            n = read(sockfd, buff, sizeof(buff));

            // socket disconnected
            if (n <= 0) {
                pthread_mutex_lock(&sock_lock);
                close(sockfd);
                sockfd = -1;
                pthread_mutex_unlock(&sock_lock);

                sleep(1);
                break;
            }

            aee_host_msg_callback(buff, n);
        }
#if WASM_ENABLE_FUZZ_TEST != 0
        /* Exit the process when host disconnect.
           This is helpful for reproducing failure case. */
        close(sockfd);
        exit(1);
#endif
    }
}

#else
static int
parse_baudrate(int baud)
{
    switch (baud) {
        case 9600:
            return B9600;
        case 19200:
            return B19200;
        case 38400:
            return B38400;
        case 57600:
            return B57600;
        case 115200:
            return B115200;
        case 230400:
            return B230400;
        case 460800:
            return B460800;
        case 500000:
            return B500000;
        case 576000:
            return B576000;
        case 921600:
            return B921600;
        case 1000000:
            return B1000000;
        case 1152000:
            return B1152000;
        case 1500000:
            return B1500000;
        case 2000000:
            return B2000000;
        case 2500000:
            return B2500000;
        case 3000000:
            return B3000000;
        case 3500000:
            return B3500000;
        case 4000000:
            return B4000000;
        default:
            return -1;
    }
}
static bool
uart_init(const char *device, int baudrate, int *fd)
{
    int uart_fd;
    struct termios uart_term;

    uart_fd = open(device, O_RDWR | O_NOCTTY);

    if (uart_fd <= 0)
        return false;

    memset(&uart_term, 0, sizeof(uart_term));
    uart_term.c_cflag = baudrate | CS8 | CLOCAL | CREAD;
    uart_term.c_iflag = IGNPAR;
    uart_term.c_oflag = 0;

    /* set noncanonical mode */
    uart_term.c_lflag = 0;
    uart_term.c_cc[VTIME] = 30;
    uart_term.c_cc[VMIN] = 1;
    tcflush(uart_fd, TCIFLUSH);

    if (tcsetattr(uart_fd, TCSANOW, &uart_term) != 0) {
        close(uart_fd);
        return false;
    }

    *fd = uart_fd;

    return true;
}

static void *
func_uart_mode(void *arg)
{
    int n;
    char buff[MAX];

    if (!uart_init(uart_device, baudrate, &uartfd)) {
        printf("open uart fail! %s\n", uart_device);
        return NULL;
    }

    for (;;) {
        bzero(buff, MAX);

        n = read(uartfd, buff, sizeof(buff));

        if (n <= 0) {
            close(uartfd);
            uartfd = -1;
            break;
        }

        aee_host_msg_callback(buff, n);
    }

    return NULL;
}

static int
uart_send(void *ctx, const char *buf, int size)
{
    int ret;

    ret = write(uartfd, buf, size);

    return ret;
}

static void
uart_destroy()
{
    close(uartfd);
}

/* clang-format off */
static host_interface interface = {
    .send = uart_send,
    .destroy = uart_destroy
};
/* clang-format on */

#endif

static attr_container_t *
read_test_sensor(void *sensor)
{
    attr_container_t *attr_obj = attr_container_create("read test sensor data");
    if (attr_obj) {
        bool ret =
            attr_container_set_string(&attr_obj, "name", "read test sensor");
        if (!ret) {
            attr_container_destroy(attr_obj);
            return NULL;
        }
        return attr_obj;
    }
    return NULL;
}

static bool
config_test_sensor(void *s, void *config)
{
    return false;
}

static char global_heap_buf[1024 * 1024] = { 0 };

/* clang-format off */
static void
showUsage()
{
#ifndef CONNECTION_UART
     printf("Usage:\n");
     printf("\nWork as TCP server mode:\n");
     printf("\tsimple -s|--server_mode -p|--port <Port>\n");
     printf("where\n");
     printf("\t<Port> represents the port that would be listened on and the default is 8888\n");
     printf("\nWork as TCP client mode:\n");
     printf("\tsimple -a|--host_address <Host Address> -p|--port <Port>\n");
     printf("where\n");
     printf("\t<Host Address> represents the network address of host and the default is 127.0.0.1\n");
     printf("\t<Port> represents the listen port of host and the default is 8888\n");
#else
     printf("Usage:\n");
     printf("\tsimple -u <Uart Device> -b <Baudrate>\n\n");
     printf("where\n");
     printf("\t<Uart Device> represents the UART device name and the default is /dev/ttyS2\n");
     printf("\t<Baudrate> represents the UART device baudrate and the default is 115200\n");
#endif
}
/* clang-format on */

static bool
parse_args(int argc, char *argv[])
{
    int c;

    while (1) {
        int optIndex = 0;
        static struct option longOpts[] = {
#ifndef CONNECTION_UART
            { "server_mode", no_argument, NULL, 's' },
            { "host_address", required_argument, NULL, 'a' },
            { "port", required_argument, NULL, 'p' },
#else
            { "uart", required_argument, NULL, 'u' },
            { "baudrate", required_argument, NULL, 'b' },
#endif
            { "help", required_argument, NULL, 'h' },
            { 0, 0, 0, 0 }
        };

        c = getopt_long(argc, argv, "sa:p:u:b:w:h", longOpts, &optIndex);
        if (c == -1)
            break;

        switch (c) {
#ifndef CONNECTION_UART
            case 's':
                server_mode = true;
                break;
            case 'a':
                host_address = optarg;
                printf("host address: %s\n", host_address);
                break;
            case 'p':
                port = atoi(optarg);
                printf("port: %d\n", port);
                break;
#else
            case 'u':
                uart_device = optarg;
                printf("uart device: %s\n", uart_device);
                break;
            case 'b':
                baudrate = parse_baudrate(atoi(optarg));
                printf("uart baudrate: %s\n", optarg);
                break;
#endif
            case 'h':
                showUsage();
                return false;
            default:
                showUsage();
                return false;
        }
    }

    return true;
}

// Driver function
int
iwasm_main(int argc, char *argv[])
{
    RuntimeInitArgs init_args;
    korp_tid tid;

    if (!parse_args(argc, argv))
        return -1;

    memset(&init_args, 0, sizeof(RuntimeInitArgs));

#if USE_GLOBAL_HEAP_BUF != 0
    init_args.mem_alloc_type = Alloc_With_Pool;
    init_args.mem_alloc_option.pool.heap_buf = global_heap_buf;
    init_args.mem_alloc_option.pool.heap_size = sizeof(global_heap_buf);
#else
    init_args.mem_alloc_type = Alloc_With_Allocator;
    init_args.mem_alloc_option.allocator.malloc_func = malloc;
    init_args.mem_alloc_option.allocator.realloc_func = realloc;
    init_args.mem_alloc_option.allocator.free_func = free;
#endif

    /* initialize runtime environment */
    if (!wasm_runtime_full_init(&init_args)) {
        printf("Init runtime environment failed.\n");
        return -1;
    }

    /* connection framework */
    if (!init_connection_framework()) {
        goto fail1;
    }

    /* sensor framework */
    if (!init_sensor_framework()) {
        goto fail2;
    }

    /* timer manager */
    if (!init_wasm_timer()) {
        goto fail3;
    }

    /* add the sys sensor objects */
    add_sys_sensor("sensor_test1", "This is a sensor for test", 0, 1000,
                   read_test_sensor, config_test_sensor);
    add_sys_sensor("sensor_test2", "This is a sensor for test", 0, 1000,
                   read_test_sensor, config_test_sensor);
    start_sensor_framework();

#ifndef CONNECTION_UART
    if (server_mode)
        os_thread_create(&tid, func_server_mode, NULL,
                         BH_APPLET_PRESERVED_STACK_SIZE);
    else
        os_thread_create(&tid, func, NULL, BH_APPLET_PRESERVED_STACK_SIZE);
#else
    os_thread_create(&tid, func_uart_mode, NULL,
                     BH_APPLET_PRESERVED_STACK_SIZE);
#endif

    app_manager_startup(&interface);

    exit_wasm_timer();

fail3:
    exit_sensor_framework();

fail2:
    exit_connection_framework();

fail1:
    wasm_runtime_destroy();

    return -1;
}


text:
package decorator

import (
	"go/ast"
	"go/format"
	"go/token"
	"io"
	"io/ioutil"
)

type ProfInjector interface {
	Inject(code string) *ast.File
}

type FileInjector struct {
	injector ProfInjector
}

func NewFileInjector(injector ProfInjector) *FileInjector {
	return &FileInjector{
		injector: injector,
	}
}

func (i *FileInjector) Inject(reader io.Reader, writer io.Writer) {
	code, err := ioutil.ReadAll(reader)
	if err != nil {
		panic(err)
	}

	f := i.injector.Inject(string(code))
	output(f, writer)
}

func output(f ast.Node, writer io.Writer) error {
	return format.Node(writer, token.NewFileSet(), f)
}


text:
$LOAD_PATH << "." unless $LOAD_PATH.include?(".")
require 'rails'
require File.expand_path('../../lib/appmospheres_audit', __FILE__)
require 'ammeter/init'
require 'database_cleaner'
require 'fake_app'
require 'rspec/rails'

RSpec.configure do |config|
  config.before :all do
    CreateAllTables.up unless ActiveRecord::Base.connection.table_exists? :users
  end
end


text:
package com.jonandvirginia.hr.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

/**
 * Basic employee data: name, type, title.
 */
@Entity
public class Employee {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
	private String id;
	private String firstname;
	private String lastname;
	private String group;
	private String type;
	private String title;

	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}

	public String getFirstname() {
		return firstname;
	}
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public String getLastname() {
		return lastname;
	}
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	public String getGroup() {
		return group;
	}
	public void setGroup(String group) {
		this.group = group;
	}

	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}

	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
}


text:
package com.intellij.lang.java;

import com.intellij.lang.ImportOptimizer;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiImportList;
import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NotNull;

/**
 * @author max
 */
public class JavaImportOptimizer implements ImportOptimizer {
  private static final Logger LOG = Logger.getInstance("#com.intellij.lang.java.JavaImportOptimizer");

  @Override
  @NotNull
  public Runnable processFile(final PsiFile file) {
    if (!(file instanceof PsiJavaFile)) {
      return EmptyRunnable.getInstance();
    }
    Project project = file.getProject();
    final PsiImportList newImportList = JavaCodeStyleManager.getInstance(project).prepareOptimizeImportsResult((PsiJavaFile)file);
    if (newImportList == null) return EmptyRunnable.getInstance();
    return new Runnable() {
      @Override
      public void run() {
        try {
          final PsiDocumentManager manager = PsiDocumentManager.getInstance(file.getProject());
          final Document document = manager.getDocument(file);
          if (document != null) {
            manager.commitDocument(document);
          }
          final PsiImportList oldImportList = ((PsiJavaFile)file).getImportList();
          assert oldImportList != null;
          oldImportList.replace(newImportList);
        }
        catch (IncorrectOperationException e) {
          LOG.error(e);
        }
      }
    };
  }

  @Override
  public boolean supports(PsiFile file) {
    return file instanceof PsiJavaFile;
  }
}


text:
<!DOCTYPE html >

          <meta http-equiv="X-UA-Compatible" content="IE=edge" />
          <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
          <title>ScalaTest 3.0.5  - org.scalatest.mockito</title>
          <meta name="description" content="ScalaTest 3.0.5 - org.scalatest.mockito" />
          <meta name="keywords" content="ScalaTest 3.0.5 org.scalatest.mockito" />
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />

      <link href="../../../lib/index.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
      <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />

        ScalaTest 3.0.5
        < Back

            <input autocapitalize="none" placeholder="Search" id="index-input" type="text" accesskey="/" />
            
            

Packages

        

        package

        root

Definition Classes

root

        

        package

        org

Definition Classes

root

        

        package

        scalatest

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

Definition Classes

org

        

        package

        compatible

Definition Classes

scalatest

        

        package

        concurrent

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

ScalaTest's main traits, classes, and other members, including members supporting ScalaTest's DSL for the Scala interpreter.

Definition Classes

scalatest

        

        package

        easymock

Definition Classes

scalatest

        

        package

        enablers

Definition Classes

scalatest

        

        package

        events

Definition Classes

scalatest

        

        package

        exceptions

Definition Classes

scalatest

        

        package

        fixture

Definition Classes

scalatest

        

        package

        jmock

Definition Classes

scalatest

        

        package

        junit

Definition Classes

scalatest

        

        package

        matchers

Definition Classes

scalatest

        

        package

        mockito

Definition Classes

scalatest

                        MockitoSugar

        

        package

        path

Definition Classes

scalatest

        

        package

        prop

Definition Classes

scalatest

        

        package

        refspec

Definition Classes

scalatest

        

        package

        selenium

Definition Classes

scalatest

        

        package

        tagobjects

Definition Classes

scalatest

        

        package

        tags

Definition Classes

scalatest

        

        package

        testng

Definition Classes

scalatest

        

        package

        time

Definition Classes

scalatest

        

        package

        tools

Definition Classes

scalatest

        

        package

        words

Definition Classes

scalatest

p

org.scalatest

mockito

        

        package

        mockito

          

            <input id="mbrsel-input" placeholder="Filter all members" type="text" accesskey="/" />

          

            Ordering

Alphabetic

              Visibility

Public

All

Type Members

        

        trait

        MockitoSugar extends AnyRef

Trait that provides some basic syntax sugar for Mockito.

Trait that provides some basic syntax sugar for Mockito.

Using the Mockito API directly, you create a mock with:

val mockCollaborator = mock(classOf[Collaborator])

Using this trait, you can shorten that to:

val mockCollaborator = mock[Collaborator]

This trait also provides shorthands for the three other (non-deprecated) overloaded mock methods,
which allow you to pass in a default answer, a name, or settings.

Value Members

        

        object

        MockitoSugar extends MockitoSugar

Companion object that facilitates the importing of MockitoSugar members as
an alternative to mixing it in.

Companion object that facilitates the importing of MockitoSugar members as
an alternative to mixing it in. One use case is to import MockitoSugar members so you can use
them in the Scala interpreter.

Ungrouped


text:
This is the fastest way to get going with Fabric8 and OpenShift on your laptop.

Here is a [video walking you through these steps](https://vimeo.com/134408216)

### How to vagrant up

* Download and install [VirtualBox](https://www.virtualbox.org/wiki/Downloads)
* Download and install [Vagrant](http://www.vagrantup.com/downloads.html)

Now clone the [fabric8 installer git repository](https://github.com/fabric8io/fabric8-installer) repository and type these commands:

```sh
$ git clone https://github.com/fabric8io/fabric8-installer.git
$ cd fabric8-installer/vagrant/openshift/latest
```

Depending on your host operating system you need to install an additional vagrant plugin:

* `vagrant plugin install landrush` for Linux and OS X
* `vagrant plugin install vagrant-hostmanager-fabric8` for Windows

The next steps are needed for proper routing from the host to OpenShift services which are exposed via routes:

* **Linux**: Setup up once a `dnsmasq` DNS proxy locally. The detailed procedure depend on the Linux distribution used.
  Here is the example for Ubuntu:

        sudo apt-get install -y resolvconf dnsmasq
        sudo sh -c 'echo "server=/vagrant.dev/127.0.0.1#10053" > /etc/dnsmasq.d/vagrant-landrush'
        sudo service dnsmasq restart

* **Windows**: Unfortunately for Windows no automatic routing for new services is possible. You have to add new routes
  manually to `%WINDIR%\System32\drivers\etc\hosts`. For your convenience, a set of routes for default Fabric8 applications
  has been pre-added. For new services look for the following line and add your new routes (`<service-name>.vagrant.f8`) to
  this file on a new line like this:

        ## vagrant-hostmanager-start id: 9a4ba3f3-f5e4-4ad4-9e80-b4045c6cf2fc
        172.28.128.4  vagrant.f8 fabric8.vagrant.f8 jenkins.vagrant.f8 .....
        172.28.128.4  myservice.vagrant.f8
        ## vagrant-hostmanager-end

* **OS X**: Nothing has to be done. OS X will automatically resolve all routes to `*.vagrant.f8` to
  your Vagrant VM. This is done vial OS X's resolver feature (see `man 5 resolver` for details)

Now startup the Vagrant VM

```sh
vagrant up
```

Note the vagrant image is by default configured with 2 cpu cores and 4gb of memory. It is recommended to not exceed about half of your machine's resources. In case you have plenty of resources on your machine you can increase the settings, by editing the `Vagrantfile`. The settings are defined in the bottom of the file:

```ruby
v.memory = 4096
v.cpus = 2
```

Then follow the on screen instructions.

* You should now have a running vagrant image running at IP address `172.28.128.4` or at `vagrant.f8`
* Downloading the docker images may take a few minutes so you might want to jump ahead
  to the [Local Setup](local.html) recipe then coming back here when you're done.
* After the vagrant box is created and docker images are downloaded, the [fabric8 console](../console.html) should
  appear at [http://fabric8.vagrant.f8/](http://fabric8.vagrant.f8/)
* When you first open your browser Chrome will say:

        Your connection is not private

* You will want to accept the self signed cert, follow [these steps](./browserCertificates.html) and return here
* Enter `admin` and `admin`
* You should now be in the main fabric8 console! That was easy eh! :)
* Make sure you start off in the `default` namespace.

### Installing other applications

When you are on the `Apps` tab in the [fabric8 console](http://fabric8.io/guide/console.html) click on
the `Run...` button.

This will list all of the installed [OpenShift Templates](http://docs.openshift.org/latest/dev_guide/templates.html)
on your installation.

* To Run any of the installed templates just click the `Run` button (the green play button).
* To install any new [OpenShift Templates](http://docs.openshift.org/latest/dev_guide/templates.html) or other Kubernetes resources just drag and drop the JSON file onto the `Apps` tab!
  * You can download the [fabric8 templates 2.2.16 distribution](http://repo1.maven.org/maven2/io/fabric8/apps/distro/2.2.16/distro-2.2.16-templates.zip) unzip and drag the JSON files you want to install onto the [fabric8 console](http://fabric8.io/guide/console.html) and they should appear on the `Run...` page
* You can also install other OpenShift Templates or Kubernetes resources via the **oc** command line tool:

    oc create -f jsonOrYamlFileOrUrl

### Setting up your local machine

In order to communicate with the Vagrant VM from you localhost it is recommended to install the OpenShift client
tools. This is explained in an extra [document](local.html).

This is also useful using the [fabric8 maven tooling](../mavenPlugin.html) or reusing the docker daemon
inside vagrant; so that all images built are accessible inside the OpenShift environment.

Alternatively you can log into the Vagrant VM also via `vagrant ssh`. The OpenShift tools (`oc`, `oadmn`) are installed in the VM, too.

### Trying a fresh image

Note: in case you already ran the above and want to update to the latest vagrant image, OpenShift and Fabric8 release you need to destroy and recreate the vagrant image.
You can do that using:

```sh
vagrant destroy -f
git pull
vagrant up
```

### Troubleshooting

The `oc` command can be really useful for viewing resources (pods, services, RCs, templates etc) and deleting pods so
they get recreated, looking at logs etc.

If you add the `fabric8-installer/bin` folder to your `$PATH` then there are a few handy shell scripts

* `oc-bash name` finds the first pod with the given name pattern and runs a bash shell in the docker container
* `oc-log name` finds the first pod with the given name pattern and shows the container's log

On your host machine or inside the vagrant image you should have access to docker thanks to the environment variable:

```sh
export DOCKER_HOST=tcp://vagrant.f8:2375
```

So you should be able to run things like

```sh
docker ps
docker log nameOfContainer
```

You can SSH into the vagrant image using:

```sh
vagrant ssh
```

Then you can look around.

#### Looking at the OpenShift logs

If you hit any issues then try look at the logs for the `openshift` master:

```sh
vagrant ssh
sudo journalctl -u openshift
```

Or you can tail the logs via

```sh
vagrant ssh
sudo journalctl -fu openshift
```

You can watch the docker daemon too via

```sh
vagrant ssh
sudo journalctl -fu docker
```


text:
  package test.routes;

import com.firefly.model.Model;
import com.firefly.tools.DateUtil;

public class RouteModel extends Model {

	private Integer rownum;

	private String id;
	private String name;
	private String tags;
	private String author;
	private Long startdate;
	private Integer days;
	private Long enddate;
	private String startcity;
	private String endcity;
	public Integer getDays() {
		return days;
	}
	public void setDays(Integer days) {
		this.days = days;
	}
	public String getStartcity() {
		return startcity;
	}
	public void setStartcity(String startcity) {
		this.startcity = startcity;
	}
	public String getEndcity() {
		return endcity;
	}
	public void setEndcity(String endcity) {
		this.endcity = endcity;
	}
	private Integer status;
	private String pics;
	private String detail;
	public Integer getRownum() {
		return rownum;
	}
	public void setRownum(Integer rownum) {
		this.rownum = rownum;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTags() {
		return tags;
	}
	public void setTags(String tags) {
		this.tags = tags;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public Long getStartdate() {
		return startdate;
	}
	public void setStartdate(Long startdate) {
		this.startdate = startdate;
	}
	public Long getEnddate() {
		return enddate;
	}
	public void setEnddate(Long enddate) {
		this.enddate = enddate;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public String getPics() {
		return pics;
	}
	public void setPics(String pics) {
		this.pics = pics;
	}
	public String getDetail() {
		return detail;
	}
	public void setDetail(String detail) {
		this.detail = detail;
	}

	public String getStartdateStr() {
		return DateUtil.long2String(getStartdate());
	}
	public void setStartdateStr(String startdateStr) {
		setStartdate(DateUtil.string2LongBegin(startdateStr));
	}
	private String startdateStr;
	private String startcityStr;
	private String endcityStr;
	public String getStartcityStr() {
		return startcityStr;
	}
	public void setStartcityStr(String startcityStr) {
		this.startcityStr = startcityStr;
	}
	public String getEndcityStr() {
		return endcityStr;
	}
	public void setEndcityStr(String endcityStr) {
		this.endcityStr = endcityStr;
	}

}


text:
import fs from 'fs';

/**
 * Checks if a path is writable.
 * @param    {string}  path Directory or file path.
 * @returns  {Promise}
 * @resolves {bool}         Resolves
 * @rejects  {Error}        Error from filesystem access attempt
 */
export default function pathHasReadWrite(path) {
  return new Promise((resolve, reject) => {
    fs.access(
      path,
      // eslint-disable-next-line no-bitwise
      fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK,
      (error) => {
        if (error) {
          reject(error);
        }

        resolve(true);
      },
    );
  });
}


text:
<?php

namespace DAO;

use DAO;

/**
 * Function that maps to SQL NOW().
 *
 * @see DAO\Func
 */
class FuncNow
{
    public function __toString()
    {
        return 'NOW()';
    }

    public static function imbue()
    {
        return new static();
    }
}


text:
#include "sol-buffer.h"
#include "sol-flow/update.h"
#include "sol-flow-internal.h"
#include "sol-json.h"
#include "sol-macros.h"
#include "sol-str-slice.h"
#include "sol-types.h"
#include "sol-update.h"

#include <sol-util-internal.h>
#include <errno.h>

struct update_data {
    struct sol_update_handle *handle;
};

struct update_node_type {
    struct sol_flow_node_type base;
    uint16_t progress_port;
};

static int
cancel_check_process(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    struct update_data *mdata = data;

    if (mdata->handle) {
        if (!sol_update_cancel(mdata->handle))
            sol_flow_send_error_packet(node, EINVAL,
                "Could not cancel check process");
        else
            mdata->handle = NULL;
    } else {
        SOL_WRN("No current check in process, ignoring request to cancel");
    }

    return 0;
}

static void
check_cb(void *data, int status, const struct sol_update_info *response)
{
    struct sol_flow_node *node = data;
    struct update_data *mdata = sol_flow_node_get_private_data(node);

    if (status < 0) {
        sol_flow_send_error_packet(node, -status,
            "Error while checking for updates: %s", sol_util_strerrora(-status));
        goto end;
    }

#ifndef SOL_NO_API_VERSION
    if (SOL_UNLIKELY(response->api_version != SOL_UPDATE_INFO_API_VERSION)) {
        SOL_WRN("Update info config version '%u' is unexpected, expected '%u'",
            response->api_version, SOL_UPDATE_INFO_API_VERSION);
        return;
    }
#endif

    sol_flow_send_string_packet(node,
        SOL_FLOW_NODE_TYPE_UPDATE_CHECK__OUT__VERSION, response->version);
    sol_flow_send_irange_value_packet(node,
        SOL_FLOW_NODE_TYPE_UPDATE_CHECK__OUT__SIZE, response->size);
    sol_flow_send_boolean_packet(node,
        SOL_FLOW_NODE_TYPE_UPDATE_CHECK__OUT__NEED_UPDATE, response->need_update);

end:
    mdata->handle = NULL;
}

static int
check_process(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    struct update_data *mdata = data;

    if (mdata->handle) {
        SOL_DBG("Check already in progress. Ignoring packet");
        return 0;
    }

    mdata->handle = sol_update_check(check_cb, node);
    if (!mdata->handle) {
        sol_flow_send_error_packet(node, EINVAL,
            "Could not check for updates");
        return -EINVAL;
    }

    return 0;
}

static void
common_close(struct sol_flow_node *node, void *data)
{
    struct update_data *mdata = data;

    if (mdata->handle) {
        if (!sol_update_cancel(mdata->handle))
            SOL_WRN("Could not cancel ongoing task: %p", mdata->handle);
    }
}

static int
cancel_fetch_process(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    struct update_data *mdata = data;

    if (mdata->handle) {
        if (!sol_update_cancel(mdata->handle))
            sol_flow_send_error_packet(node, EINVAL,
                "Could not cancel fetch process");
        else
            mdata->handle = NULL;
    } else {
        SOL_WRN("No current fetch in process, ignoring request to cancel");
    }

    return 0;
}

static void
fetch_cb(void *data, int status)
{
    struct sol_flow_node *node = data;
    struct update_data *mdata = sol_flow_node_get_private_data(node);

    if (status < 0) {
        sol_flow_send_error_packet(node, -status,
            "Error while fetching update file: %s",
            sol_util_strerrora(-status));
    }

    sol_flow_send_boolean_packet(node,
        SOL_FLOW_NODE_TYPE_UPDATE_FETCH__OUT__SUCCESS, status == 0);

    mdata->handle = NULL;
}

static int
fetch_process(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    struct update_data *mdata = data;

    if (mdata->handle) {
        SOL_DBG("Fetch already in progress. Ignoring packet");
        return 0;
    }

    mdata->handle = sol_update_fetch(fetch_cb, node, true);
    if (!mdata->handle) {
        sol_flow_send_error_packet(node, EINVAL, "Could not fetch update file");
        return -EINVAL;
    }

    return 0;
}

static int
cancel_install_process(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    struct update_data *mdata = data;

    if (mdata->handle) {
        if (!sol_update_cancel(mdata->handle))
            sol_flow_send_error_packet(node, EINVAL,
                "Could not cancel install process");
        else
            mdata->handle = NULL;
    } else {
        SOL_WRN("No current install in process, ignoring request to cancel");
    }

    return 0;
}

static void
install_cb(void *data, int status)
{
    struct sol_flow_node *node = data;
    struct update_data *mdata = sol_flow_node_get_private_data(node);

    if (status < 0) {
        sol_flow_send_error_packet(node, -status,
            "Error while installing update: %s", sol_util_strerrora(-status));
    }

    sol_flow_send_boolean_packet(node,
        SOL_FLOW_NODE_TYPE_UPDATE_INSTALL__OUT__SUCCESS, status == 0);

    mdata->handle = NULL;
}

static int
install_process(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    struct update_data *mdata = data;

    if (mdata->handle) {
        SOL_DBG("Install already in progress. Ignoring packet");
        return 0;
    }

    mdata->handle = sol_update_install(install_cb, node);
    if (!mdata->handle) {
        sol_flow_send_error_packet(node, EINVAL, "Could not install update file");
        return -EINVAL;
    }

    return 0;
}

static int
common_get_progress(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet)
{
    struct update_data *mdata = data;
    struct update_node_type *type;
    struct sol_irange irange = {
        .step = 1,
        .min = 0,
        .max = 100
    };

    type = (struct update_node_type *)sol_flow_node_get_type(node);

    if (mdata->handle) {
        irange.val = sol_update_get_progress(mdata->handle);
        if (irange.val >= 0 && irange.val <= 100)
            sol_flow_send_irange_packet(node, type->progress_port, &irange);
        else
            sol_flow_send_error_packet(node, EINVAL,
                "Could not get progress of task");
    } else {
        SOL_DBG("No current operation in process, ignoring request to get progress");
    }

    return 0;
}

#include "update-gen.c"


text:
(function () {
  'use strict';

  angular
    .module('app.core')
    .directive('gtCountUpTo', gtCountUpTo);

  /** @ngInject */
  function gtCountUpTo($timeout) {
    const directive = {
      link,
      restrict: 'A',
      scope: {
        countUpTo: '=gtCountUpTo'
      }
    };
    return directive;

    function link($scope, $element, $attrs) {
      const options = {
        useEasing: true,
        useGrouping: true,
        separator: ',',
        decimal: '.',
        prefix: '',
        suffix: ''
      };

      $attrs.from = angular.isDefined($attrs.from) ? parseInt($attrs.from) : 0;
      $attrs.decimals = angular.isDefined($attrs.decimals) ? parseInt($attrs.decimals) : 2;
      $attrs.duration = angular.isDefined($attrs.duration) ? parseFloat($attrs.duration) : 3;

      const watch = $scope.$watch('countUpTo', () => {
        $timeout(() => {
          const animation = new CountUp($element[0], $attrs.from, $scope.countUpTo, $attrs.decimals, $attrs.duration, options);
          animation.start();
        }, 100);
      });

      $scope.$on('$destroy', () => {
        watch();
      });
    }
  }
})();


text:
pub trait IterUtilsExt: Iterator {
    /// Return the first element that maps to `Some(_)`, or None if the iterator
    /// was exhausted.
    fn ex_find_map<F, R>(&mut self, mut f: F) -> Option<R>
    where
        F: FnMut(Self::Item) -> Option<R>,
    {
        for elt in self {
            if let result @ Some(_) = f(elt) {
                return result;
            }
        }
        None
    }

    /// Return the last element from the back that maps to `Some(_)`, or
    /// None if the iterator was exhausted.
    fn ex_rfind_map<F, R>(&mut self, mut f: F) -> Option<R>
    where
        F: FnMut(Self::Item) -> Option<R>,
        Self: DoubleEndedIterator,
    {
        while let Some(elt) = self.next_back() {
            if let result @ Some(_) = f(elt) {
                return result;
            }
        }
        None
    }
}

impl<I> IterUtilsExt for I where I: Iterator {}


text:
@class SYUserInfoListView;

@protocol SYUserInfoListViewDelegate <NSObject>

//点击阴影部分 显示导航栏和状态栏
-(void)infoListViewRemoveFromSuperView:(SYUserInfoListView*)infoListView;

//点击cell跳转到不同的控制器
-(void)infoListView:(SYUserInfoListView*)infoListView didSelectRowWithIndexPath:(NSIndexPath*)indexPath;

@end

@interface SYUserInfoListView : UIView

@property (nonatomic ,weak)id<SYUserInfoListViewDelegate> delegate;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<project>
  <properties>
    <hudson.plugins.promoted__builds.JobPropertyImpl>
      <activeProcessNames>
        <string>Release to QA</string>
        <string>Jane Must Approve</string>
      </activeProcessNames>
    </hudson.plugins.promoted__builds.JobPropertyImpl>
  </properties>
</project>


text:
<?php

namespace zsql\Migrator\Tests;

class MigratorIntegrationTest extends Common
{
    public function setup()
    {
        $d = $this->databaseFactory();
        $d->query('TRUNCATE TABLE `zsql`.`migrationsFixtureE`');
        $d->query('DROP TABLE IF EXISTS `zsql`.`migrationtesta`');
        $d->query('DROP TABLE IF EXISTS `zsql`.`migrationtestb`');
        $d->query('DROP TABLE IF EXISTS `zsql`.`migrationtestc`');
        $d->query('DROP TABLE IF EXISTS `zsql`.`migrationtestd`');
        $d->query('DROP TABLE IF EXISTS `zsql`.`migrationteste`');
        $d->query('DROP TABLE IF EXISTS `zsql`.`migrationtestf`');
        $d->query('DROP TABLE IF EXISTS `zsql`.`migrationtestg`');
    }

    public function testIntegration()
    {
        $database = $this->databaseFactory();
        $migrator = $this->migratorFactory('migrationsC', 'migrationsFixtureE');

        // First, let's migrate all the way up
        $migrator->migrateLatest();

        // Check that all five migrations completed successfully
        $rows = $database->select()
                ->from('migrationsFixtureE')
                ->query()
                ->fetchAll();
        $this->assertCount(5, $rows);
        foreach( $rows as $row ) {
            $this->assertEquals('success', $row->state);
        }
        $blegh = $database->query('SHOW TABLES')->fetchAll(\zsql\Result::FETCH_COLUMN);
        $this->assertContains('migrationtesta', $blegh);
        $this->assertContains('migrationtestb', $blegh);
        $this->assertContains('migrationtestc', $blegh);
        $this->assertContains('migrationtestd', $blegh);
        $this->assertContains('migrationteste', $blegh);

        // Now let's revert a couple migrations
        $migrator->migrateRevert(array(
            1412129177,
            1412292439
        ));

        // Check that all five migrations completed successfully
        $rows = $database->select()
                ->from('migrationsFixtureE')
                ->query()
                ->fetchAll();
        $this->assertCount(5, $rows);
        foreach( $rows as $row ) {
            if( $row->version == 1412129177 ||
                $row->version == 1412292439 ) {
                $this->assertEquals('initial', $row->state);
            } else {
                $this->assertEquals('success', $row->state);
            }
        }
        $blegh = $database->query('SHOW TABLES')->fetchAll(\zsql\Result::FETCH_COLUMN);
        $this->assertContains('migrationtesta', $blegh);
        $this->assertNotContains('migrationtestb', $blegh);
        $this->assertContains('migrationtestc', $blegh);
        $this->assertNotContains('migrationtestd', $blegh);
        $this->assertContains('migrationteste', $blegh);

        // Now let's pick each migration
        $migrator->migratePick(array(
            1412129177,
            1412292439
        ));

        // Check that all five migrations completed successfully
        $rows = $database->select()
                ->from('migrationsFixtureE')
                ->query()
                ->fetchAll();
        $this->assertCount(5, $rows);
        foreach( $rows as $row ) {
            $this->assertEquals('success', $row->state);
        }
        $blegh = $database->query('SHOW TABLES')->fetchAll(\zsql\Result::FETCH_COLUMN);
        $this->assertContains('migrationtesta', $blegh);
        $this->assertContains('migrationtestb', $blegh);
        $this->assertContains('migrationtestc', $blegh);
        $this->assertContains('migrationtestd', $blegh);
        $this->assertContains('migrationteste', $blegh);

        // Let's mark a migration as failed an then retry it
        $database->query('DROP TABLE migrationtestd');
        $database->query("UPDATE migrationsFixtureE SET state = 'failed' "
                . "WHERE version = 1412292439 LIMIT 1");
        $migrator = $this->migratorFactory('migrationsC', 'migrationsFixtureE');

        $migrator->migrateRetry();

        $row = $database->select()
                ->from('migrationsFixtureE')
                ->where('version', 1412292439)
                ->query()
                ->fetchRow();
        $this->assertEquals('success', $row->state);
        $blegh = $database->query('SHOW TABLES')->fetchAll(\zsql\Result::FETCH_COLUMN);
        $this->assertContains('migrationtestd', $blegh);
    }
}


text:
<?php
namespace Core\Service;

/**
 * Description of Storage
 *
 * @author uzzal
 */
class SessionStorage extends \Zend\Authentication\Storage\Session{
    public function forgetMe(){
        $this->session->getManager()->forgetMe();
    }
}


text:
<?php

namespace Alzheimer\NoticiasBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class NoticiasType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('titulo')
            ->add('cuerpo','textarea')
            ->add('fecha','date',array('widget' => 'single_text'))
            ->add('imagenPrim','file',array('data_class'=>null))
            ->add('imagenSec','file', array('data_class'=>null))
	    ->add('guardar', 'submit')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Alzheimer\NoticiasBundle\Entity\Noticias'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'alzheimer_noticiasbundle_noticias';
    }
}


text:
package com.moonlightpixels.jrpg.map.internal;

import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.Array;
import com.moonlightpixels.jrpg.internal.graphics.GraphicsContext;
import com.moonlightpixels.jrpg.map.TileCoordinate;
import lombok.Getter;

import java.io.Serializable;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;

final class JRPGMapLayer {
    private static final ActorRenderOrderComparator ACTOR_RENDER_ORDER_COMPARATOR = new ActorRenderOrderComparator();

    @Getter
    private final int layerIndex;
    private final TiledMapRenderer mapRenderer;
    private final Stage stage;
    private final List<TiledMapTileLayer> backgroundLayers = new LinkedList<>();
    private final List<TiledMapTileLayer> foregroundLayers = new LinkedList<>();
    private TiledMapTileLayer collisionLayer;

    JRPGMapLayer(final int layerIndex, final TiledMapRenderer mapRenderer, final Stage stage) {
        this.layerIndex = layerIndex;
        this.mapRenderer = mapRenderer;
        this.stage = stage;
    }

    void addBackgroundLayer(final TiledMapTileLayer tileLayer) {
        backgroundLayers.add(tileLayer);
    }

    void addForegroundLayer(final TiledMapTileLayer tileLayer) {
        foregroundLayers.add(tileLayer);
    }

    Optional<TiledMapTileLayer> getCollisionLayer() {
        return Optional.ofNullable(collisionLayer);
    }

    void setCollisionLayer(final TiledMapTileLayer collisionLayer) {
        this.collisionLayer = collisionLayer;
    }

    void addActor(final Actor actor) {
        stage.addActor(actor);
    }

    void removeActor(final Actor actor) {
        stage.getRoot().removeActor(actor);
    }

    void update(final float delta) {
        stage.act(delta);
        sortActors();
    }

    void render(final GraphicsContext graphicsContext) {
        graphicsContext.getSpriteBatch().begin();
        backgroundLayers.forEach(mapRenderer::renderTileLayer);
        graphicsContext.getSpriteBatch().end();

        stage.draw();

        graphicsContext.getSpriteBatch().begin();
        foregroundLayers.forEach(mapRenderer::renderTileLayer);
        graphicsContext.getSpriteBatch().end();
    }

    private void sortActors() {
       Array<Actor> actors = stage.getActors();
       actors.sort(ACTOR_RENDER_ORDER_COMPARATOR);
       for (int i = 0; i < actors.size; i++) {
            actors.get(i).setZIndex(i);
       }
    }

    boolean isOpen(final TileCoordinate tileCoordinate) {
        return getCollisionLayer()
            .map(tiledMapTileLayer -> tiledMapTileLayer.getCell(tileCoordinate.getX(), tileCoordinate.getY()) == null)
            .orElse(true);
    }

    private static class ActorRenderOrderComparator implements Comparator<Actor>, Serializable {
        private static final long serialVersionUID = 4352090894431376885L;

        @Override
        public int compare(final Actor left, final Actor right) {
            // sort in descending order by Y position
            return Float.compare(right.getY(), left.getY());
        }
    }
}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__wchar_t_console_ifstream_52c.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-52c.tmpl.cpp
*/
/*
 * @description
 * CWE: 36 Absolute Path Traversal
 * BadSource: console Read input from the console
 * GoodSource: Full path and file name
 * Sink: ifstream
 *    BadSink : Open the file named in data using ifstream::open()
 * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files
 *
 * */

#include "std_testcase.h"

#ifndef _WIN32
#include <wchar.h>
#endif

#include <fstream>
using namespace std;

namespace CWE36_Absolute_Path_Traversal__wchar_t_console_ifstream_52
{

/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */

#ifndef OMITBAD

void badSink_c(wchar_t * data)
{
    {
        ifstream inputFile;
        /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
        inputFile.open((char *)data);
        inputFile.close();
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink_c(wchar_t * data)
{
    {
        ifstream inputFile;
        /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
        inputFile.open((char *)data);
        inputFile.close();
    }
}

#endif /* OMITGOOD */

} /* close namespace */


text:
'use strict';

var yeoman = require('yeoman-generator');
var fs = require('fs');
var yosay = require('yosay');
var taskDependencies = require('./taskdependencies');

module.exports = yeoman.generators.NamedBase.extend({
    constructor: function() {
        yeoman.generators.NamedBase.apply(this, arguments);

        this.fileName = this.name + '.js';
        this.srcConfigPath = this.templatePath('configs/' + this.fileName);
        this.srcTaskPath = this.templatePath('tasks/' + this.fileName);
        this.destConfigPath = this.destinationPath('gulp/configs/' + this.fileName);
        this.destTaskPath = this.destinationPath('gulp/tasks/' + this.fileName);
    },
    checkIfTaskExists: function() {
        try {
            fs.lstatSync(this.srcConfigPath);
            fs.lstatSync(this.srcTaskPath);
        } catch (e) {
            this.log('This task doesn\'t exist. Exiting.');
            process.exit(1);
        }
    },
    checkIfGulpIsInstalled: function() {
        try {
            fs.lstatSync(this.destinationPath('gulpfile.js'));
            this.isGulpInstalled = true;
        } catch (e) {
            this.isGulpInstalled = false;
        }
    },
    promptInstallGulp: function() {
        if (!this.isGulpInstalled) {
            var done = this.async();

            this.prompt({
                type: 'confirm',
                name: 'installGulp',
                message: 'It seems Gulp is not installed. Do you want to install it ?'
            }, function(answers) {
                this.installGulp = answers.installGulp;

                done();
            }.bind(this));
        } else {
            this.installGulp = false;
        }
    },
    installGulp: function() {
        if (this.installGulp) {
            var done = this.async();

            this.invoke('sillysmart:gulp')
                .on('end', function() {
                    done();
                });
        }
    },
    copyFiles: function() {
        this.copy(this.srcConfigPath, this.destConfigPath);
        this.copy(this.srcTaskPath, this.destTaskPath);
    },
    installDependencies: function() {
        if (taskDependencies[this.name]) {
            this.npmInstall(taskDependencies[this.name], { saveDev: true });
        }
    }
});


text:
module StripeRails
  class PlanInterval
    attr_accessor :id
    attr_accessor :duration
    attr_accessor :display
    attr_accessor :singular
    attr_accessor :plural

    def self.find(id)
      @items.find {|item| item.id == id}
    end

    def self.find_by_duration(name)
      @items.find {|item| item.duration == name}
    end

    def self.all
      @items
    end

    def to_s
      return self.display
    end

    def monthly?
      duration == 'month'
    end

    def yearly?
      duration == 'year'
    end

    def weekly?
      duration == 'week'
    end

    def daily?
      duration == 'day'
    end

    def self.add_item(id, duration, display, singular, plural )
      @items ||= Array.new

      item = PlanInterval.new
      item.id = id
      item.duration = duration
      item.display = display
      item.singular = singular
      item.plural = plural

      @items.push(item)
    end

    PlanInterval.add_item 1, 'day', 'day(s)', 'daily', 'days'
    PlanInterval.add_item 2, 'week', 'week(s)', 'weekly', 'weeks'
    PlanInterval.add_item 3, 'month', 'month(s)', 'monthly', 'months'
    PlanInterval.add_item 4, 'year', 'year', 'yearly', 'years'
  end
end


text:
/**
 * Dependencies
 */

import angular from 'angular'
import formly from 'angular-formly'
import formlyBootstrap from 'angular-formly-templates-bootstrap'
import pxPagination from '../../components/px-pagination'
import coreFilters from '../../core/filters'

/**
 * Resources
 */

import './style.css'
import template from './template.html'

/**
 * Module
 */

export default angular.module('app.components.pxform', [
  formly,
  formlyBootstrap,
  pxPagination,
  coreFilters,
])
.component('pxForm', {
  bindings: {
    options: '=',
    form: '=?',
    paginationChangeHandler: '&?',
  },
  controller: pxFormCtrl,
  controllerAs: 'vm',
  template: template,
})
.name

/**
 * Component's Controller
 */

function pxFormCtrl($scope, $timeout) {
  var vm = this

  /*
  vm function assignments
   */

  vm.isSubmitDisabled = isSubmitDisabled

  /*
  Sync initialization
   */

  init()

  /*
  Async initialization
   */

  $scope.$watch('vm.options', function(newOptions) {
    if (newOptions) {
      initMetadata(newOptions.metadata, newOptions.data)
      initFields(newOptions.fields, newOptions.data)
      // deferred after form initialization
      $timeout(initReferrerValue)
    }
  })

  /*
  function declarations
   */

  function init() {
    // Default options
    vm.paginationOptions = {}
    vm.paginationOptions.paginationPageSizes = [1, 2, 3, 5, 8, 13]
    vm.paginationOptions.paginationId = 'pagination' + getRandomInt(0, 9999)
  }

  function initFields(fields, data) {
    var countRecords, index
    if (!fields || !data) {
      return
    }
    // Not already initialized as array
    if (!(fields[0] && angular.isArray(fields[0]))) {
      // Fields array initialization
      // Based on: http://angular-formly.com/#/example/advanced/repeating-section
      vm.options.fields = []
      // Get total number of records (multiple paginated), at least create One
      countRecords = data.length || 1
      for (index = 0; index < countRecords; index++) {
        vm.options.fields.push(copyFields(fields, index))
      }
    }
  }

  function initMetadata(metadata, data) {
    if (!metadata) {
      return
    }
    // Pagination
    if (metadata.totalItems) {
      // Server-side Paginationa
      vm.paginationOptions.totalItems = metadata.totalItems
      vm.paginationOptions.paginationPageSize = metadata.pageSize
      vm.paginationOptions.paginationCurrentPage = metadata.pageIndex
    } else {
      // Client-side Pagination
      vm.paginationOptions.totalItems = data.length
      vm.paginationOptions.paginationPageSize = metadata.pageSize || 1
      vm.paginationOptions.paginationCurrentPage = metadata.pageIndex || 1
    }
  }

  function copyFields(fields) {
    var newFields = angular.copy(fields)
    addRandomIds(newFields)
    return newFields
  }

  function addRandomIds(fields) {
    angular.forEach(fields, function(field, index) {
      if (field.fields) {
        addRandomIds(field.fields)
        return // fieldsets/tab don't need an ID
      }
      if (field.fieldGroup) {
        addRandomIds(field.fieldGroup)
        return // fieldGroups don't need an ID
      }
      if (field.type && field.type === 'tabPanel' && field.data && field.data.tabs) {
        addRandomIds(field.data.tabs)
        return // tabPanel don't need an ID
      }
      if (field.data && field.data.fields) {
        addRandomIds(field.data.fields)
        return // nested fields don't need an ID
      }

      field.id = field.id || (field.key + '_' + index + '_' + getRandomInt(0, 9999))
    })
  }

  function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min
  }

  function initReferrerValue() {
    var ref = vm.options.metadata.ref
    var refId = vm.options.metadata.refId
    var fieldName = Object.keys(vm.form).filter((x)=>x.startsWith(ref))[0]
    if (ref && refId && fieldName && vm.form[fieldName]) {
      vm.options.data[0][ref] = refId
      vm.form[fieldName].$setDirty(true)
    }
  }

  function isSubmitDisabled() {
    if (vm.form) {
      if (vm.options.metadata && vm.options.metadata.mode !== 'readonly') {
        if (vm.options.metadata.mode === 'insert') {
          if (vm.form.$invalid) {
            return true
          }
          return false
        } else if (vm.options.metadata.mode === 'edit') {
          if (vm.form.$pristine) {
            return true
          }
          if (vm.form.$invalid) {
            return true
          }
          return false
        }
      }
    }
    return true
  }
}


text:
using System;
using System.Collections.Generic;
using Assets.Characters.AiScripts;
using Assets.Characters.AiScripts.States;
using Assets.Core.Configuration;
using UnityEngine;

namespace Assets.Characters.SideKick.Scripts
{
    public class SidekickControls : MonoBehaviour
    {
        #region Instatiate

        private GameObject _sideKick;
        private NavMeshAgent _sideKickAgent;
        private AiMovement _sideKickMovement;
        private PickupHandler _sidekickPickupHandler;
        private GameObject _player;
        private DatabaseManager _dbManager;

        // Use this for initialization
        void Start()
        {
            _sideKick = GameObject.FindGameObjectWithTag(Constants.Tags.SideKick);
            _sideKickAgent = _sideKick.GetComponent<NavMeshAgent>();
            _sideKickMovement = _sideKick.GetComponent<AiMovement>();
            _player = GameObject.FindGameObjectWithTag(Constants.Tags.Player);
            _sidekickPickupHandler = _sideKick.GetComponent<PickupHandler>();

            var db = GameObject.FindGameObjectWithTag(Constants.Tags.DatabaseManager);
            if (db != null)
                _dbManager = db.GetComponent<DatabaseManager>();
            else
                Debug.Log("No dbmanager in scene!! - Problem?");

        }

        #endregion

        public void ExecuteAction(int i)
        {
            switch (i)
            {
                case 0:
                    _sideKickMovement.AssignNewState(new GoSomewhereAndWaitState(_sideKickAgent,
                        _player.transform.position));
                    return;
                case 1:
                    _sideKickMovement.AssignNewState(new WaitState(_sideKickAgent));
                    return;
                case 2:
                    _sideKickMovement.AssignNewState(new InteractWithNearestState(_sideKickAgent, Constants.Tags.Lever,
                        _sidekickPickupHandler.CurrentPickup));
                    return;
                case 3:
                    _sideKickMovement.AssignNewState(new PickupItemState(_sideKickAgent, Constants.Tags.Stick));
                    return;
                case 4:
                    _sideKickMovement.AssignNewState(new InteractWithNearestState(_sideKickAgent, Constants.Tags.Brazier,
                        _sidekickPickupHandler.CurrentPickup));
                    return;
                case 5:
                    _sideKickMovement.AssignNewState(new TradeState(_sideKickAgent, _player.GetComponent<NavMeshAgent>()));
                    return;
                case 6:
                    _sideKickMovement.AssignNewState(new PickupItemState(_sideKickAgent, Constants.Tags.Bucket));
                    return;
                case 7:
                    _sideKickMovement.AssignNewState(new InteractWithNearestState(_sideKickAgent, Constants.Tags.Pool,
                        _sidekickPickupHandler.CurrentPickup));
                    return;
                case 8:
                    _sideKickMovement.AssignNewState(new InteractWithNearestState(_sideKickAgent, Constants.Tags.Font,
                        _sidekickPickupHandler.CurrentPickup));
                    return;
                case 9:
                    _sideKickMovement.AssignNewState(new PickupItemState(_sideKickAgent, Constants.Tags.Key));
                    return;
                case 10:
                    _sideKickMovement.AssignNewState(new InteractWithNearestState(_sideKickAgent, Constants.Tags.Keyhole,
                        _sidekickPickupHandler.CurrentPickup));
                    return;
            }
        }
    }
}


text:
import matplotlib
import numpy as np
import matplotlib.pyplot as pp
import math
import scipy as scp
import time
import datetime

import gspread
from oauth2client.service_account import ServiceAccountCredentials

import sys
import schedule
import os, os.path

import csv

class Cnt_Lines:
    def __init__(self, paths):
	self.paths = paths
	today = datetime.datetime.now()
	self.day = today.day
	self.month = today.month
	self.year = today.year
	self.lines = 0

    def count_lines(self):
	for path_code in self.paths:
            for path,dirs,fs in os.walk(path_code):
		for f in fs:
	            if f.lower().endswith('.py') or f.lower().endswith('.sh') or f.lower().endswith('.launch') or f.lower().endswith('.c') or f.lower().endswith('.cpp') or f.lower().endswith('.h') or f.lower().endswith('.m'):
		        full_path  = path + '/' + f
			if os.path.isfile(full_path):
			    with open(full_path) as f:
				self.lines = self.lines + sum(1 for _ in f if _.rstrip())

    def return_lines(self):
	return self.lines

    def return_date(self):
	return self.month, self.day, self.year

def run_algorithm(path_to_code):
    code = Cnt_Lines(path_to_code)
    code.count_lines()
    lines_today = code.return_lines()
    today_month, today_day, today_year = code.return_date()
    lines_data = [today_month, today_day, today_year, lines_today]

    save_data_to_google_spreadsheet(lines_data)

def save_data_to_google_spreadsheet(lines_data):
    scope = ['https://spreadsheets.google.com/feeds']
    credentials = ServiceAccountCredentials.from_json_keyfile_name('/home/tapo/git/project lines code-85f392792e73.json', scope)
    gc = gspread.authorize(credentials)
    wks = gc.open("lines_of_code").sheet1

    data = wks.get_all_values()
    data_arr_prev = np.array(data)
    rows_prev, cols_prev = np.shape(data_arr_prev)
    if rows_prev <= 2:
        new_data = [str(lines_data[0])+'/'+str(lines_data[1])+'/'+str(lines_data[2]),str(0),str(lines_data[3])]
    else:
        prev_lines = data_arr_prev[1][cols_prev-1]
        new_data = [str(lines_data[0])+'/'+str(lines_data[1])+'/'+str(lines_data[2]),str(float(lines_data[3])-float(prev_lines)), str(lines_data[3])]
    wks.insert_row(new_data,2)

if __name__ == '__main__':

    path_to_git_code1 = '/home/tapo/git/hrl-haptic-manip-dev/sandbox_tapo_darpa_m3/'
    path_to_git_code2 = '/home/tapo/git/projects_in_c_cpp/'
    path_to_git_code3 = '/home/tapo/git/projects_in_matlab/'
    path_to_git_code4 = '/home/tapo/git/projects_in_python/'
    path_to_git_code5 = '/home/tapo/git/pyFunda/'
    path_to_svn_robot1_code = '/home/tapo/svn/robot1/usr/tapo/'
    path_to_svn_robot1_data_code = '/home/tapo/svn/robot1_data/usr/tapo/data_code/'
    path_to_pr_code = '/home/tapo/my-workspace/src/'
    path_to_account_setup_code = '/home/tapo/git/shells_aliases/'
    path_to_dropbox_code='/home/tapo/Dropbox/Personal/patrol/'
    #path_to_code = [path_to_git_code1, path_to_git_code2, path_to_git_code3, path_to_git_code4, path_to_git_code5, path_to_svn_robot1_code, path_to_svn_robot1_data_code, path_to_dropbox_code]
    path_to_code = [path_to_git_code2, path_to_git_code3, path_to_git_code4, path_to_git_code5, path_to_pr_code, path_to_account_setup_code, path_to_dropbox_code]

    schedule.every().day.at("23:59").do(run_algorithm, path_to_code)

    while True:
        schedule.run_pending()
        time.sleep(1)


text:
package edu.tamu.tcat.dex.importer;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Stack;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.lang.StringEscapeUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import edu.tamu.tcat.dex.importer.model.ExtractImportDTO;
import edu.tamu.tcat.dex.importer.model.ManuscriptImportDTO;

class ManuscriptHandler extends DefaultHandler
{
   private static final Logger logger = Logger.getLogger(PeopleAndPlaysHandler.class.getName());

   private static class XmlStringBuilder
   {
      private StringBuilder sb;

      public XmlStringBuilder()
      {
         sb = new StringBuilder();
         sb.append("<?xml version=\"1.0\"?>");
      }

      public void startTag(String qName, Attributes attributes)
      {
         // write tag as string
         sb.append('<')
            .append(qName);

         int numAttributes = attributes.getLength();
         for (int i = 0; i < numAttributes; i++)
         {
            String attrName = attributes.getQName(i);
            String attrValue = attributes.getValue(i);

            sb.append(' ').append(attrName).append("=\"").append(attrValue).append('"');
         }

         sb.append('>');
      }

      public void endTag(String qName)
      {
         sb.append("</").append(qName).append('>');
      }

      public void text(String value)
      {
         String escapedValue = StringEscapeUtils.escapeXml(value);
         sb.append(escapedValue);
      }

      @Override
      public String toString()
      {
         return sb.toString();
      }
   }

   private Stack<String> elementStack;
   private Stack<Object> objectStack;

   private boolean rawMode;
   private int extractNumber;
   private String currentFolioIdent;

   private ManuscriptImportDTO manuscript;

   /**
    * Set to {@code false} when the current {@code
} element does not represent a dramatic
    * extract, but, for example, a heading.
    */
   private boolean inExtractDiv;    // FIXME does not get set to false when no-longer in extract div

   public ManuscriptImportDTO getManuscript()
   {
      return manuscript;
   }

   @Override
   public void startDocument() throws SAXException
   {
      elementStack = new Stack<>();
      objectStack = new Stack<>();

      manuscript = new ManuscriptImportDTO();

      currentFolioIdent = null;
      extractNumber = 0;
      rawMode = false;
   }

   @Override
   public void endDocument() throws SAXException
   {
      assert elementStack.empty() : "Leftover elements in element stack";
      assert objectStack.empty() : "Leftover objects in object stack";
   }

   @Override
   public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException
   {
      if (rawMode)
      {
         XmlStringBuilder xsb = (XmlStringBuilder)objectStack.peek();
         xsb.startTag(qName, attributes);
      }

      elementStack.push(qName);

      if (qName.equals("div"))
      {
         inExtractDiv = "extract".equals(attributes.getValue("type"));
         if (inExtractDiv)
            handleExtractDiv(qName, attributes);
      }
      else if (qName.equals("sp") && isParentElement("div") && inExtractDiv)
      {
         handleSpeakerStartElement(attributes);
      }
      else if (qName.equals("pb"))
      {
         currentFolioIdent = attributes.getValue("n");
      }
      else if (qName.equals("graphic") && isParentElement("facsimile"))
      {
         try
         {
            // append facsimile link to list of links
            URI target = new URI(attributes.getValue("url"));

            // HACK HACK HACK comma-separated list of HTML links‽‽‽
            if (!manuscript.links.isEmpty())
            {
               manuscript.links += ", ";
            }
            manuscript.links += "Facsimile";
         }
         catch (URISyntaxException e) {
            logger.log(Level.WARNING, "malformed URI in link attribute", e);
         }
      }
      else if (qName.equals("bibl") && isParentElement("listBibl"))
      {
         // push link title
         objectStack.push(attributes.getValue("type"));
      }
      else if (qName.equals("link") && isParentElement("bibl"))
      {
         // push link target
         URI target = null;
         try
         {
            target = new URI(attributes.getValue("target"));
         }
         catch (URISyntaxException e)
         {
            logger.log(Level.WARNING, "malformed URI in link attribute", e);
         }
         objectStack.push(target);
      }
   }

   private void handleSpeakerStartElement(Attributes attributes)
   {
      String who = attributes.getValue("who");
      if (who != null)
      {
         String[] speakerRefs = who.trim().split("\\s+");
         for (String ref : speakerRefs)
         {
            String speakerId = ref.substring(ref.indexOf('#') + 1);

            ExtractImportDTO extract = (ExtractImportDTO)objectStack.get(objectStack.size() - 2);
            extract.speakerIds.add(speakerId);
         }
      }
   }

   private void handleExtractDiv(String qName, Attributes attributes)
   {
      ExtractImportDTO extract = new ExtractImportDTO();
      extract.id = UUID.randomUUID().toString();
      extract.msIndex = extractNumber++;

      if (currentFolioIdent != null) {
         extract.folioIdent = currentFolioIdent;
      }

      // inherit manuscript author by default
      // TODO: parse per-extract authors
      extract.author = manuscript.author;

      extract.sourceRef = attributes.getValue("n");

      manuscript.extracts.add(extract);

      String corresp = attributes.getValue("corresp");
      if (corresp != null)
      {
         extract.sourceId = corresp.substring(corresp.indexOf('#') + 1);
      }

      objectStack.push(extract);

      XmlStringBuilder xsb = new XmlStringBuilder();
      xsb.startTag(qName, attributes);
      rawMode = true;
      objectStack.push(xsb);
   }

   @Override
   public void endElement(String uri, String localName, String qName) throws SAXException
   {
      // just finished dramatic extract definition
      if (qName.equals("div") && inExtractDiv)
      {
         XmlStringBuilder xsb = (XmlStringBuilder)objectStack.pop();
         xsb.endTag("div");

         ExtractImportDTO extract = (ExtractImportDTO)objectStack.pop();

         // parse TEI XML string into W3C DOM
         extract.teiContent = xsb.toString().trim();
         inExtractDiv = false;
         rawMode = false;
      }
      else if (qName.equals("bibl") && isParentElement("listBibl"))
      {
         // append link to manuscript list of links
         URI target = (URI)objectStack.pop();
         String title = (String)objectStack.pop();

         if (target != null && title != null && !title.isEmpty())
         {
            // HACK HACK HACK comma-separated list of HTML links‽‽‽
            if (manuscript.links == null)
            {
               manuscript.links = "";
            }
            else if (!manuscript.links.isEmpty())
            {
               manuscript.links += ", ";
            }
            manuscript.links += "" + title + "";
         }
      }

      elementStack.pop();

      if (rawMode)
      {
         XmlStringBuilder xsb = (XmlStringBuilder)objectStack.peek();
         xsb.endTag(qName);
      }
   }

   @Override
   public void characters(char[] ch, int start, int length) throws SAXException
   {
      String value = new String(ch, start, length).replaceAll("\\s+", " ");

      if (rawMode)
      {
         XmlStringBuilder xsb = (XmlStringBuilder)objectStack.peek();
         xsb.text(value);
      }
      else
      {
         if (isCurrentElement("title") && isParentElement("titleStmt"))
         {
            manuscript.title = value.trim();
         }
         else if (isCurrentElement("persName") && isParentElement("author"))
         {
            manuscript.author = value.trim();
         }
      }
   }

   private boolean isCurrentElement(String qName)
   {
      return !elementStack.empty() && elementStack.peek().equals(qName);
   }

   private boolean isParentElement(String qName)
   {
      return elementStack.size() > 2 && elementStack.get(elementStack.size() - 2).equals(qName);
   }
}