text:
'use strict';
/**
 * Created by Alex Levshin on 27/5/16.
 */
var _ = require('lodash');
var moment = require('moment');
var authenticationSupervisorController = require('./supervisor/authentication-controller')();
var paymentSupervisorController = require('./supervisor/payment-controller')();
var errorSupervisorController = require('./supervisor/error-controller')();
var protocol = rootRequire('shared/protocols/v1/restapi-sv.module').OPERATIONS;

var RestApiPaymentController = function (socket) {
    var _apiFullPath;
    var ResourceName = 'payments';

    function _authenticateByEmail(req, res, next) {
        var data = {};
        data.email = req.authorization.basic.username;
        data.password = req.authorization.basic.password;
        authenticationSupervisorController.authenticateByEmail(data, function (err, account) {
            if (err) {
                next(err);
            } else if (!account) {
                next(errorSupervisorController.createInvalidCredentialsError());
            } else if (account.removed) {
                next(errorSupervisorController.createAccountRemovedError());
            } else {
                req.accountId = account._id;
                next();
            }
        });
    }

    // External API
    this.init = function (server, apiFullPath, subVersion) {
        _apiFullPath = apiFullPath;

        var dateWrapper = moment(new Date(subVersion));
        if (dateWrapper.isValid()) {
            subVersion = dateWrapper.format('YYYY.M.D');
        }

        // Retrieves the all transactions
        // Retrieve the all transactions mentioning the word 'return' (Filtering & sorting & searching)
        server.get({path: apiFullPath + 'payments', version: subVersion}, _authenticateByEmail, this.getAll);

        // Retrieves a specific payment transaction #id
        server.get({path: apiFullPath + 'payments/:id', version: subVersion}, _authenticateByEmail, this.getById);

        // Creates a new payment transaction (for example, buy a workty)
        server.post({path: apiFullPath + 'payments', version: subVersion}, _authenticateByEmail, this.add);

        // Updates payment transaction #id
        server.put({path: apiFullPath + 'payments/:id', version: subVersion}, _authenticateByEmail, this.update);

        // Deletes payment transaction #id
        server.del({path: apiFullPath + 'payments/:id', version: subVersion}, _authenticateByEmail, this.del);
    };

    // apidoc engine
    /**
     * @api {get} /payments Get all payments
     * @apiVersion 1.0.0
     * @apiName GetPayments
     * @apiGroup Payments
     *
     * @apiPermission View
     *
     * @apiHeader {String} [accept-version] The subversion value
     * @apiHeader {String} useremail:userpassword The user email and password values for authorization
     * @apiParam {Boolean=true,false} [pretty]  The prettify flag for output result
     * @apiParam {String[]} [sort]    The list of field names from payment model separated by comma that used for sorting
     * @apiParam {String[]} [fields]  The list of field names from payment model separated by comma that should be included in output result
     * @apiParam {Number}  [page_num=1] The page number that used as a first for pagination
     * @apiParam {Number}  [per_page=10] The number of workflows to send for pagination
     * @apiParam {Number}  [count] The number of sent payments
     *
     * @apiExample {curl} Example usage:
     *  curl -k -v -u 'youremail@mail.com':'userpassword' -H 'accept-version: 2016.3.1' https://127.0.0.1:9999/api/v1/payments?pretty=true&sort=created
     *
     * @apiSuccess (Success 200) {Object[]} payments The array of payments for current account. It can be empty
     *
     * @apiSuccessExample {json} 200 OK
     *      HTTP/1.1 200 OK
     *      [
     *          {
     *               "id": 54688a597129c4c6419c4f76,
     *               "accountId": 54688a597129c4c6419c4f11,
     *               "worktyId": 54688a597129c4c6419c4f22,
     *               "msg": "payment for generic workty",
     *               "created": "2014-11-23T11:45:00.000Z"
     *          },
     *          {
     *               "id": 54688a597129c4c6419c4f77,
     *               "accountId": 54688a597129c4c6419c4f11,
     *               "worktyId": 54688a597129c4c6419c4f23,
     *               "msg": "payment for encrypt pdf file workty",
     *               "created": "2014-11-23T11:45:00.000Z"
     *          }
     *      ]
     * @apiSuccessExample {json} 200 OK
     *      HTTP/1.1 200 OK
     *      [
     *      ]
     *
     * @apiError (Error 5xx) {500} OPERATION_FORBIDDEN Operation is forbidden
     * @apiError (Error 5xx) {500} UNEXPECTED Unexpected error on server side
     * @apiError (Error 5xx) {500} ACCOUNT_REMOVED The account was removed
     * @apiError (Error 4xx) {401} INVALID_CREDENTIALS Invalid credentials
     * @apiErrorExample {json} 500 OPERATION_FORBIDDEN
     *     HTTP/1.1 500 InternalError
     *     {
     *          error: {
     *              code: 13,
     *              error_link: https://127.0.0.1:9999/api/v1/13,
     *              message: 'The operation is forbidden'
     *          }
     *     }
     *
     * @apiErrorExample {json} 500 UNEXPECTED
     *     HTTP/1.1 500 InternalError
     *     {
     *          error: {
     *              code: 1,
     *              error_link: https://127.0.0.1:9999/api/v1/1,
     *              message: 'Unexpected error, please check request parameters or contact with our support service'
     *          }
     *     }
     * @apiErrorExample {json} 500 ACCOUNT_REMOVED
     *     HTTP/1.1 500 InternalError
     *     {
     *          error: {
     *              code: 14,
     *              error_link: https://127.0.0.1:9999/api/v1/14,
     *              message: 'The account was removed. Please recover it'
     *          }
     *     }
     * @apiErrorExample {json} 401 INVALID_CREDENTIALS
     *     HTTP/1.1 401 InvalidCredentials
     *     {
     *          error: {
     *              code: '',
     *              error_link: https://127.0.0.1:9999/api/v1/401
     *          }
     *     }
     */
    this.getAll = function (req, res, next) {
        var data = {};
        data.accountId = req.accountId;
        data.permissionName = protocol[ResourceName].REFRESH_ALL.permissionName;
        data.resourceName = ResourceName;

        authenticationSupervisorController.isAclPermissionAllowed(data, function _onOperationAllowed(err, permissionsAllowed) {
            if (err) {
                next(errorSupervisorController.createOperationForbiddenError({err: err, inputParameters: req.params}));
            } else {
                let inputData = {};
                inputData.accountId = req.accountId;
                authenticationSupervisorController.hasAccountAdminAclRole(inputData, function _onAccountAdminAclRoleReturned(err, hasRole) {
                    if (err) {
                        next(errorSupervisorController.createOperationForbiddenError({
                            err: err,
                            inputParameters: req.params
                        }));
                    } else {
                        var params = req.params;
                        params.accountId = req.accountId;
                        params.hasAdminRole = hasRole;
                        //console.log('[' + new Date() + ']' + ' get all payment transactions: ' + JSON.stringify(req.params));

                        paymentSupervisorController.getAll(params, function _onAllPaymentTransactionsReturned(err, paymentTransactions) {
                            if (err) {
                                next(err);
                            } else {
                                if (params.count && params.count === 'true') {
                                    res.header('Records-count', paymentTransactions ? paymentTransactions.length : 0);
                                }

                                res.send(paymentTransactions);
                                next();
                            }
                        });
                    }
                });
            }
        });
    };

    // apidoc engine
    /**
     * @api {get} /payments/:id Get payment by id
     * @apiVersion 1.0.0
     * @apiName GetPayment
     * @apiGroup Payments
     *
     * @apiPermission View
     *
     * @apiHeader {String} [accept-version] The subversion value
     * @apiHeader {String} useremail:userpassword The user email and password values for authorization
     * @apiParam {Boolean=true,false} [pretty]  The prettify flag for output result
     * @apiParam {String[]} [fields]  The list of field names from payment model separated by comma that should be included in output result
     * @apiParam {Number}  [count] The number of sent payments
     *
     * @apiExample {curl} Example usage:
     *  curl -k -v -u 'youremail@mail.com':'userpassword' https://127.0.0.1:9999/api/v1/payments/547b689eba9d33302c164b6e
     *
     * @apiSuccess (Success 200) {Object} payment The payment. It can be empty
     *
     * @apiSuccessExample {json} 200 OK
     *      HTTP/1.1 200 OK
     *      {
     *           "id": 547b689eba9d33302c164b6e,
     *           "accountId": 54688a597129c4c6419c4f11,
     *           "worktyId": 54688a597129c4c6419c4f22,
     *           "msg": "payment for generic workty",
     *           "created": "2014-11-23T11:45:00.000Z"
     *      }
     * @apiSuccessExample {json} 200 OK
     *      HTTP/1.1 200 OK
     *      {
     *      }
     *
     * @apiError (Error 5xx) {500} OPERATION_FORBIDDEN Operation is forbidden
     * @apiError (Error 5xx) {500} UNEXPECTED Unexpected error on server side
     * @apiError (Error 5xx) {500} ACCOUNT_REMOVED The account was removed
     * @apiError (Error 4xx) {401} INVALID_CREDENTIALS Invalid credentials
     * @apiErrorExample {json} 500 OPERATION_FORBIDDEN
     *     HTTP/1.1 500 InternalError
     *     {
     *          error: {
     *              code: 13,
     *              error_link: https://127.0.0.1:9999/api/v1/13,
     *              message: 'The operation is forbidden'
     *          }
     *     }
     *
     * @apiErrorExample {json} 500 UNEXPECTED
     *     HTTP/1.1 500 InternalError
     *     {
     *          error: {
     *              code: 1,
     *              error_link: https://127.0.0.1:9999/api/v1/1,
     *              message: 'Unexpected error, please check request parameters or contact with our support service'
     *          }
     *     }
     * @apiErrorExample {json} 500 ACCOUNT_REMOVED
     *     HTTP/1.1 500 InternalError
     *     {
     *          error: {
     *              code: 14,
     *              error_link: https://127.0.0.1:9999/api/v1/14,
     *              message: 'The account was removed. Please recover it'
     *          }
     *     }
     * @apiErrorExample {json} 401 INVALID_CREDENTIALS
     *     HTTP/1.1 401 InvalidCredentials
     *     {
     *          error: {
     *              code: '',
     *              error_link: https://127.0.0.1:9999/api/v1/401
     *          }
     *     }
     */
    this.getById = function (req, res, next) {
        var data = {};
        data.accountId = req.accountId;
        data.permissionName = protocol[ResourceName].REFRESH.permissionName;
        data.resourceName = ResourceName;

        authenticationSupervisorController.isAclPermissionAllowed(data, function _onOperationAllowed(err, permissionsAllowed) {
            if (err) {
                next(errorSupervisorController.createOperationForbiddenError({err: err, inputParameters: req.params}));
            } else {
                let inputData = {};
                inputData.accountId = req.accountId;
                authenticationSupervisorController.hasAccountAdminAclRole(inputData, function _onAccountAdminAclRoleReturned(err, hasRole) {
                    if (err) {
                        next(errorSupervisorController.createOperationForbiddenError({err: err, inputParameters: req.params}));
                    } else {
                        var params = req.params;
                        params.accountId = req.accountId;
                        params.hasAdminRole = hasRole;
                        paymentSupervisorController.getById(params, function _onPaymentTransactionReturned(err, paymentTransaction) {
                            if (err) {
                                next(err);
                            } else {
                                if (params.count && params.count === 'true') {
                                    res.header('Records-count', paymentTransaction ? 1 : 0);
                                }

                                res.send(paymentTransaction);
                                next();
                            }
                        });
                    }
                });
            }
        });
    };

    // apidoc engine
    /**
     * @api {post} /payments Add the new payment
     * @apiVersion 1.0.0
     * @apiName AddPayment
     * @apiGroup Payments
     *
     * @apiPermission Create
     *
     * @apiHeader {String} [accept-version] The subversion value
     * @apiHeader {String} Content-type application/json
     * @apiHeader {String} useremail:userpassword The user email and password values for authorization
     *
     * @apiExample {curl} Example usage:
     * curl -u 'youremail@mail.com':'userpassword' -H 'Content-type: application/json' --data '{ "worktyId": "545f95ee2f82bdb917ad6f81" }' -k -v https://127.0.0.1:9999/api/v1/payments
     *
     * @apiSuccess (Success 201) {Object} payment The new payment
     *
     * @apiSuccessExample {json} 201 CREATED
     *     HTTP/1.1 201 Created
     *     {
     *           "id": 547b689eba9d33302c164b50,
     *           "accountId": 54688a597129c4c6419c4f11,
     *           "worktyId": "545f95ee2f82bdb917ad6f81,
     *           "msg": "payment for generic workty",
     *           "created": "2014-11-23T11:45:00.000Z"
     *     }
     *
     * @apiError (Error 5xx) {500} OPERATION_FORBIDDEN Operation is forbidden
     * @apiError (Error 5xx) {500} UNEXPECTED Unexpected error on server side
     * @apiError (Error 5xx) {500} ENT_NOT_FOUND The entity was not found
     * @apiError (Error 5xx) {500} ENT_NOT_SAVED The entity was not saved
     * @apiError (Error 5xx) {500} ACCOUNT_REMOVED The account was removed
     * @apiError (Error 4xx) {400} INVALID_CONTENT The input json value is not correct
     * @apiError (Error 4xx) {401} INVALID_CREDENTIALS Invalid credentials
     * @apiError (Error 4xx) {409} VALIDATION_ERR Validation error
     * @apiErrorExample {json} 500 OPERATION_FORBIDDEN
     *      HTTP/1.1 500 InternalError
     *      {
     *          error: {
     *              code: 13,
     *              error_link: https://127.0.0.1:9999/api/v1/13,
     *              message: 'The operation is forbidden'
     *          }
     *      }
     * @apiErrorExample {json} 500 UNEXPECTED
     *      HTTP/1.1 500 InternalError
     *      {
     *          error: {
     *              code: 1,
     *              error_link: https://127.0.0.1:9999/api/v1/1,
     *              message: 'Unexpected error, please check request parameters or contact with our support service'
     *          }
     *      }
     * @apiErrorExample {json} 500 ENT_NOT_FOUND
     *      HTTP/1.1 500 InternalError
     *      {
     *          error: {
     *              code: 2,
     *              error_link: https://127.0.0.1:9999/api/v1/2,
     *              message: 'The entity was not found'
     *          }
     *      }
     * @apiErrorExample {json} 500 ENT_NOT_SAVED
     *      HTTP/1.1 500 InternalError
     *      {
     *          error: {
     *              code: 5,
     *              error_link: https://127.0.0.1:9999/api/v1/5,
     *              message: 'The entity was not saved'
     *          }
     *      }
     * @apiErrorExample {json} 500 ACCOUNT_REMOVED
     *     HTTP/1.1 500 InternalError
     *     {
     *          error: {
     *              code: 14,
     *              error_link: https://127.0.0.1:9999/api/v1/14,
     *              message: 'The account was removed. Please recover it'
     *          }
     *     }
     * @apiErrorExample {json} 400 INVALID_CONTENT
     *      HTTP/1.1 400 InvalidContent
     *      {
     *          error: {
     *              code: '',
     *              error_link: https://127.0.0.1:9999/api/v1/400
     *          }
     *      }
     * @apiErrorExample {json} 401 INVALID_CREDENTIALS
     *     HTTP/1.1 401 InvalidCredentials
     *     {
     *          error: {
     *              code: '',
     *              error_link: https://127.0.0.1:9999/api/v1/401
     *          }
     *     }
     * @apiErrorExample {json} 409 VALIDATION_ERR
     *      HTTP/1.1 409 MissingParameter
     *      {
     *          error: {
     *              code: '',
     *              error_link: https://127.0.0.1:9999/api/v1/409,
     *              message: 'Validation error'
     *              errors: [
     *                  message: 'Path `worktyId` is required.'
     *              ]
     *          }
     *      }
     */
    this.add = function (req, res, next) {
        if (!req.is('application/json') && !req.is('json')) {
            // send 400
            return next(errorSupervisorController.createInvalidContentError({inputParameters: req.params}));
        }

        var data = {};
        data.accountId = req.accountId;
        data.permissionName = protocol[ResourceName].ADD.permissionName;
        data.resourceName = ResourceName;

        authenticationSupervisorController.isAclPermissionAllowed(data, function _onOperationAllowed(err, permissionsAllowed) {
            if (err) {
                next(errorSupervisorController.createOperationForbiddenError({err: err, inputParameters: req.params}));
            } else {
                var params = req.params;
                params.accountId = req.accountId;
                //console.log('[' + new Date() + ']' + ' add payment transaction: ' + JSON.stringify(req.params));

                paymentSupervisorController.add(params, function _onPaymentTransactionAdded(err, result) {
                    if (err) {
                        next(err);
                    } else {
                        // Add transaction (send to supervisor)
                        var inputData = {paymentTransaction: result.paymentTransaction, workty: result.workty, accountId: params.accountId};
                        socket.emit(protocol[ResourceName].ADD.name, inputData);

                        res.header('Location', errorSupervisorController.formatLocationHeader(_apiFullPath + 'payments/' + result.paymentTransaction._id));
                        res.send(201, result.paymentTransaction);
                        next();
                    }
                });
            }
        });
    };

    // apidoc engine
    /**
     * @api {put} /payments/:id Update the existing payment
     * @apiVersion 1.0.0
     * @apiName UpdatePayment
     * @apiGroup Payments
     *
     * @apiPermission Update
     *
     * @apiHeader {String} [accept-version] The subversion value
     * @apiHeader {String} Content-type application/json
     * @apiHeader {String} useremail:userpassword The user email and password values for authorization
     *
     * @apiExample {curl} Example usage:
     *  curl -X PUT -u 'youremail@mail.com':'userpassword' -H 'Content-type: application/json' --data '{ "msg": "another message" }' -k -v https://127.0.0.1:9999/api/v1/payments/545f95ee2f82bdb917ad6f81
     *
     * @apiSuccess {Object} payment The updated payment
     *
     * @apiSuccessExample {json} 200 OK
     *     HTTP/1.1 200 OK
     *     {
     *           "id": 545f95ee2f82bdb917ad6f81,
     *           "accountId": 54688a597129c4c6419c4f11,
     *           "worktyId": "545f95ee2f82bdb917ad6f81,
     *           "msg": "another message",
     *           "created": "2014-11-23T11:45:00.000Z"
     *     }
     *
     * @apiError (Error 5xx) {500} OPERATION_FORBIDDEN Operation is forbidden
     * @apiError (Error 5xx) {500} UNEXPECTED Unexpected error on server side
     * @apiError (Error 5xx) {500} ENT_NOT_FOUND The entity was not found
     * @apiError (Error 5xx) {500} ENT_NOT_UPDATED The entity was not updated
     * @apiError (Error 5xx) {500} ACCOUNT_REMOVED The account was removed
     * @apiError (Error 4xx) {400} INVALID_CONTENT The input json value is not correct
     * @apiError (Error 4xx) {400} BAD_DIGEST No data to update
     * @apiError (Error 4xx) {401} INVALID_CREDENTIALS Invalid credentials
     * @apiErrorExample {json} 500 OPERATION_FORBIDDEN
     *      HTTP/1.1 500 InternalError
     *      {
     *          error: {
     *              code: 13,
     *              error_link: https://127.0.0.1:9999/api/v1/13,
     *              message: 'The operation is forbidden'
     *          }
     *      }
     * @apiErrorExample {json} 500 UNEXPECTED
     *      HTTP/1.1 500 InternalError
     *      {
     *          error: {
     *              code: 1,
     *              error_link: https://127.0.0.1:9999/api/v1/1,
     *              message: 'Unexpected error, please check request parameters or contact with our support service'
     *          }
     *      }
     * @apiErrorExample {json} 500 ENT_NOT_FOUND
     *      HTTP/1.1 500 InternalError
     *      {
     *          error: {
     *              code: 2,
     *              error_link: https://127.0.0.1:9999/api/v1/2,
     *              message: 'The entity was not found'
     *          }
     *      }
     * @apiErrorExample {json} 500 ENT_NOT_UPDATED
     *      HTTP/1.1 500 InternalError
     *      {
     *          error: {
     *              code: 3,
     *              error_link: https://127.0.0.1:9999/api/v1/3,
     *              message: 'The entity was not updated'
     *          }
     *      }
     * @apiErrorExample {json} 500 ACCOUNT_REMOVED
     *     HTTP/1.1 500 InternalError
     *     {
     *          error: {
     *              code: 14,
     *              error_link: https://127.0.0.1:9999/api/v1/14,
     *              message: 'The account was removed. Please recover it'
     *          }
     *     }
     * @apiErrorExample {json} 400 INVALID_CONTENT
     *      HTTP/1.1 400 InvalidContent
     *      {
     *          error: {
     *              code: '',
     *              error_link: https://127.0.0.1:9999/api/v1/400
     *          }
     *      }
     * @apiErrorExample {json} 400 BAD_DIGEST
     *      HTTP/1.1 400 BadDigest
     *      {
     *          error: {
     *              code: '',
     *              error_link: https://127.0.0.1:9999/api/v1/400
     *          }
     *      }
     * @apiErrorExample {json} 401 INVALID_CREDENTIALS
     *     HTTP/1.1 401 InvalidCredentials
     *     {
     *          error: {
     *              code: '',
     *              error_link: https://127.0.0.1:9999/api/v1/401
     *          }
     *     }
     */
    this.update = function (req, res, next) {
        if (!req.is('application/json') && !req.is('json')) {
            // send 400
            return next(errorSupervisorController.createInvalidContentError({inputParameters: req.params}));
        }

        var data = {};
        data.accountId = req.accountId;
        data.permissionName = protocol[ResourceName].UPD.permissionName;
        data.resourceName = ResourceName;

        authenticationSupervisorController.isAclPermissionAllowed(data, function _onOperationAllowed(err, permissionsAllowed) {
            if (err) {
                next(errorSupervisorController.createOperationForbiddenError({err: err, inputParameters: req.params}));
            } else {
                let inputData = {};
                inputData.accountId = req.accountId;
                authenticationSupervisorController.hasAccountAdminAclRole(inputData, function _onAccountAdminAclRoleReturned(err, hasRole) {
                    if (err) {
                        next(errorSupervisorController.createOperationForbiddenError({err: err, inputParameters: req.params}));
                    } else {
                        var params = req.params;
                        params.accountId = req.accountId;
                        params.hasAdminRole = hasRole;
                        //console.log('[' + new Date() + ']' + ' update payment transaction: ' + JSON.stringify(req.params));

                        paymentSupervisorController.update(params, function _onPaymentTransactionUpdated(err, updatedPaymentTransaction) {
                            if (err) {
                                next(err);
                            } else {
                                // Update payment transaction (send to supervisor)
                                var inputData = {
                                    paymentTransaction: updatedPaymentTransaction,
                                    accountId: params.accountId
                                };
                                socket.emit(protocol[ResourceName].UPD.name, inputData);

                                // send 200
                                res.send(updatedPaymentTransaction);
                                next();
                            }
                        });
                    }
                });
            }
        });
    };

    // apidoc engine
    /**
     * @api {delete} /payments/:id Delete the existing payment
     * @apiVersion 1.0.0
     * @apiName DeletePayment
     * @apiGroup Payments
     *
     * @apiPermission Delete
     *
     * @apiHeader {String} [accept-version] The subversion value
     * @apiHeader {String} useremail:userpassword The user email and password values for authorization
     *
     * @apiExample {curl} Example usage:
     * curl -X DELETE -u 'youremail@mail.com':'userpassword' -k -v https://127.0.0.1:9999/api/v1/payments/545f95ee2f82bdb917ad6f81
     *
     * @apiSuccess {Object} payment The empty object
     *
     * @apiSuccessExample {json} 204 NO_CONTENT
     *      HTTP/1.1 204
     *      {
     *      }
     *
     * @apiError (Error 5xx) {500} OPERATION_FORBIDDEN Operation is forbidden
     * @apiError (Error 5xx) {500} UNEXPECTED Unexpected error on server side
     * @apiError (Error 5xx) {500} ENT_NOT_FOUND The entity was not found
     * @apiError (Error 5xx) {500} ACCOUNT_REMOVED The account was removed
     * @apiError (Error 4xx) {401} INVALID_CREDENTIALS Invalid credentials
     * @apiErrorExample {json} 500 OPERATION_FORBIDDEN
     *      HTTP/1.1 500 InternalError
     *      {
     *          error: {
     *              code: 13,
     *              error_link: https://127.0.0.1:9999/api/v1/13,
     *              message: 'The operation is forbidden'
     *          }
     *      }
     * @apiErrorExample {json} 500 UNEXPECTED
     *      HTTP/1.1 500 InternalError
     *      {
     *          error: {
     *              code: 1,
     *              error_link: https://127.0.0.1:9999/api/v1/1,
     *              message: 'Unexpected error, please check request parameters or contact with our support service'
     *          }
     *      }
     * @apiErrorExample {json} 500 ENT_NOT_FOUND
     *      HTTP/1.1 500 InternalError
     *      {
     *          error: {
     *              code: 2,
     *              error_link: https://127.0.0.1:9999/api/v1/2,
     *              message: 'The entity was not found'
     *          }
     *      }
     * @apiErrorExample {json} 500 ACCOUNT_REMOVED
     *     HTTP/1.1 500 InternalError
     *     {
     *          error: {
     *              code: 14,
     *              error_link: https://127.0.0.1:9999/api/v1/14,
     *              message: 'The account was removed. Please recover it'
     *          }
     *     }
     * @apiErrorExample {json} 401 INVALID_CREDENTIALS
     *     HTTP/1.1 401 InvalidCredentials
     *     {
     *          error: {
     *              code: '',
     *              error_link: https://127.0.0.1:9999/api/v1/401
     *          }
     *     }
     */
    this.del = function (req, res, next) {
        var data = {};
        data.accountId = req.accountId;
        data.permissionName = protocol[ResourceName].DEL.permissionName;
        data.resourceName = ResourceName;

        authenticationSupervisorController.isAclPermissionAllowed(data, function _onOperationAllowed(err, permissionsAllowed) {
            if (err) {
                next(errorSupervisorController.createOperationForbiddenError({err: err, inputParameters: req.params}));
            } else {
                let inputData = {};
                inputData.accountId = req.accountId;
                authenticationSupervisorController.hasAccountAdminAclRole(inputData, function _onAccountAdminAclRoleReturned(err, hasRole) {
                    if (err) {
                        next(errorSupervisorController.createOperationForbiddenError({err: err, inputParameters: req.params}));
                    } else {
                        var params = req.params;
                        params.accountId = req.accountId;
                        params.hasAdminRole = hasRole;
                        //console.log('[' + new Date() + ']' + ' delete payment transaction: ' + JSON.stringify(req.params));

                        paymentSupervisorController.del(params, function _onPaymentTransactionDeleted(err, paymentTransaction) {
                            if (err) {
                                next(err);
                            } else {
                                // Delete workty (send to supervisor)
                                var inputData = {paymentTransaction: paymentTransaction, accountId: params.accountId};
                                socket.emit(protocol[ResourceName].DEL.name, inputData);

                                // Send 204 (No content)
                                res.header('Content-type', '');
                                res.send(204, {});
                                next();
                            }
                        });
                    }
                });
            }
        });
    };
};

module.exports = RestApiPaymentController;


text:
module.exports = angular.module('trafficOps.table.regions', [])
    .controller('TableRegionsController', require('./TableRegionsController'));

redpajama_set_name: RedPajamaGithub


text:
/*
 * Unit tests for the Expresion system
 */

#pragma once

int runExpressionTests();


text:
<?php

namespace Sylius\Bundle\AddressingBundle\Form\EventListener;

use Doctrine\Common\Persistence\ObjectRepository;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormFactoryInterface;

/**
 * This listener adds the province field to form if needed.
 *
 * @author Paweł Jędrzejewski <pjedrzejewski@diweb.pl>
 */
class BuildAddressFormListener implements EventSubscriberInterface
{
    /**
     * @var ObjectRepository
     */
    private $countryRepository;

    /**
     * Form factory.
     *
     * @var FormFactoryInterface
     */
    private $factory;

    /**
     * Constructor.
     *
     * @param ObjectRepository     $countryRepository
     * @param FormFactoryInterface $factory
     */
    public function __construct(ObjectRepository $countryRepository, FormFactoryInterface $factory)
    {
        $this->countryRepository = $countryRepository;
        $this->factory = $factory;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        return array(
            FormEvents::PRE_SET_DATA => 'preSetData',
            FormEvents::PRE_SUBMIT   => 'preBind'
        );
    }

    /**
     * Removes or adds a province field based on the country set.
     *
     * @param FormEvent $event
     */
    public function preSetData(FormEvent $event)
    {
        $address = $event->getData();
        if (null === $address) {
            return;
        }

        $country = $address->getCountry();
        if (null === $country) {
            return;
        }

        if ($country->hasProvinces()) {
            $event->getForm()->add($this->factory->createNamed('province', 'sylius_province_choice', $address->getProvince(), array(
                'country' => $country, 'auto_initialize' => false
            )));
        }
    }

    /**
     * Removes or adds a province field based on the country set on submitted form.
     *
     * @param FormEvent $event
     */
    public function preBind(FormEvent $event)
    {
        $data = $event->getData();
        if (!is_array($data) || !array_key_exists('country', $data)) {
            return;
        }

        $country = $this->countryRepository->find($data['country']);
        if (null === $country) {
            return;
        }

        if ($country->hasProvinces()) {
            $event->getForm()->add($this->factory->createNamed('province', 'sylius_province_choice', null, array(
                'country'  => $country, 'auto_initialize' => false
            )));
        }
    }
}


text:
<?php

// SonataAdminBundle:CRUD:show_percent.html.twig
return array (
);


text:
#include "hazptr.h"

namespace folly {
namespace hazptr {

FOLLY_STATIC_CTOR_PRIORITY_MAX hazptr_domain default_domain_;

hazptr_stats hazptr_stats_;

bool hazptr_tc_enabled() {
  return HAZPTR_TC;
}

bool hazptr_priv_enabled() {
  return HAZPTR_PRIV;
}

} // namespace hazptr
} // namespace folly


text:
package ec.app.gpsemantics.func;
import ec.*;
import ec.gp.*;
import ec.util.*;

/*
 * SemanticX9.java
 *
 */

/**
 * @author James McDermott
 */

public class SemanticX9 extends SemanticNode
    {
    public char value() { return 'X'; }
    public int index() { return 9; }
    }


text:
package twitchpokedex.twitch;

import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;

import twitchpokedex.logging.Logging;
import twitchpokedex.twitch.api.TwitchUser;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class TwitchAPI
{
	private static final String USER_API = "https://api.twitch.tv/kraken/users/%s";

	private static <T> T GetObject(String url, Class<T> type)
	{
		URL getRequest;
		try {
			getRequest = new URL(url);
			try (Reader reader = new InputStreamReader(getRequest.openStream())) {
				Gson gson = new GsonBuilder().create();
				T returnObject = gson.fromJson(reader, type);
				return returnObject;
			}
		} catch (Exception e) {
			Logging.GetLogger().error(e.getMessage());
			return null;
		}
	}

	/**
	 * Gets a Twitch user from the API
	 *
	 * @param username The username of the Twitch user
	 * @return The object representing the Twitch user
	 */
	public static TwitchUser GetTwitchUser(String username)
	{
		String url = String.format(USER_API, username);
		TwitchUser returnUser = GetObject(url, TwitchUser.class);

		return returnUser;
	}
}


text:
package com.amazonaws.services.securityhub.model;

import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;

/**
 *

 * A rule for redirecting requests to the website.
 *

 *
 * @see AWS API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AwsS3BucketWebsiteConfigurationRoutingRule implements Serializable, Cloneable, StructuredPojo {

    /**
     *

     * Provides the condition that must be met in order to apply the routing rule.
     *

     */
    private AwsS3BucketWebsiteConfigurationRoutingRuleCondition condition;
    /**
     *

     * Provides the rules to redirect the request if the condition in Condition is met.
     *

     */
    private AwsS3BucketWebsiteConfigurationRoutingRuleRedirect redirect;

    /**
     *

     * Provides the condition that must be met in order to apply the routing rule.
     *

     *
     * @param condition
     *        Provides the condition that must be met in order to apply the routing rule.
     */

    public void setCondition(AwsS3BucketWebsiteConfigurationRoutingRuleCondition condition) {
        this.condition = condition;
    }

    /**
     *

     * Provides the condition that must be met in order to apply the routing rule.
     *

     *
     * @return Provides the condition that must be met in order to apply the routing rule.
     */

    public AwsS3BucketWebsiteConfigurationRoutingRuleCondition getCondition() {
        return this.condition;
    }

    /**
     *

     * Provides the condition that must be met in order to apply the routing rule.
     *

     *
     * @param condition
     *        Provides the condition that must be met in order to apply the routing rule.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AwsS3BucketWebsiteConfigurationRoutingRule withCondition(AwsS3BucketWebsiteConfigurationRoutingRuleCondition condition) {
        setCondition(condition);
        return this;
    }

    /**
     *

     * Provides the rules to redirect the request if the condition in Condition is met.
     *

     *
     * @param redirect
     *        Provides the rules to redirect the request if the condition in Condition is met.
     */

    public void setRedirect(AwsS3BucketWebsiteConfigurationRoutingRuleRedirect redirect) {
        this.redirect = redirect;
    }

    /**
     *

     * Provides the rules to redirect the request if the condition in Condition is met.
     *

     *
     * @return Provides the rules to redirect the request if the condition in Condition is met.
     */

    public AwsS3BucketWebsiteConfigurationRoutingRuleRedirect getRedirect() {
        return this.redirect;
    }

    /**
     *

     * Provides the rules to redirect the request if the condition in Condition is met.
     *

     *
     * @param redirect
     *        Provides the rules to redirect the request if the condition in Condition is met.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public AwsS3BucketWebsiteConfigurationRoutingRule withRedirect(AwsS3BucketWebsiteConfigurationRoutingRuleRedirect redirect) {
        setRedirect(redirect);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getCondition() != null)
            sb.append("Condition: ").append(getCondition()).append(",");
        if (getRedirect() != null)
            sb.append("Redirect: ").append(getRedirect());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof AwsS3BucketWebsiteConfigurationRoutingRule == false)
            return false;
        AwsS3BucketWebsiteConfigurationRoutingRule other = (AwsS3BucketWebsiteConfigurationRoutingRule) obj;
        if (other.getCondition() == null ^ this.getCondition() == null)
            return false;
        if (other.getCondition() != null && other.getCondition().equals(this.getCondition()) == false)
            return false;
        if (other.getRedirect() == null ^ this.getRedirect() == null)
            return false;
        if (other.getRedirect() != null && other.getRedirect().equals(this.getRedirect()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getCondition() == null) ? 0 : getCondition().hashCode());
        hashCode = prime * hashCode + ((getRedirect() == null) ? 0 : getRedirect().hashCode());
        return hashCode;
    }

    @Override
    public AwsS3BucketWebsiteConfigurationRoutingRule clone() {
        try {
            return (AwsS3BucketWebsiteConfigurationRoutingRule) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

    @com.amazonaws.annotation.SdkInternalApi
    @Override
    public void marshall(ProtocolMarshaller protocolMarshaller) {
        com.amazonaws.services.securityhub.model.transform.AwsS3BucketWebsiteConfigurationRoutingRuleMarshaller.getInstance()
                .marshall(this, protocolMarshaller);
    }
}


text:
import numpy as np

from sklearn.metrics import euclidean_distances
from sklearn.neighbors import KNeighborsTransformer, RadiusNeighborsTransformer
from sklearn.neighbors._base import _is_sorted_by_data

def test_transformer_result():
    # Test the number of neighbors returned
    n_neighbors = 5
    n_samples_fit = 20
    n_queries = 18
    n_features = 10

    rng = np.random.RandomState(42)
    X = rng.randn(n_samples_fit, n_features)
    X2 = rng.randn(n_queries, n_features)
    radius = np.percentile(euclidean_distances(X), 10)

    # with n_neighbors
    for mode in ["distance", "connectivity"]:
        add_one = mode == "distance"
        nnt = KNeighborsTransformer(n_neighbors=n_neighbors, mode=mode)
        Xt = nnt.fit_transform(X)
        assert Xt.shape == (n_samples_fit, n_samples_fit)
        assert Xt.data.shape == (n_samples_fit * (n_neighbors + add_one),)
        assert Xt.format == "csr"
        assert _is_sorted_by_data(Xt)

        X2t = nnt.transform(X2)
        assert X2t.shape == (n_queries, n_samples_fit)
        assert X2t.data.shape == (n_queries * (n_neighbors + add_one),)
        assert X2t.format == "csr"
        assert _is_sorted_by_data(X2t)

    # with radius
    for mode in ["distance", "connectivity"]:
        add_one = mode == "distance"
        nnt = RadiusNeighborsTransformer(radius=radius, mode=mode)
        Xt = nnt.fit_transform(X)
        assert Xt.shape == (n_samples_fit, n_samples_fit)
        assert not Xt.data.shape == (n_samples_fit * (n_neighbors + add_one),)
        assert Xt.format == "csr"
        assert _is_sorted_by_data(Xt)

        X2t = nnt.transform(X2)
        assert X2t.shape == (n_queries, n_samples_fit)
        assert not X2t.data.shape == (n_queries * (n_neighbors + add_one),)
        assert X2t.format == "csr"
        assert _is_sorted_by_data(X2t)

def _has_explicit_diagonal(X):
    """Return True if the diagonal is explicitly stored"""
    X = X.tocoo()
    explicit = X.row[X.row == X.col]
    return len(explicit) == X.shape[0]

def test_explicit_diagonal():
    # Test that the diagonal is explicitly stored in the sparse graph
    n_neighbors = 5
    n_samples_fit, n_samples_transform, n_features = 20, 18, 10
    rng = np.random.RandomState(42)
    X = rng.randn(n_samples_fit, n_features)
    X2 = rng.randn(n_samples_transform, n_features)

    nnt = KNeighborsTransformer(n_neighbors=n_neighbors)
    Xt = nnt.fit_transform(X)
    assert _has_explicit_diagonal(Xt)
    assert np.all(Xt.data.reshape(n_samples_fit, n_neighbors + 1)[:, 0] == 0)

    Xt = nnt.transform(X)
    assert _has_explicit_diagonal(Xt)
    assert np.all(Xt.data.reshape(n_samples_fit, n_neighbors + 1)[:, 0] == 0)

    # Using transform on new data should not always have zero diagonal
    X2t = nnt.transform(X2)
    assert not _has_explicit_diagonal(X2t)


text:
<?php
include_once("common-header.php");
?>

Kirin Art School

Ham Eun-jung as Yoon Baek Hee

<?php
include_once("common-footer.php");
?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Classes (myorm 1.0-SNAPSHOT API)</title>
<meta name="date" content="2017-05-29">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

All Classes

BasicEntityManager

Column

Entity

EntityManager

GenerationType

Id

MappingHelper

NamedPreparedStatement

ReflectionUtil

Samples

SqlGenerator

Transient

User


text:
//-----------------------------------------------
//
//	This file is part of the Siv3D Engine.
//
//	Copyright (c) 2008-2022 Ryo Suzuki
//	Copyright (c) 2016-2022 OpenSiv3D Project
//
//	Licensed under the MIT License.
//
//-----------------------------------------------

# pragma once
# include <ThirdParty/Xoshiro-cpp/XoshiroCpp.hpp>
# include "Common.hpp"
# include "SFMT.hpp"

namespace s3d
{
	namespace PRNG
	{
		using SplitMix64			= XoshiroCpp::SplitMix64;
		using Xoshiro256Plus		= XoshiroCpp::Xoshiro256Plus;
		using Xoshiro256PlusPlus	= XoshiroCpp::Xoshiro256PlusPlus;
		using Xoshiro256StarStar	= XoshiroCpp::Xoshiro256StarStar;
		using Xoroshiro128Plus		= XoshiroCpp::Xoroshiro128Plus;
		using Xoroshiro128PlusPlus	= XoshiroCpp::Xoroshiro128PlusPlus;
		using Xoroshiro128StarStar	= XoshiroCpp::Xoroshiro128StarStar;
		using Xoshiro128Plus		= XoshiroCpp::Xoshiro128Plus;
		using Xoshiro128PlusPlus	= XoshiroCpp::Xoshiro128PlusPlus;
		using Xoshiro128StarStar	= XoshiroCpp::Xoshiro128StarStar;
	}

	using SmallRNG = PRNG::Xoshiro256PlusPlus;
}


text:
#ifndef BSON_MACROS_H
#define BSON_MACROS_H

//#if !defined(BSON_INSIDE) && !defined(BSON_COMPILATION)
//#error "Only <bson.h> can be included directly."
//#endif

#include <stdio.h>
#include <stdint.h>

#ifdef __cplusplus
#include <algorithm>
#endif

#include "bson-config.h"

#ifdef __cplusplus
#define BSON_BEGIN_DECLS extern "C" {
#define BSON_END_DECLS }
#else
#define BSON_BEGIN_DECLS
#define BSON_END_DECLS
#endif

#if defined (__GNUC__)
#define BSON_GNUC_CHECK_VERSION(major, minor) \
   ((__GNUC__ > (major)) ||                   \
    ((__GNUC__ == (major)) && (__GNUC_MINOR__ >= (minor))))
#else
#define BSON_GNUC_CHECK_VERSION(major, minor) 0
#endif

#if defined (__GNUC__)
#define BSON_GNUC_IS_VERSION(major, minor) \
   ((__GNUC__ == (major)) && (__GNUC_MINOR__ == (minor)))
#else
#define BSON_GNUC_IS_VERSION(major, minor) 0
#endif

/* Decorate public functions:
 * - if BSON_STATIC, we're compiling a program that uses libbson as a static
 *   library, don't decorate functions
 * - else if BSON_COMPILATION, we're compiling a static or shared libbson, mark
 *   public functions for export from the shared lib (which has no effect on
 *   the static lib)
 * - else, we're compiling a program that uses libbson as a shared library,
 *   mark public functions as DLL imports for Microsoft Visual C
 */

#define BSON_API
#define BSON_CALL

#define BSON_EXPORT(type) BSON_API type BSON_CALL

#define BSON_MIN(a, b) (((a) < (b)) ? (a) : (b))

#define BSON_MAX(a, b) (((a) > (b)) ? (a) : (b))

#define BSON_ABS(a) (((a) < 0) ? ((a) * -1) : (a))

#define BSON_ALIGN_OF_PTR (sizeof (void *))

#define BSON_ALIGNED_BEGIN(_N)      __attribute__((aligned(_N)))
#define BSON_ALIGNED_END(_N)

#define bson_str_empty(s) (!s[0])
#define bson_str_empty0(s) (!s || !s[0])

#define BSON_FUN_TIME   rt_time

#define BSON_FUNC   __FUNCTION__

#define BSON_ASSERT(test)                                  \
   do {                                                    \
      if (!(BSON_LIKELY (test))) {                         \
         rt_kprintf (                                      \
                  "%s:%d %s(): precondition failed: %s\n", \
                  __FILE__,                                \
                  __LINE__,                                \
                  BSON_FUNC,                               \
                  #test);                                  \
         while (1);                                         \
      }                                                    \
   } while (0)

#define BSON_STATIC_ASSERT(s) BSON_STATIC_ASSERT_ (s, __LINE__)
#define BSON_STATIC_ASSERT_JOIN(a, b) BSON_STATIC_ASSERT_JOIN2 (a, b)
#define BSON_STATIC_ASSERT_JOIN2(a, b) a##b
#define BSON_STATIC_ASSERT_(s, l)                             \
   typedef char BSON_STATIC_ASSERT_JOIN (static_assert_test_, \
                                         __LINE__)[(s) ? 1 : -1]

#define BSON_GNUC_CONST
#define BSON_GNUC_WARN_UNUSED_RESULT

#define BSON_GNUC_NULL_TERMINATED
#define BSON_GNUC_INTERNAL

#define BSON_LIKELY(v) v
#define BSON_UNLIKELY(v) v

#define BSON_GNUC_PRINTF(f, v) __attribute__ ((format (printf, f, v)))

// based on rtthread RTOS.

#define BSON_MEM_MALLOC     rt_malloc
#define BSON_MEM_CALLOC     rt_calloc
#define BSON_MEM_RELLOC     rt_realloc
#define BSON_MEM_FREE       rt_free

#define BSON_FILE_OPEN(path, mode)      open(path, mode, 0)
#define BSON_FILE_READ(fd, buf, len)    read(fd, buf, len)
#define BSON_FILE_WRITE(fd, buf, len)   write(fd, buf, len)
#define BSON_FILE_CLOSE(fd)             close(fd)

#define BSON_PRINTF         rt_kprintf

#define BSON_WORD_SIZE  32

#define BSON_INLINE   __inline

#define BSON_ENSURE_ARRAY_PARAM_SIZE(_n) static(_n)
#define BSON_TYPEOF typeof

#if BSON_GNUC_CHECK_VERSION(3, 1)
#define BSON_GNUC_DEPRECATED __attribute__ ((__deprecated__))
#else
#define BSON_GNUC_DEPRECATED
#endif

#if BSON_GNUC_CHECK_VERSION(4, 5)
#define BSON_GNUC_DEPRECATED_FOR(f) \
   __attribute__ ((deprecated ("Use " #f " instead")))
#else
#define BSON_GNUC_DEPRECATED_FOR(f) BSON_GNUC_DEPRECATED
#endif

// Song: added
struct timeval {
uint32_t tv_sec; /* seconds */
uint32_t tv_usec; /* microseconds */
};

#endif /* BSON_MACROS_H */


text:
layout: post
author: batlopez
title: "Nat's first post!"
---

Nat is an MSLS student and works at the Davis Library Research Hub. Her life revolves around her dog, Lola.


text:
require 'formula'

class Ophcrack < Formula
  homepage 'http://ophcrack.sourceforge.net/'
  url 'https://downloads.sourceforge.net/project/ophcrack/ophcrack/3.6.0/ophcrack-3.6.0.tar.bz2'
  sha1 '8e39b8c013b3f2144b23e33abeeadbb81e4120ca'

  def install
    system "./configure", "--disable-debug",
                          "--disable-gui",
                          "--prefix=#{prefix}"

    system "make"
    system "make", "-C", "src", "install"
  end
end


text:
<LINK REL="stylesheet" HREF="../static/styles.css">

<TITLE>FMOD_CODEC_READ_CALLBACK</TITLE>

Firelight Technologies FMOD Studio API

FMOD_CODEC_READ_CALLBACK

Read callback for the codec for when FMOD tries to read some data from the file to the destination format (format
specified in the open callback).

C/C++ Syntax

FMOD_RESULT F_CALLBACK FMOD_CODEC_READ_CALLBACK(
  FMOD_CODEC_STATE *codec_state,
  void *buffer,
  unsigned int samples_in,
  unsigned int *samples_out
);

Parameters

codec_state

Pointer to the codec state.  The user can use this variable to access runtime plugin specific variables and plugin writer user data.

buffer

Buffer to read PCM data to.  Note that the format of this data is the format described in FMOD_CODEC_WAVEFORMAT.

samples_in

Number of PCM samples to decode

samples_out

Number of PCM samples decoded

Return Values

If the function succeeds then the return value is FMOD_OK.

If the function fails then the return value will be one of the values defined in the FMOD_RESULT enumeration.

Remarks

If you cannot read number of samples requested, simply return FMOD_OK and give samples_out the number of samples you decoded.

Read and seek within the file using the 'fileread' and 'fileseek' members of the FMOD_CODEC codec that is passed in.

Note: DO NOT USE YOUR OWN FILESYSTEM.

The reasons for this are:

The user may have set their own file system via user filesystem callbacks.

FMOD allows file reading via disk, memory and TCP/IP.  If you use your own file routines you will lose this ability.

Remember to return FMOD_OK at the bottom of the function, or an appropriate error code from FMOD_RESULT.

See Also

FMOD_CODEC_STATE

FMOD_CODEC_DESCRIPTION

FMOD_CODEC_OPEN_CALLBACK

FMOD_CODEC_CLOSE_CALLBACK

FMOD_CODEC_GETLENGTH_CALLBACK

FMOD_CODEC_SETPOSITION_CALLBACK

FMOD_CODEC_GETPOSITION_CALLBACK

FMOD_CODEC_SOUNDCREATE_CALLBACK

Version 1.08.02 Built on Apr 14, 2016


text:
package maru.ui.test;

import junit.framework.TestCase;
import junit.framework.TestSuite;
import maru.ui.MaruUIPlugin;
import maru.ui.model.UiModel;

public class UiModelPlatformTests extends TestCase
{
    private UiModel uiModel;

    public static void main(String[] args)
    {
        junit.textui.TestRunner.run(suite());
    }

    public static TestSuite suite()
    {
        return new TestSuite(UiModelPlatformTests.class);
    }

    public UiModelPlatformTests(String name)
    {
        super(name);
    }

    @Override
    protected void setUp() throws Exception
    {
        uiModel = MaruUIPlugin.getDefault().getUiModel();
    }

    @Override
    protected void tearDown() throws Exception
    {

    }

    public void testStartupShutdownStartup()
    {
        uiModel.startup();
        uiModel.shutdown();
        uiModel.startup();
    }
}


text:
using Moq;
using NUnit.Framework;
using Simple.Migrations.ConsoleRunner.Output;
using Simple.Migrations.ConsoleRunner.Process;
using SimpleMigrations;

namespace Simple.Migrations.ConsoleRunner.UnitTests
{
    [TestFixture]
    public class MigrationRunnerTests
    {
        [TestFixture]
        public class GivenInvalidMigration
        {
            private Mock<IVersionValidator> _versionValidator;
            private Mock<IApplyProcess> _applyProcess;
            private Mock<INoOpProcess> _noOpProcess;
            private Mock<ISimpleMigrator> _migrator;
            private Settings _settings;
            private Mock<IVersionOutputHelper> _versionOutputHelper;
            private bool _result;

            [OneTimeSetUp]
            public void WhenRunningMigrationFromSettings()
            {
                _versionValidator = new Mock<IVersionValidator>();
                _versionValidator
                    .Setup(v => v.Validate(It.IsAny<ISimpleMigrator>(), It.IsAny<Settings>()))
                    .Returns(VersionValidation.TargetVersionIsSameAsCurrent);

                _applyProcess = new Mock<IApplyProcess>();
                _noOpProcess = new Mock<INoOpProcess>();

                _migrator = new Mock<ISimpleMigrator>();
                _settings = new Settings("connection", 100, Mode.Apply, "assembly");

                _versionOutputHelper = new Mock<IVersionOutputHelper>();

                var runner = new MigrationRunner(_migrator.Object, _versionValidator.Object, _noOpProcess.Object, _applyProcess.Object, _versionOutputHelper.Object);
                _result = runner.Execute(_settings);
            }

            [Test]
            public void ThenTheVersionInfoIsOutput()
            {
                _versionOutputHelper.Verify(v => v.WriteVersionSection(_migrator.Object, _settings));
            }

            [Test]
            public void ThenTheSettingsAreValidated()
            {
                _versionValidator.Verify(v => v.Validate(_migrator.Object, _settings));
            }

            [Test]
            public void ThenTheMigrationsAreNotProcessed()
            {
                _noOpProcess.Verify(p => p.Run(It.IsAny<ISimpleMigrator>(), It.IsAny<long>()), Times.Never);
                _applyProcess.Verify(p => p.Run(It.IsAny<ISimpleMigrator>(), It.IsAny<long>()), Times.Never);
            }

            [Test]
            public void ThenTheResultIsFalse()
            {
                Assert.That(_result, Is.False);
            }
        }

        [TestFixture]
        public class GivenAValidNoOpMigration
        {
            private Settings _settings;
            private Mock<ISimpleMigrator> _migrator;
            private Mock<IVersionValidator> _versionValidator;
            private Mock<INoOpProcess> _noOpProcess;
            private Mock<IVersionOutputHelper> _versionOutputHelper;
            private bool _result;

            [OneTimeSetUp]
            public void WhenRunningMigrationFromSettings()
            {
                _versionValidator = new Mock<IVersionValidator>();
                _versionValidator
                    .Setup(v => v.Validate(It.IsAny<ISimpleMigrator>(), It.IsAny<Settings>()))
                    .Returns(VersionValidation.Valid);

                _noOpProcess = new Mock<INoOpProcess>();

                _settings = new Settings("connection", 1, Mode.NoOp, "test.dll");

                _migrator = new Mock<ISimpleMigrator>();

                _versionOutputHelper = new Mock<IVersionOutputHelper>();

                var runner = new MigrationRunner(_migrator.Object, _versionValidator.Object, _noOpProcess.Object, null, _versionOutputHelper.Object);
                _result = runner.Execute(_settings);
            }

            [Test]
            public void ThenTheVersionInfoIsOutput()
            {
                _versionOutputHelper.Verify(v => v.WriteVersionSection(_migrator.Object, _settings));
            }

            [Test]
            public void ThenTheSettingsAreValidated()
            {
                _versionValidator.Verify(v => v.Validate(_migrator.Object, _settings));
            }

            [Test]
            public void ThenTheNoOpProcessIsRun()
            {
                _noOpProcess.Verify(n => n.Run(_migrator.Object, _settings.TargetVersion));
            }

            [Test]
            public void ThenTheResultIsTrue()
            {
                Assert.That(_result, Is.True);
            }
        }

        [TestFixture]
        public class GivenAValidApplyMigration
        {
            private Settings _settings;
            private Mock<ISimpleMigrator> _migrator;
            private Mock<IVersionValidator> _versionValidator;
            private Mock<IApplyProcess> _applyProcess;
            private Mock<IVersionOutputHelper> _versionOutputHelper;
            private bool _result;

            [OneTimeSetUp]
            public void WhenRunningMigrationFromSettings()
            {
                _versionValidator = new Mock<IVersionValidator>();
                _versionValidator
                    .Setup(v => v.Validate(It.IsAny<ISimpleMigrator>(), It.IsAny<Settings>()))
                    .Returns(VersionValidation.Valid);

                _settings = new Settings("connection", 1, Mode.Apply, "test.dll");

                _migrator = new Mock<ISimpleMigrator>();

                _applyProcess = new Mock<IApplyProcess>();

                _versionOutputHelper = new Mock<IVersionOutputHelper>();

                var runner = new MigrationRunner(_migrator.Object, _versionValidator.Object, null, _applyProcess.Object, _versionOutputHelper.Object);
                _result = runner.Execute(_settings);
            }

            [Test]
            public void ThenTheVersionInfoIsOutput()
            {
                _versionOutputHelper.Verify(v => v.WriteVersionSection(_migrator.Object, _settings));
            }

            [Test]
            public void ThenTheSettingsAreValidated()
            {
                _versionValidator.Verify(v => v.Validate(_migrator.Object, _settings));
            }

            [Test]
            public void ThenTheApplyProcessIsRun()
            {
                _applyProcess.Verify(n => n.Run(_migrator.Object, _settings.TargetVersion));
            }

            [Test]
            public void ThenTheResultIsTrue()
            {
                Assert.That(_result, Is.True);
            }
        }
    }
}


text:
package ru.greg3d.factory.elements;

import org.openqa.selenium.WebElement;

/**
 * Represents text block on a web page.
 *
 * @author Behruz Afzali xy6er@yandex-team.ru
 */
public class TextBlock extends TypifiedElement {
    public TextBlock(WebElement wrappedElement) {
        super(wrappedElement);
    }

    /**
     * Returns text contained in text block.
     */
    public String getText() {
        return getWrappedElement().getText();
    }
}


text:
/*
 * Copyright 2005 Sun Microsystems, Inc. All rights reserved.
 */
package org.apache.jcp.xml.dsig.internal.dom;

import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;

import java.security.InvalidAlgorithmParameterException;

import org.apache.xml.security.c14n.Canonicalizer;
import org.apache.xml.security.c14n.InvalidCanonicalizerException;

/**
 * DOM-based implementation of CanonicalizationMethod for Canonical XML
 * (with or without comments). Uses Apache XML-Sec Canonicalizer.
 *
 */
public final class DOMCanonicalXMLC14NMethod extends ApacheCanonicalizer {

    public void init(TransformParameterSpec params)
        throws InvalidAlgorithmParameterException {
        if (params != null) {
            throw new InvalidAlgorithmParameterException("no parameters " +
                "should be specified for Canonical XML C14N algorithm");
        }
    }

    public Data transform(Data data, XMLCryptoContext xc)
        throws TransformException {

        // ignore comments if dereferencing same-document URI that requires
        // you to omit comments, even if the Transform says otherwise -
        // this is to be compliant with section 4.3.3.3 of W3C Rec.
        if (data instanceof DOMSubTreeData) {
            DOMSubTreeData subTree = (DOMSubTreeData) data;
            if (subTree.excludeComments()) {
                try {
                    canonicalizer = Canonicalizer.getInstance
                        (CanonicalizationMethod.INCLUSIVE);
                } catch (InvalidCanonicalizerException ice) {
                    throw new TransformException
                        ("Couldn't find Canonicalizer for: " +
                         CanonicalizationMethod.INCLUSIVE + ": " +
                         ice.getMessage(), ice);
                }
            }
        }

        return canonicalize(data, xc);
    }
}


text:
$packageName = 'babelpad'
$toolsDir = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
$url = 'http://www.babelstone.co.uk/Software/BabelPad.zip'
$checksum = '9864cfd216709cb8e3b07bddab840edcfb54761b'
$checksumType = 'sha1'

Install-ChocolateyZipPackage -PackageName "$packageName" `
                             -Url "$url" `
                             -UnzipLocation "$toolsDir" `
                             -Url64bit "" `
                             -Checksum "$checksum" `
                             -ChecksumType "$checksumType"


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;

namespace Bytes2you.Validation
{
    public interface IValidatableArgument<T> : IArgument<T>
    {
        [EditorBrowsable(EditorBrowsableState.Never)]
        IEnumerable<IValidationPredicate<T>> ValidationPredicates { get; }

        [EditorBrowsable(EditorBrowsableState.Never)]
        void AddValidationPredicate(IValidationPredicate<T> validationPredicate);

        [EditorBrowsable(EditorBrowsableState.Never)]
        IEnumerable<IValidationPredicateResult> MatchValidationPredicates();
    }
}


text:
// +build windows

package winstats

import (
	"os"
	"os/exec"
	"runtime"
	"strings"
	"sync"
	"syscall"
	"time"

	"errors"
	"github.com/golang/glog"
	cadvisorapi "github.com/google/cadvisor/info/v1"
	"k8s.io/apimachinery/pkg/util/wait"
	"unsafe"
)

// NewPerfCounterClient creates a client using perf counters
func NewPerfCounterClient() (Client, error) {
	return newClient(&perfCounterNodeStatsClient{})
}

// perfCounterNodeStatsClient is a client that provides Windows Stats via PerfCounters
type perfCounterNodeStatsClient struct {
	nodeMetrics
	mu sync.RWMutex // mu protects nodeMetrics
	nodeInfo
}

func (p *perfCounterNodeStatsClient) startMonitoring() error {
	memory, err := getPhysicallyInstalledSystemMemoryBytes()
	if err != nil {
		return err
	}

	version, err := exec.Command("cmd", "/C", "ver").Output()
	if err != nil {
		return err
	}

	osImageVersion := strings.TrimSpace(string(version))
	kernelVersion := extractVersionNumber(osImageVersion)
	p.nodeInfo = nodeInfo{
		kernelVersion:               kernelVersion,
		osImageVersion:              osImageVersion,
		memoryPhysicalCapacityBytes: memory,
		startTime:                   time.Now(),
	}

	cpuCounter, err := newPerfCounter(cpuQuery)
	if err != nil {
		return err
	}

	memWorkingSetCounter, err := newPerfCounter(memoryPrivWorkingSetQuery)
	if err != nil {
		return err
	}

	memCommittedBytesCounter, err := newPerfCounter(memoryCommittedBytesQuery)
	if err != nil {
		return err
	}

	go wait.Forever(func() {
		p.collectMetricsData(cpuCounter, memWorkingSetCounter, memCommittedBytesCounter)
	}, perfCounterUpdatePeriod)

	return nil
}

func (p *perfCounterNodeStatsClient) getMachineInfo() (*cadvisorapi.MachineInfo, error) {
	hostname, err := os.Hostname()
	if err != nil {
		return nil, err
	}

	return &cadvisorapi.MachineInfo{
		NumCores:       runtime.NumCPU(),
		MemoryCapacity: p.nodeInfo.memoryPhysicalCapacityBytes,
		MachineID:      hostname,
	}, nil
}

func (p *perfCounterNodeStatsClient) getVersionInfo() (*cadvisorapi.VersionInfo, error) {
	return &cadvisorapi.VersionInfo{
		KernelVersion:      p.nodeInfo.kernelVersion,
		ContainerOsVersion: p.nodeInfo.osImageVersion,
	}, nil
}

func (p *perfCounterNodeStatsClient) getNodeMetrics() (nodeMetrics, error) {
	p.mu.RLock()
	defer p.mu.RUnlock()
	return p.nodeMetrics, nil
}

func (p *perfCounterNodeStatsClient) getNodeInfo() nodeInfo {
	return p.nodeInfo
}

func (p *perfCounterNodeStatsClient) collectMetricsData(cpuCounter, memWorkingSetCounter, memCommittedBytesCounter *perfCounter) {
	cpuValue, err := cpuCounter.getData()
	if err != nil {
		glog.Errorf("Unable to get cpu perf counter data; err: %v", err)
		return
	}

	memWorkingSetValue, err := memWorkingSetCounter.getData()
	if err != nil {
		glog.Errorf("Unable to get memWorkingSet perf counter data; err: %v", err)
		return
	}

	memCommittedBytesValue, err := memCommittedBytesCounter.getData()
	if err != nil {
		glog.Errorf("Unable to get memCommittedBytes perf counter data; err: %v", err)
		return
	}

	p.mu.Lock()
	defer p.mu.Unlock()
	p.nodeMetrics = nodeMetrics{
		cpuUsageCoreNanoSeconds:   p.convertCPUValue(cpuValue),
		memoryPrivWorkingSetBytes: memWorkingSetValue,
		memoryCommittedBytes:      memCommittedBytesValue,
		timeStamp:                 time.Now(),
	}
}

func (p *perfCounterNodeStatsClient) convertCPUValue(cpuValue uint64) uint64 {
	cpuCores := runtime.NumCPU()
	// This converts perf counter data which is cpu percentage for all cores into nanoseconds.
	// The formula is (cpuPercentage / 100.0) * #cores * 1e+9 (nano seconds). More info here:
	// https://github.com/kubernetes/heapster/issues/650
	newValue := p.nodeMetrics.cpuUsageCoreNanoSeconds + uint64((float64(cpuValue)/100.0)*float64(cpuCores)*1e9)
	return newValue
}

func getPhysicallyInstalledSystemMemoryBytes() (uint64, error) {
	type MEMORY_STATUS_EX struct {
		Length               uint32
		MemoryLoad           uint32
		TotalPhys            uint64
		AvailPhys            uint64
		TotalPageFile        uint64
		AvailPageFile        uint64
		TotalVirtual         uint64
		AvailVirtual         uint64
		AvailExtendedVirtual uint64
	}

	var mod = syscall.NewLazyDLL("kernel32.dll")
	var proc = mod.NewProc("GlobalMemoryStatusEx")

	var memStatEx MEMORY_STATUS_EX
	memStatEx.Length = uint32(unsafe.Sizeof(memStatEx))
	ret, _, _ := proc.Call(uintptr(unsafe.Pointer(&memStatEx)))

	if ret == 0 {
		return 0, errors.New("unable to read physical memory")
	}

	return memStatEx.TotalPhys, nil
}


text:
.class abstract Landroid/support/v4/content/ModernAsyncTask$WorkerRunnable;
.super Ljava/lang/Object;
.source "ModernAsyncTask.java"

# interfaces
.implements Ljava/util/concurrent/Callable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/content/ModernAsyncTask;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x40a
    name = "WorkerRunnable"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<Params:",
        "Ljava/lang/Object;",
        "Result:",
        "Ljava/lang/Object;",
        ">",
        "Ljava/lang/Object;",
        "Ljava/util/concurrent/Callable",
        "<TResult;>;"
    }
.end annotation

# instance fields
.field mParams:[Ljava/lang/Object;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "[TParams;"
        }
    .end annotation
.end field

# direct methods
.method private constructor <init>()V
    .registers 1

    .prologue
    .line 492
    .local p0, "this":Landroid/support/v4/content/ModernAsyncTask$WorkerRunnable;, "Landroid/support/v4/content/ModernAsyncTask$WorkerRunnable<TParams;TResult;>;"
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Landroid/support/v4/content/ModernAsyncTask$1;)V
    .registers 2
    .param p1, "x0"    # Landroid/support/v4/content/ModernAsyncTask$1;

    .prologue
    .line 492
    .local p0, "this":Landroid/support/v4/content/ModernAsyncTask$WorkerRunnable;, "Landroid/support/v4/content/ModernAsyncTask$WorkerRunnable<TParams;TResult;>;"
    invoke-direct {p0}, Landroid/support/v4/content/ModernAsyncTask$WorkerRunnable;-><init>()V

    return-void
.end method


text:
package com.orientechnologies.lucene.collections;

import com.orientechnologies.common.util.ORawPair;
import com.orientechnologies.orient.core.id.ORID;
import java.util.stream.Stream;

/** Created by frank on 03/05/2017. */
public final class LuceneIndexTransformer {
  public static Stream<ORawPair<Object, ORID>> transformToStream(
      OLuceneResultSet resultSet, Object key) {
    return resultSet.stream()
        .map((identifiable -> new ORawPair<>(key, identifiable.getIdentity())));
  }
}


text:
package com.synckware.afinal;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

public class DetalheActivity extends AppCompatActivity {

    TextView txtPessoa;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detalhe);

        txtPessoa = (TextView) findViewById(R.id.txtPessoa);

        Bundle dado = getIntent().getExtras();
        String pessoa = dado.getString("pessoa");

        txtPessoa.setText("Parabens: "+pessoa);

    }
}


text:
package org.zkoss.zss.essential.advanced.customization;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zss.ui.AuxAction;
import org.zkoss.zss.ui.Spreadsheet;
import org.zkoss.zss.ui.UserActionManager;
import org.zkoss.zss.ui.impl.DefaultUserActionManagerCtrl;

/**
 * This class demonstrate usage of "custom user action handler".
 * @author Hawk
 *
 */
@SuppressWarnings("serial")
public class CustomHandlerComposer extends SelectorComposer<Component> {

	@Wire
	private Spreadsheet ss;

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);

		//initialize custom handlers
		UserActionManager actionManager = ss.getUserActionManager();
		actionManager.registerHandler(
				DefaultUserActionManagerCtrl.Category.AUXACTION.getName(),
				AuxAction.NEW_BOOK.getAction(), new NewBookHandler());
		actionManager.registerHandler(
				DefaultUserActionManagerCtrl.Category.AUXACTION.getName(),
				AuxAction.SAVE_BOOK.getAction(), new SaveBookHandler());
	}
}


text:
input, #search-button{
    padding:0 !important;
}

a{
    border:none !important;
}

#container-header .row, #container-header .navbar-inner {
    background-color: transparent;
}
/*

#container-search .row{
    border:1px solid blue;
    text-align: left;
    padding-right:20px;
     display:inline-block;
}
.search-bar{

   border:1px solid red;
   display:inline;
   width:200px;

}*/

@media all and (max-width: 980px) {

    #container-search{
        margin-top:60px;
    }
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Orderform extends CI_Controller {

    function __construct() {

  	parent::__construct();

         header("Content-Type: text/html; charset=UTF8");

         $this->load->helper(array('form', 'url'));
         $this->load->database();
         $this->load->library('session');

         $this->load->model('Data_forall', '', TRUE);
         $this->load->model('Data_uni', '', TRUE);
         $this->load->model('Data_orderform', '', TRUE);

         if (($this->session->userdata('userLang') != null)AND($this->session->userdata('userLang') != FALSE)) {
          $userLang = $this->session->userdata('userLang');
         } else {
          $userLang = BASELANG;
         }

         $this->lang->load('forall', $userLang);
         $this->lang->load('orderform', $userLang);
         $this->config->set_item('language', $userLang);

         ini_set('date.timezone', TIMEZONE);
         setlocale(LC_ALL, "Russian_Russia.UTF8");

    }

    function _remap($method) {

     $allowedPages = array();

     $pars = $this->uri->segment_array();

      unset($pars[1]);
      unset($pars[2]);

      if (($this->session->userdata('userLang') != null)AND($this->session->userdata('userLang') != FALSE)) {
          $userLang = $this->session->userdata('userLang');
         } else {
          $userLang = BASELANG;
         }

      array_push($pars,$userLang);

      if ($method!='css') call_user_func_array(array($this, $method), $pars);

    }

    function sendmail() {

         $ot_kogo = "newmailreg@yandex.ru";
         $tema = "tema test";
         $telo = "test";
         $to = "navakus@mail.ru";

         $this->Data_forall->send_pismo($ot_kogo,$to,$tema,$telo);

         $ot_kogo = "navakus@mail.ru";
         $tema = "tema test";
         $telo = "test";
         $to = "newmailreg@yandex.ru";

         $this->Data_forall->send_pismo($ot_kogo,$to,$tema,$telo);

         echo "$ot_kogo,$to,$tema,$telo";

    }

    public function index($userLang) {

      $pageData['page_title'] = $this->lang->line('orderform_title_page');

      $pageData['localize'] = $_POST['localize'] = $this->Data_uni->get_localize($userLang);

      $pageData['plug_components'] = $this->Data_forall->get_plug_components( array( "jquery","bootstrap","font_awesome","datetimepicker" ) );
      $pageData['plug_css'] = $this->Data_forall->get_css( array("forall","orderform") );

      $pageData['id_partner'] = $this->session->userdata('id_partner');

      $pageData['resorts'] = $this->Data_uni->uni_get_alldata_from_table("resorts","");

      $pageData['id_order'] = '';

      $pageData['form'] = $this->load->view('orderform/orderform_form',$pageData,TRUE);

      //$pageData['order'] = $this->Data_orderform->get_order(22);

      $this->load->view('layouts/header',$pageData);

      //$this->load->view('orderform/success');

      $this->load->view('orderform/orderform_main');
      $this->load->view('layouts/footer');

    }

    function del_jqOrder($userLang) {

      $jq_html = "0";

      if ($this->input->post('id_order')) {

       $jq_html = $this->Data_uni->uni_delete_by_field("orders","id",$this->input->post('id_order'));

      }

      if ($jq_html=="0" or $jq_html==FALSE) $response['jq_alert_msg'] = "".$this->input->post('dontdeleting');

      $response['jq_html'] = "$jq_html";

      echo json_encode($response);
    }

    function add_jqOrder($userLang) {

       $this->load->library('form_validation');

       $data = $this->Data_forall->get_all_date_from_post();

       $this->lang->load('myvalidation', $userLang);

       $alert_msg = $jq_html = "0";
       $jq_html_data_showing_order = "";

       $this->form_validation->set_rules('id_partner', '', 'integer|required');
       $this->form_validation->set_rules('id_resort', $this->lang->line('id_resort'), 'required');
       $this->form_validation->set_rules('equip', $this->lang->line('equip'), 'required');
       $this->form_validation->set_rules('kolvo', $this->lang->line('kolvo'), 'integer|required');
       $this->form_validation->set_rules('adultchild[]', $this->lang->line('adultchild'), 'required');
       $this->form_validation->set_rules('age_child_from', $this->lang->line('from'), 'trim');
       $this->form_validation->set_rules('age_child_to', $this->lang->line('to'), 'trim');
       $this->form_validation->set_rules('name', $this->lang->line('your_name'), 'trim|required');
       $this->form_validation->set_rules('tel', $this->lang->line('tel'), 'trim|min_length[10]|required');
       $this->form_validation->set_rules('date_time', $this->lang->line('fst_date_time'), 'regex_match[/(\d{2}).(\d{2}).(\d{4}) (\d{2}):(\d{2})/]');
       $this->form_validation->set_rules('kolvo_days', $this->lang->line('kolvo_days'), 'integer|required');
       $this->form_validation->set_rules('hours_by_day', $this->lang->line('kolvo_hours_by_day'), 'integer|required');

       if ($this->form_validation->run() == FALSE) {

        $alert_msg = "
×".$this->lang->line('error')."".validation_errors()."
";

       } else {

        $data['adultchild'] = implode(",", $data['adultchild']);
        $data['date_time'] = $this->Data_uni->YearToDay($data['date_time']);
        $data['id_partner_give'] = $data['id_partner'];
        unset($data['id_partner']);
        $data['id_partner_take'] = 0;

        //INSERT или UPDATE
        if ((isset($data['id_order']) and $data['id_order']=='')or(isset($data['id_order']) and $data['id_order']==0)) unset($data['id_order']);

        if (isset($data['id_order'])) {

          $pageData['id_order'] = $data['id_order'];
          unset($data['id_order']);

          unset($data['id_partner_take']);

          $this->Data_uni->uni_update_arr($data,"orders","id",$pageData['id_order']);
          //$this->Data_orderform->update_order($data,$pageData['id_order']);

          //Карточка для акцепта заказа со стороны инструктора
          if ($data['status']=="in_operation_step1") {
           $pageData['order'] = $this->Data_orderform->get_order($pageData['id_order']);
           $pageData['no_buttons'] = TRUE;
           $jq_html_data_showing_order = $this->load->view('feed/feed_success_pickup',$pageData,TRUE);
          }

        } else {

         $data['data_born'] = date("Y-m-d H:i:s");

         $pageData['id_order'] = $this->Data_uni->uni_insert($data,"orders");

        /* if ($pageData['id_order']) {

          $param = array(
             "id_order"=>$pageData['id_order']
          );

          $pageData['id_feed'] = $this->Data_uni->uni_insert($data,"feed");

         } */

        }

        $pageData['order'] = $this->Data_orderform->get_order($pageData['id_order']);

        if ($pageData['order']) $this->Data_orderform->send_notifs_by_addorder($data,$pageData['order']);

        $jq_html = $this->load->view('orderform/orderform_success',$pageData,TRUE);
       }

      $response['jq_html'] = "$jq_html";
      $response['jq_html_data_showing_order'] = "$jq_html_data_showing_order";
      $response['jq_alert_msg'] = "$alert_msg";

      echo json_encode($response);
    }

}


text:
StacksightMeteor = {
    extendsFS: function(collections) {
        _.each(collections, function(collection) {
            var insert_func = collection.insert;
            collection.insert = function(file, callback) {
                var insert_callback = function(err, fileout) {
                    if(err !== undefined) {
                        //    Error callback
                    } else {
                        var dataobj = {
                            id: fileout._id,
                            url: Meteor.absoluteUrl(fileout.url({brokenIsFine: true})),
                            name: fileout.data.blob.name,
                            size: fileout.data.blob.size,
                            type: fileout.data.blob.type,
                        };
                        if(fileout.isImage() === true) {
                            dataobj = _.extend(dataobj, {
                                filetype: {subtype: 'image'}
                            });
                            Meteor.call('hookImageLoad', dataobj);
                        } else {
                            Meteor.call('hookFileLoad', dataobj);
                        }
                    }
                    callback.call(collection, err, fileout);
                }
                insert_func.call(collection, file, insert_callback);
            }
        });
    }
};


text:
.. scieloapi.py documentation master file, created by
   sphinx-quickstart on Fri Aug  2 10:49:12 2013.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

ratchetapi.py
============

Release v\ |version|.
This software is licensed under `BSD License <http://opensource.org/licenses/BSD-2-Clause>`_.

Usage example::

    >>> import ratchetapi

    >>> client = ratchetapi.Client('some.user', 'some.api_key')

    >>> for journal in client.query('journals').all():
    ...    print journal['code'], journal['total']

User guide
----------

Step-by-step guide to use the features provided by ratchetapi.py for
exploring data from SciELO.

.. toctree::
   :maxdepth: 2

   narr/install
   narr/quickstart

API documentation
-----------------

If you are looking for information about the library internals,
this if for you.

.. toctree::
   :maxdepth: 2

   api


text:
package cz.zcu.kiv.jop.strategy;

import cz.zcu.kiv.jop.context.PopulatingContext;
import cz.zcu.kiv.jop.property.Property;

/**
 * The common interface for all populating strategies for properties. The strategy is applied to
 * some property and it may populate some value into that property or enqueue class into populating
 * context to populate. Strategies can be used in combination with class providers or instance
 * matchers.
 *
 * @author Mr.FrAnTA
 * @since 1.0.0
 */
public interface PopulatingStrategy {

  /**
   * Returns information whether the populating strategy is lazy. Lazy strategies are usually
   * invoked in the end of poulating process but it depends on implementation of actual
   * {@link PopulatingContext}. Lazy strategies cannot enqueue new objects (dependencies) for
   * population.
   *
   * @return true if populating strategy is lazy; false otherwise.
   */
  public boolean isLazyStrategy();

  /**
   * Returns information whether populating strategy may be {@link #applyStrategy applied} to given
   * property.
   *
   * @param property the property to check.
   * @return true if populating strategy may be {@link #applyStrategy applied} to given
   *         property; false otherwise.
   */
  public boolean supports(Property<?> property);

  /**
   * Applies populating strategy to given property. It may populate some value into property or
   * enqueue class into populating context to populate.
   *
   * @param property the property on which will be applied this populating strategy.
   * @param context the populating context which contains already populated (generated) objects
   *          which may be obtained; also supports enqueuing classes for population.
   * @throws PopulatingStrategyException If some error occurs during applying of populating strategy
   *           to given property.
   */
  public void applyStrategy(Property<?> property, PopulatingContext context) throws PopulatingStrategyException;

}


text:
package gopdf

import (
	"fmt"
	"io"
	"math"
)

type cacheContentRotate struct {
	isReset     bool
	pageHeight  float64
	angle, x, y float64
}

func (cc *cacheContentRotate) write(w io.Writer, protection *PDFProtection) error {
	if cc.isReset == true {
		if _, err := io.WriteString(w, "Q\n"); err != nil {
			return err
		}

		return nil
	}

	matrix := computeRotateTransformationMatrix(cc.x, cc.y, cc.angle, cc.pageHeight)
	contentStream := fmt.Sprintf("q\n %s", matrix)

	if _, err := io.WriteString(w, contentStream); err != nil {
		return err
	}

	return nil
}

func computeRotateTransformationMatrix(x, y, degreeAngle, pageHeight float64) string {
	radianAngle := degreeAngle * (math.Pi / 180)

	c := math.Cos(radianAngle)
	s := math.Sin(radianAngle)
	cy := pageHeight - y

	return fmt.Sprintf("%.5f %.5f %.5f\n %.5f %.2f %.2f cm\n 1 0 0\n 1 %.2f %.2f cm\n", c, s, -s, c, x, cy, -x, -cy)
}


text:
Only li > a fires event. Clicking button does nothing.

Code

{% highlight html %}

A

B

C

    <button>button</button>

{% endhighlight %}


text:
using namespace seqan;

int main ()
{
///We begin with a @Class.StringSet@ that stores multiple strings.
	StringSet< String<char> > mySet;
	resize(mySet, 3);
	mySet[0] = "SeqAn is a library for sequence analysis.";
	mySet[1] = "The String class is the fundamental sequence type in SeqAn.";
	mySet[2] = "Subsequences can be handled with SeqAn's Segment class.";

///Then we create an @Class.Index@ of this @Class.StringSet@.
	typedef Index< StringSet<String<char> > > TMyIndex;
	TMyIndex myIndex(mySet);

///Now we require that the index has a suffix array and a lcp table using the function @Function.indexRequire@.

    indexRequire(myIndex, EsaLcp() );
    indexRequire(myIndex, EsaSA());

///We iterate over the lcp table and output the position, the value of the lcp table and the corresponding suffix using the functions @Function.saAt@ and @Function.lcpAt@.

    for ( Size<TMyIndex>::Type i=0; i<length(myIndex); ++i){
        SAValue<TMyIndex>::Type p = saAt(i,myIndex);
        ::std::cout << i << " " << lcpAt(i,myIndex) << " " << p << " " << suffix(mySet,p) << ::std::endl;
    }

	return 0;
}


text:
package com.joelapenna.foursquared;

import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquared.app.AuthenticationService;
import com.joelapenna.foursquared.error.LocationException;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.preferences.Preferences;
import com.joelapenna.foursquared.util.NotificationsUtil;

import android.accounts.AccountAuthenticatorActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Joe LaPenna (joe@joelapenna.com)
 */
public class LoginActivity extends AccountAuthenticatorActivity {
    public static final String TAG = "LoginActivity";
    public static final boolean DEBUG = FoursquaredSettings.DEBUG;

    public static final String ACTION_LOGIN = "com.joelapenna.foursquared.intent.action.LOGIN";

    private AsyncTask<Void, Void, Boolean> mLoginTask;

    private TextView mNewAccountTextView;
    private EditText mPhoneUsernameEditText;
    private EditText mPasswordEditText;

    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (DEBUG) Log.d(TAG, "onCreate()");
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.login_activity);

        Preferences.logoutUser( //
                ((Foursquared) getApplication()).getFoursquare(), //
                PreferenceManager.getDefaultSharedPreferences(this).edit());

        // Set up the UI.
        ensureUi();

        // Re-task if the request was cancelled.
        mLoginTask = (LoginTask) getLastNonConfigurationInstance();
        if (mLoginTask != null && mLoginTask.isCancelled()) {
            if (DEBUG) Log.d(TAG, "LoginTask previously cancelled, trying again.");
            mLoginTask = new LoginTask().execute();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        ((Foursquared) getApplication()).requestLocationUpdates(false);
    }

    @Override
    public void onPause() {
        super.onPause();
        ((Foursquared) getApplication()).removeLocationUpdates();
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        if (DEBUG) Log.d(TAG, "onRetainNonConfigurationInstance()");
        if (mLoginTask != null) {
            mLoginTask.cancel(true);
        }
        return mLoginTask;
    }

    private ProgressDialog showProgressDialog() {
        if (mProgressDialog == null) {
            ProgressDialog dialog = new ProgressDialog(this);
            dialog.setTitle(R.string.login_dialog_title);
            dialog.setMessage(getString(R.string.login_dialog_message));
            dialog.setIndeterminate(true);
            dialog.setCancelable(true);
            mProgressDialog = dialog;
        }
        mProgressDialog.show();
        return mProgressDialog;
    }

    private void dismissProgressDialog() {
        try {
            mProgressDialog.dismiss();
        } catch (IllegalArgumentException e) {
            // We don't mind. android cleared it for us.
        }
    }

    private void ensureUi() {
        final Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLoginTask = new LoginTask().execute();
            }
        });

        mNewAccountTextView = (TextView) findViewById(R.id.newAccountTextView);
        mNewAccountTextView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent( //
                        Intent.ACTION_VIEW, Uri.parse(Foursquare.FOURSQUARE_MOBILE_SIGNUP)));
            }
        });

        mPhoneUsernameEditText = ((EditText) findViewById(R.id.phoneEditText));
        mPasswordEditText = ((EditText) findViewById(R.id.passwordEditText));

        TextWatcher fieldValidatorTextWatcher = new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                button.setEnabled(phoneNumberEditTextFieldIsValid()
                        && passwordEditTextFieldIsValid());
            }

            private boolean phoneNumberEditTextFieldIsValid() {
                // This can be either a phone number or username so we don't
                // care too much about the
                // format.
                return !TextUtils.isEmpty(mPhoneUsernameEditText.getText());
            }

            private boolean passwordEditTextFieldIsValid() {
                return !TextUtils.isEmpty(mPasswordEditText.getText());
            }
        };

        mPhoneUsernameEditText.addTextChangedListener(fieldValidatorTextWatcher);
        mPasswordEditText.addTextChangedListener(fieldValidatorTextWatcher);
    }

    private class LoginTask extends AsyncTask<Void, Void, Boolean> {
        private static final String TAG = "LoginTask";
        private static final boolean DEBUG = FoursquaredSettings.DEBUG;

        private String mPhoneNumber;
        private String mPassword;
        private Exception mReason;

        @Override
        protected void onPreExecute() {
            if (DEBUG) Log.d(TAG, "onPreExecute()");
            showProgressDialog();
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            if (DEBUG) Log.d(TAG, "doInBackground()");
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(LoginActivity.this);
            Editor editor = prefs.edit();
            Foursquared foursquared = (Foursquared) getApplication();
            Foursquare foursquare = foursquared.getFoursquare();
            try {
                mPhoneNumber = mPhoneUsernameEditText.getText().toString();
                mPassword = mPasswordEditText.getText().toString();

                Foursquare.Location location = null;
                try {
                    location = LocationUtils.createFoursquareLocation(foursquared.getLastKnownLocation());
                } catch (LocationException e) {
                    // best effort for a login. We can guess the location from
                    // the user's current city setting.
                }

                boolean loggedIn = Preferences.loginUser(foursquare, mPhoneNumber, mPassword,
                        location, editor);

                // Make sure prefs make a round trip.
                String userId = Preferences.getUserId(prefs);
                if (TextUtils.isEmpty(userId)) {
                    if (DEBUG) Log.d(TAG, "Preference store calls failed");
                    throw new FoursquareException(getResources().getString(
                            R.string.login_failed_login_toast));
                }

                // Add it to the android account manager.
                Bundle result = AuthenticationService.createSystemAccount(getApplicationContext(),
                        mPhoneNumber, mPassword);
                setAccountAuthenticatorResult(result);

                return loggedIn;

            } catch (Exception e) {
                if (DEBUG) Log.d(TAG, "Caught Exception logging in.", e);
                mReason = e;
                Preferences.logoutUser(foursquare, editor);
                return false;
            }
        }

        @Override
        protected void onPostExecute(Boolean loggedIn) {
            if (DEBUG) Log.d(TAG, "onPostExecute(): " + loggedIn);
            Foursquared foursquared = (Foursquared) getApplication();

            if (loggedIn) {
                sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_IN));
                Toast.makeText(foursquared, getString(R.string.login_welcome_toast),
                        Toast.LENGTH_SHORT).show();

                // Launch the service to update any widgets, etc.
                foursquared.requestStartService();

                // If we got here on our own, not from some login intent, lets
                // try and launch main.
                if (!ACTION_LOGIN.equals(getIntent().getAction())) {
                    // Launch the main activity to let the user do anything.
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }

                // Be done with the activity.
                finish();

            } else {
                sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_OUT));
                NotificationsUtil.ToastReasonForFailure(LoginActivity.this, mReason);
            }
            dismissProgressDialog();
        }

        @Override
        protected void onCancelled() {
            dismissProgressDialog();
        }
    }
}


text:
function Timer(){
    self = this;

    this.running = false;
    this.defaultTime = 3600;
    this.remaining = this.defaultTime;
    this.timeArray = {};
    this.stopped = false;

    this.apiPath = 'http://' + window.location.host + '/game-api';

    this.build = function() {
        self.stopped = false;
        self.tick();

        $('#start').click(function(){
            self.start();
        });

        $('#pause').click(function(){
            self.stop();
        });

        $('#setTime').click(function(){
            self.set();
        });
    };

    this.halt = function() {
        self.stopped = true;
    };

    this.sync = function() {
        jQuery.ajax({
            url:    self.apiPath + '/timer',
            success: function(result) {
                self.running = result.running;
                self.remaining = result.remaining;
            },
            async:   false
        });
    };

    this.tickEvent = function() {
        var tick = new CustomEvent('tick', {'detail': this.remaining});
        window.dispatchEvent(tick);
        window.dispatchEvent(tick);
    };

    this.tick = function() {
        console.log('tick');
        if (self.stopped !== true) {
            if (self.running === false){
                self.sync();
            }

            if (self.running === true && self.remaining > 0) {
                console.log(self.remaining);
                self.sync();

                self.remaining -= 1;
                self.tickEvent();
                window.setTimeout(self.tick, 1000);
                return;
            } else {
                window.setTimeout(self.tick, 1000);
                return;
            }
        }
    };

    this.getTime = function(){
        var hours = document.querySelector('input[name="hours"]').value;
        var minutes = document.querySelector('input[name="minutes"]').value;
        var seconds = document.querySelector('input[name="seconds"]').value;
        if (hours === ''|| hours === null || hours === undefined)
        {
            hours = 0;
        }
        if (minutes === ''|| minutes === null || minutes === undefined)
        {
            minutes = 0;
        }
        if (seconds === ''|| seconds === null || seconds === undefined)
        {
            seconds = 0;
        }

        var time = parseInt(seconds);
        time += parseInt(minutes)*60;
        time += parseInt(hours)*3600;
        return time;
    };

    this.start = function() {
        $.ajax({
            url: self.apiPath + '/timer',
            type: 'POST',
            data: JSON.stringify({action: "start"}),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(msg) {
                console.log(msg);
            }
        });
    };

    this.stop = function() {
        $.ajax({
            url: self.apiPath + '/timer',
            type: 'POST',
            data: JSON.stringify({action: "stop"}),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(msg) {
                console.log(msg);
            }
        });
    };

    this.set = function() {
        $.ajax({
            url: self.apiPath + '/timer',
            type: 'POST',
            data: JSON.stringify({action: "set", remaining: self.getTime()}),
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            success: function(msg) {
                toastr.success('Idő beállítva');
            }
        });
    };

}