text:
'use strict';

/**
 * Unit tests for aws-core-utils/api-lambdas.js
 * @author Byron du Preez
 */

const test = require('tape');

// The test subject
const apiLambdas = require('../api-lambdas');

const appErrors = require('core-functions/app-errors');
const BadRequest = appErrors.BadRequest;

const Promises = require('core-functions/promises');

const Strings = require('core-functions/strings');
const stringify = Strings.stringify;

const logging = require('logging-utils');
const LogLevel = logging.LogLevel;

const kinesisCache = require("../kinesis-cache");
const dynamoDBDocClientCache = require("../dynamodb-doc-client-cache");

const samples = require('./samples');
// For AWS contexts
const sampleInvokedFunctionArn = samples.sampleInvokedFunctionArn;
const sampleAwsContext = samples.sampleAwsContext;

const uuid = require('uuid');

function sampleFunction(resolvedResponse, rejectedError, ms) {
  if (!ms) ms = 1;

  function doSomethingUseful(event, context) {
    context.info(`Simulating doing something useful with event ${JSON.stringify(event)}`);
    return Promises.delay(ms)
      .then(() => {
        return rejectedError ? Promise.reject(rejectedError) : Promise.resolve(resolvedResponse);
      });
  }

  return doSomethingUseful;
}

function setRegionStageAndDeleteCachedInstances(region, stage) {
  // Set up region
  if (region)
    process.env.AWS_REGION = region;
  else
    delete process.env.AWS_REGION;

  // Set up stage
  if (stage)
    process.env.STAGE = stage;
  else
    delete process.env.STAGE;

  // Remove any cached entries before configuring
  deleteCachedInstances();
  return region;
}

function deleteCachedInstances() {
  const region = process.env.AWS_REGION;
  kinesisCache.deleteKinesis(region);
  dynamoDBDocClientCache.deleteDynamoDBDocClient(region);
}

/**
 * A custom `toErrorResponse` function.
 * @param {AppError} error
 * @param {AwsEvent} event
 * @param {StandardHandlerContext} context
 */
function toCustomErrorResponse(error, event, context) {
  return {
    ErrorType: error.code || null,
    HttpStatus: error.httpStatus || null,
    AuditReferenceNumber: error.auditRef || (context.awsContext && context.awsContext.awsRequestId) || null,
    Message: error.message || null
  };
}

// =====================================================================================================================
// generateHandlerFunction simulating successful response (with useLambdaProxy false & NON-legacy parameters)
// =====================================================================================================================

test('generateHandlerFunction simulating successful response (with useLambdaProxy false & NON-legacy parameters & NON-legacy opts)', t => {
  try {
    // Set up environment for testing
    const region = setRegionStageAndDeleteCachedInstances('us-west-2', 'dev99');

    // Create sample AWS event and AWS context
    const event = {body: {abc: 123}};
    const invokedFunctionArn = sampleInvokedFunctionArn(region, 'myLambdaFunctionName', 'dev77');
    const awsContext = sampleAwsContext('myLambdaFunctionName', '1.0.1', invokedFunctionArn, 500);

    const expectedResponse = {def: 456};

    // Create a sample function to be executed within the Lambda handler function
    const fn = sampleFunction(expectedResponse, undefined);

    // Create a sample AWS Lambda handler function
    const createContext = () => ({});
    const createSettings = undefined;
    const createOptions = () => require('./api-lambdas-context-options-1.json');

    const opts = {
      logRequestResponseAtLogLevel: LogLevel.INFO,
      invalidRequestMsg: 'Invalid do something request',
      failedMsg: 'Failed to do something useful',
      successMsg: 'Did something useful'
    };

    const handler = apiLambdas.generateHandlerFunction(createContext, createSettings, createOptions, fn, opts);

    // Wrap the callback-based AWS Lambda handler function as a Promise returning function purely for testing purposes
    const handlerWithPromise = Promises.wrap(handler);

    // Invoke the handler function
    handlerWithPromise(event, awsContext)
      .then(response => {
        t.pass(`handler should have passed`);
        t.equal(response, expectedResponse, `response must be ${JSON.stringify(expectedResponse)}`);
        t.end();
      })
      .catch(err => {
        t.fail(`handler should not have failed - ${err}`);
        t.end();
      });

  } catch (err) {
    t.fail(`handler should not have failed in try-catch - ${err}`);
    t.end();

  } finally {
    // Clean up environment
    setRegionStageAndDeleteCachedInstances(undefined, undefined);
  }
});

// =====================================================================================================================
// generateHandlerFunction simulating failure (with useLambdaProxy false & NON-legacy parameters)
// =====================================================================================================================

test('generateHandlerFunction simulating failure (with useLambdaProxy false & NON-legacy parameters & NON-legacy opts)', t => {
  try {
    // Set up environment for testing
    const region = setRegionStageAndDeleteCachedInstances('us-west-2', 'dev99');

    // Create sample AWS event and AWS context
    const event = {body: {abc: 123}};
    const invokedFunctionArn = sampleInvokedFunctionArn(region, 'myLambdaFunctionName', 'dev77');
    const awsContext = sampleAwsContext('myLambdaFunctionName', '1.0.1', invokedFunctionArn, 500);

    const expectedError = new Error('Kaboom');

    // Create a sample function to be executed within the Lambda handler function
    const fn = sampleFunction(undefined, expectedError);

    // Create a sample AWS Lambda handler function
    const createContext = () => ({});
    const createOptions = () => require('./api-lambdas-context-options-1.json');

    const opts = {
      logRequestResponseAtLogLevel: LogLevel.TRACE,
      invalidRequestMsg: 'Invalid do something request',
      failedMsg: 'Failed to do something useful',
      successMsg: 'Did something useful'
    };

    const handler = apiLambdas.generateHandlerFunction(createContext, undefined, createOptions, fn, opts);

    // Wrap the callback-based AWS Lambda handler function as a Promise returning function purely for testing purposes
    const handlerWithPromise = Promises.wrap(handler);

    // Invoke the handler function
    handlerWithPromise(event, awsContext)
      .then(response => {
        t.fail(`handler should NOT have passed with response ${stringify(response)}`);
        t.end();
      })
      .catch(err => {
        //console.error(`################### err = ${err}`);
        t.pass(`handler should have failed - ${err}`);
        const e = JSON.parse(err);
        t.equal(e.message, expectedError.message, `e.message must be "${expectedError.message}"`);
        t.equal(e.code, "Error", `e.code must be "Error"`);
        t.equal(e.httpStatus, 500, `e.httpStatus must be 500`);
        const expectedCause = 'Error: ' + expectedError.message;
        t.equal(e.cause, expectedCause, `e.cause must be "${expectedCause}"`);
        t.equal(e.causeStatus, undefined, `e.causeStatus must be undefined`);
        t.equal(e.awsRequestId, awsContext.awsRequestId, `e.awsRequestId must be "${awsContext.awsRequestId}"`);
        t.end();
      });

  } catch (err) {
    t.fail(`handler should not have failed in try-catch - ${err}`);
    t.end();

  } finally {
    // Clean up environment
    setRegionStageAndDeleteCachedInstances(undefined, undefined);
  }
});

// =====================================================================================================================
// generateHandlerFunction simulating successful response (with useLambdaProxy true & NON-legacy parameters)
// =====================================================================================================================

test('generateHandlerFunction simulating successful response (with useLambdaProxy true & NON-legacy parameters & NON-legacy opts)', t => {
  try {
    // Set up environment for testing
    const region = setRegionStageAndDeleteCachedInstances('us-west-2', 'dev99');

    // Create sample AWS event and AWS context
    const event = require('./sample-lamba-proxy-request.json');
    const invokedFunctionArn = sampleInvokedFunctionArn(region, 'myLambdaFunctionName', 'dev77');
    const awsContext = sampleAwsContext('myLambdaFunctionName', '1.0.1', invokedFunctionArn, 500);

    const body = {def: 456};
    const response = {
      // statusCode: 200,
      headers: {hdr1: 'h1', hdr3: 'h3'},
      body: body
    };
    const expectedResponse = {
      statusCode: 200,
      headers: {hdr1: 'h1', hdr3: 'h3', hdr2: 'dh2'}, // merged headers
      body: JSON.stringify(body)
    };

    // Create a sample function to be executed within the Lambda handler function
    const fn = sampleFunction(response, undefined);

    const context = {};
    const preSuccessCallback = function preSuccessCallback(response1, event1, context1) {
      t.pass(`*** preSuccessCallback must be invoked`);
      t.ok(response1, `preSuccessCallback response1 must exist`);
      t.deepEqual(response1, expectedResponse, `preSuccessCallback response1 must be expectedResponse`);
      t.equal(event1, event, `preSuccessCallback event1 must be event`);
      t.equal(context1, context, `preSuccessCallback context1 must be context`);
    };
    // noinspection JSUnusedLocalSymbols
    const preFailureCallback = function preFailureCallback(error1, errorResponse1, event1, context1) {
      t.fail(`### preFailureCallback must NOT be invoked with error (${error1})`);
    };
    const postConfigure = function postConfigure(event1, context1) {
      t.pass(`*** postConfigure must be invoked`);
      t.equal(event1, event, `postConfigure event1 must be event`);
      t.equal(context1, context, `postConfigure context1 must be context`);

      t.equals(context1.handler.postConfigure, postConfigure, `context1.handler.postConfigure must be postConfigure`);
      t.equals(context1.handler.preSuccessCallback, preSuccessCallback, `context1.handler.preSuccessCallback must be preSuccessCallback`);
      t.equals(context1.handler.preFailureCallback, preFailureCallback, `context1.handler.preFailureCallback must be preFailureCallback`);
    };

    // Create a sample AWS Lambda handler function
    const createContext = () => context;
    const handlerSettings = {
      toErrorResponse: toCustomErrorResponse,
      postConfigure: postConfigure,
      preSuccessCallback: preSuccessCallback,
      preFailureCallback: preFailureCallback
    };
    const createSettings = () => ({handler: handlerSettings});
    const createOptions = () => require('./api-lambdas-context-options-2.json');

    const opts = {
      logRequestResponseAtLogLevel: LogLevel.INFO,
      invalidRequestMsg: 'Invalid do something request',
      failedMsg: 'Failed to do something useful',
      successMsg: 'Did something useful'
    };
    const handler = apiLambdas.generateHandlerFunction(createContext, createSettings, createOptions, fn, opts);

    // Wrap the callback-based AWS Lambda handler function as a Promise returning function purely for testing purposes
    const handlerWithPromise = Promises.wrap(handler);

    // Invoke the handler function
    handlerWithPromise(event, awsContext)
      .then(response => {
        t.pass(`handler should have passed`);
        t.deepEqual(response, expectedResponse, `response must be ${JSON.stringify(expectedResponse)}`);
        t.end();
      })
      .catch(err => {
        t.fail(`handler should not have failed - ${err}`);
        t.end();
      });

  } catch (err) {
    t.fail(`handler should not have failed in try-catch - ${err}`);
    t.end();

  } finally {
    // Clean up environment
    setRegionStageAndDeleteCachedInstances(undefined, undefined);
  }
});

// =====================================================================================================================
// generateHandlerFunction simulating failure response (with useLambdaProxy true & NON-legacy parameters)
// =====================================================================================================================

test('generateHandlerFunction simulating failure response (with useLambdaProxy true & NON-legacy parameters & NON-legacy opts)', t => {
  try {
    // Set up environment for testing
    const region = setRegionStageAndDeleteCachedInstances('us-west-2', 'dev99');

    // Create sample AWS event and AWS context
    const event = require('./sample-lamba-proxy-request.json');
    const invokedFunctionArn = sampleInvokedFunctionArn(region, 'myLambdaFunctionName', 'dev77');
    const awsContext = sampleAwsContext('myLambdaFunctionName', '1.0.1', invokedFunctionArn, 500);

    const error = new BadRequest('Invalid request');
    error.headers = {hdr1: 'h1', hdr3: 'h3'};
    error.auditRef = uuid();

    // Create a sample function to be executed within the Lambda handler function
    const fn = sampleFunction(undefined, error);

    // Create a sample AWS Lambda handler function
    const createContext = () => ({});
    const createSettings = () => undefined;
    const createOptions = () => require('./api-lambdas-context-options-2.json');

    const opts = {
      logRequestResponseAtLogLevel: LogLevel.INFO,
      invalidRequestMsg: 'Invalid do something request',
      failedMsg: 'Failed to do something useful',
      successMsg: 'Did something useful'
    };

    const handler = apiLambdas.generateHandlerFunction(createContext, createSettings, createOptions, fn, opts);

    // Wrap the callback-based AWS Lambda handler function as a Promise returning function purely for testing purposes
    const handlerWithPromise = Promises.wrap(handler);

    // Invoke the handler function
    handlerWithPromise(event, awsContext)
      .then(response => {
        t.pass(`handler should have passed`);

        const expectedResponse = {
          statusCode: error.httpStatus,
          headers: {hdr1: 'h1', hdr3: 'h3', hdr2: 'dh2'}, // merged headers
          body: JSON.stringify({message: error.message, code: error.code, auditRef: error.auditRef, awsRequestId: awsContext.awsRequestId})
        };
        t.deepEqual(response, expectedResponse, `response must be ${JSON.stringify(expectedResponse)}`);
        t.end();
      })
      .catch(err => {
        t.fail(`handler should not have failed - ${err}`);
        t.end();
      });

  } catch (err) {
    t.fail(`handler should not have failed in try-catch - ${err}`);
    t.end();

  } finally {
    // Clean up environment
    setRegionStageAndDeleteCachedInstances(undefined, undefined);
  }
});

// =====================================================================================================================
// generateHandlerFunction simulating failure response (with useLambdaProxy true & NON-legacy parameters & custom settings)
// =====================================================================================================================

test('generateHandlerFunction simulating failure response (with useLambdaProxy true & NON-legacy parameters & NON-legacy opts & custom settings)', t => {
  try {
    // Set up environment for testing
    const region = setRegionStageAndDeleteCachedInstances('us-west-2', 'dev99');

    // Create sample AWS event and AWS context
    const event = require('./sample-lamba-proxy-request.json');
    const invokedFunctionArn = sampleInvokedFunctionArn(region, 'myLambdaFunctionName', 'dev77');
    const awsContext = sampleAwsContext('myLambdaFunctionName', '1.0.1', invokedFunctionArn, 500);

    const error = new BadRequest('Invalid request');
    error.headers = {hdr1: 'h1', hdr3: 'h3'};
    error.auditRef = uuid();

    // Create a sample function to be executed within the Lambda handler function
    const fn = sampleFunction(undefined, error);

    const context = {};
    // noinspection JSUnusedLocalSymbols
    const preSuccessCallback = function preSuccessCallback(response1, event1, context1) {
      t.fail(`### preSuccessCallback must NOT be invoked with response (${JSON.stringify(response1)})`);
    };
    const preFailureCallback = function preFailureCallback(error1, errorResponse1, event1, context1) {
      t.pass(`*** preFailureCallback must be invoked`);
      t.equal(error1, error, `preFailureCallback error1 must be ${error}`);
      t.ok(errorResponse1, `preFailureCallback errorResponse1 must exist`);
      t.equal(event1, event, `preFailureCallback event1 must be event`);
      t.equal(context1, context, `preFailureCallback context1 must be context`);
    };
    const postConfigure = function postConfigure(event1, context1) {
      t.pass(`*** postConfigure must be invoked`);
      t.equal(event1, event, `postConfigure event1 must be event`);
      t.equal(context1, context, `postConfigure context1 must be context`);

      t.equals(context1.handler.postConfigure, postConfigure, `context1.handler.postConfigure must be postConfigure`);
      t.equals(context1.handler.preSuccessCallback, preSuccessCallback, `context1.handler.preSuccessCallback must be preSuccessCallback`);
      t.equals(context1.handler.preFailureCallback, preFailureCallback, `context1.handler.preFailureCallback must be preFailureCallback`);
    };

    // Create a sample AWS Lambda handler function
    const createContext = () => context;
    const handlerSettings = {
      toErrorResponse: toCustomErrorResponse,
      postConfigure: postConfigure,
      preSuccessCallback: preSuccessCallback,
      preFailureCallback: preFailureCallback
    };
    const createSettings = () => ({handler: handlerSettings});
    const createOptions = () => require('./api-lambdas-context-options-2.json');

    const opts = {
      logRequestResponseAtLogLevel: LogLevel.INFO,
      invalidRequestMsg: 'Invalid do something request',
      failedMsg: 'Failed to do something useful',
      successMsg: 'Did something useful'
    };

    const handler = apiLambdas.generateHandlerFunction(createContext, createSettings, createOptions, fn, opts);

    // Wrap the callback-based AWS Lambda handler function as a Promise returning function purely for testing purposes
    const handlerWithPromise = Promises.wrap(handler);

    // Invoke the handler function
    handlerWithPromise(event, awsContext)
      .then(response => {
        t.pass(`handler should have ended "normally" with the error`);

        const expectedResponse = {
          statusCode: error.httpStatus,
          headers: {hdr1: 'h1', hdr3: 'h3', hdr2: 'dh2'}, // merged headers
          // body: JSON.stringify({message: error.message, code: error.code, auditRef: error.auditRef, awsRequestId: awsContext.awsRequestId})
          body: JSON.stringify({
            ErrorType: error.code,
            HttpStatus: error.httpStatus,
            AuditReferenceNumber: error.auditRef || awsContext.awsRequestId,
            Message: error.message
          })
        };
        t.deepEqual(response, expectedResponse, `response must be ${JSON.stringify(expectedResponse)}`);
        t.end();
      })
      .catch(err => {
        t.fail(`handler should not have failed - ${err}`);
        t.end();
      });

  } catch (err) {
    t.fail(`handler should not have failed in try-catch - ${err}`);
    t.end();

  } finally {
    // Clean up environment
    setRegionStageAndDeleteCachedInstances(undefined, undefined);
  }
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
  <runtime name="com.genuitec.runtime.generic.jee50"/>
  <fixed facet="wst.jsdt.web"/>
  <installed facet="java" version="1.6"/>
  <installed facet="jst.web" version="2.5"/>
  <installed facet="wst.jsdt.web" version="1.0"/>
  <installed facet="jst.web.jstl" version="1.2"/>
</faceted-project>

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace LNF.Printing
{
    public static class PdfUtility
    {
        public static byte[] Combine(IEnumerable<byte[]> files)
        {
            if (files.Count() > 1)
            {
                MemoryStream ms = new MemoryStream();
                Document doc = new Document();
                PdfCopy copy = new PdfCopy(doc, ms);
                doc.Open();
                foreach (byte[] f in files)
                    copy.AddDocument(new PdfReader(f));
                doc.Close();
                return ms.ToArray();
            }
            else if (files.Count() == 1)
                return files.ElementAt(0);
            else
                return null;
        }

        public static byte[] zCombinePdfs(List<byte[]> files)
        {
            if (files.Count > 1)
            {
                MemoryStream msOutput = new MemoryStream();

                PdfReader reader = new PdfReader(files[0]);

                Document doc = new Document();

                PdfSmartCopy copy = new PdfSmartCopy(doc, msOutput);

                doc.Open();

                for (int k = 0; k < files.Count; k++)
                {
                    for (int i = 1; i < reader.NumberOfPages + 1; i++)
                    {
                        copy.AddPage(copy.GetImportedPage(reader, i));
                        copy.FreeReader(reader);
                    }
                }

                reader.Close();
                copy.Close();
                doc.Close();

                return msOutput.ToArray();
            }
            else if (files.Count == 1)
            {
                return files[0];
            }

            return null;
        }
    }
}


text:
namespace IconGenerator
{
    using System;
    using System.Windows;
    using System.Windows.Media.Media3D;

    using HelixToolkit.Wpf;

    ///
    /// Represents a 3D visual showing a trefoil knot.
    ///
    /// <remarks>See Wikipedia.</remarks>
    public class TrefoilKnotVisual3D : ParametricSurface3D
    {
        ///
        /// Identifies the <see cref="B"/> dependency property.
        ///
        public static readonly DependencyProperty BProperty =
            DependencyProperty.Register("B", typeof(double), typeof(TrefoilKnotVisual3D), new PropertyMetadata(3d, GeometryChanged));

        ///
        /// Identifies the <see cref="C1"/> dependency property.
        ///
        public static readonly DependencyProperty C1Property =
            DependencyProperty.Register("C1", typeof(double), typeof(TrefoilKnotVisual3D), new PropertyMetadata(10d, GeometryChanged));

        ///
        /// Identifies the <see cref="C2"/> dependency property.
        ///
        public static readonly DependencyProperty C2Property =
            DependencyProperty.Register("C2", typeof(double), typeof(TrefoilKnotVisual3D), new PropertyMetadata(2d, GeometryChanged));

        ///
        /// Gets or sets the b parameter. The default is 3.
        ///
        /// <value>The b value.</value>
        public double B
        {
            get { return (double)this.GetValue(BProperty); }
            set { this.SetValue(BProperty, value); }
        }

        ///
        /// Gets or sets the c1 parameter. The default is 10.
        ///
        /// <value>The c1 value.</value>
        public double C1
        {
            get { return (double)this.GetValue(C1Property); }
            set { this.SetValue(C1Property, value); }
        }

        ///
        /// Gets or sets the c2 parameter. The default is 2.
        ///
        /// <value>The c2 value.</value>
        public double C2
        {
            get { return (double)this.GetValue(C2Property); }
            set { this.SetValue(C2Property, value); }
        }

        ///
        /// Evaluates the surface at the specified u,v parameters.
        ///
        /// <param name="u">The u parameter.</param>
        /// <param name="v">The v parameter.</param>
        /// <param name="uv">The texture coordinates.</param>
        /// <returns>The evaluated <see cref="T:System.Windows.Media.Media3D.Point3D" />.</returns>
        protected override Point3D Evaluate(double u, double v, out Point uv)
        {
            u *= 4 * Math.PI;
            v = (v - 0.5) * 2 * Math.PI;

            double b = this.B;

            double cosu = Math.Cos(u);
            double sinu = Math.Sin(u);
            double cosv = Math.Cos(v);
            double sinv = Math.Sin(v);

            double c1 = this.C1;
            double c2 = this.C2;
            double c3 = c1 * (Math.Cos(b * u / 2) + b) / 4;
            double c4 = -c3 * sinu - b * c1 * Math.Sin(b * u / 2) * cosu / 8;
            double c5 = c3 * cosu - b * c1 * Math.Sin(b * u / 2) * sinu / 8;
            double c6 = (b * c3 * Math.Cos(Math.Sin(b * u / 2)) * Math.Cos(b * u / 2)) / 2 - (b * c1 * Math.Sin(Math.Sin(b * u / 2)) * Math.Sin(b * u / 2)) / 8;
            double c7 = Math.Sqrt(c4 * c4 + c5 * c5);
            double c8 = Math.Sqrt(c4 * c4 + c5 * c5 + c6 * c6);

            var x = c3 * cosu + (c2 * (c8 * cosv * c5 - sinv * c4 * c6) / (c7 * c8));
            var y = c3 * sinu - (c2 * (c8 * cosv * c4 + sinv * c5 * c6) / (c7 * c8));
            var z = c3 * Math.Sin(Math.Sin(b * u / 2)) + (c2 * sinv * c7 / c8);

            uv = new Point(u, v);
            return new Point3D(x, y, z);
        }
    }
}


text: this is not a valid javascript file


text:
<?php
$this->pageTitle=t('Product details');
$this->widget('cmswidgets.ModelViewWidget',array('model_name'=>'Product'));
?>


text:
[World Wide Web Consortium][]

[World Wide Web Consortium]: http://www.w3.org/


text:
/* global clearTimeout, FormData, btoa */

(function() {
  'use strict';

  var MorpheuzUtil = require("./morpheuzUtil");
  var MorpheuzConfig = require("./morpheuzConfig");
  var MorpheuzCommon = require("./morpheuzCommon");

  var MorpheuzAjax = {};

  /*
   * Standard Post Ajax call routine
   */
  MorpheuzAjax.makePostAjaxCall = function(url, msg, resp) {
    var tout = setTimeout(function() {
      resp({
        "status" : 0,
        "errors" : [ "timeout" ]
      });
    }, MorpheuzConfig.mConst().timeout);
    var req = new XMLHttpRequest();
    req.open("POST", url, true);
    req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    req.timeout = MorpheuzConfig.mConst().timeout;
    req.ontimeout = function() {
      resp({
        "status" : 0,
        "errors" : [ "timeout" ]
      });
      clearTimeout(tout);
    };
    req.onload = function() {
      if (req.readyState === 4 && req.status === 200) {
        clearTimeout(tout);
        var result = JSON.parse(req.responseText);
        resp(result);
      } else if (req.readyState === 4 && (req.status >= 400 && req.status < 500)) {
        clearTimeout(tout);
        var result2 = JSON.parse(req.responseText);
        resp(result2);
      } else if (req.readyState === 4 && (req.status === 500)) {
        clearTimeout(tout);
        resp({
          "status" : 0,
          "errors" : [ "500 error" ]
        });
      }
    };
    req.send(msg);
  };

  /*
   * Standard Get Ajax call routine
   */
  MorpheuzAjax.makeGetAjaxCall = function(url, resp) {
    var tout = setTimeout(function() {
      resp({
        "status" : 0,
        "errors" : [ "timeout" ]
      });
    }, MorpheuzConfig.mConst().timeout);
    var req = new XMLHttpRequest();
    req.open("GET", url, true);
    req.timeout = MorpheuzConfig.mConst().timeout;
    req.ontimeout = function() {
      resp({
        "status" : 0,
        "errors" : [ "timeout" ]
      });
      clearTimeout(tout);
    };
    req.onload = function() {
      if (req.readyState === 4 && req.status === 200) {
        clearTimeout(tout);
        resp({
          "status" : 1,
          "data" : req.responseText
        });
      } else if (req.readyState === 4 && (req.status >= 300 && req.status <= 599)) {
        clearTimeout(tout);
        resp({
          "status" : 0,
          "errors" : [ req.status, MorpheuzCommon.nvl(req.responseText, "No Msg") ]
        });
      }
    };
    req.send();

  };

  /*
   * If LIFX values are set, this function will turn on all the lights with a
   * custom fade-in time
   */
  MorpheuzAjax.turnLifxLightsOn = function() {

    // Find out config information
    var token = MorpheuzUtil.getWithDef("lifx-token", "");
    var fadeInTime = MorpheuzUtil.getWithDef("lifx-time", MorpheuzConfig.mConst().lifxTimeDef);

    // Escape if not configured
    if (token === "" || fadeInTime === "") {
      console.log("lifx control deactivated");
      return;
    }

    var url = "https://api.lifx.com/v1beta1/lights/all/power";
    var method = "PUT";
    var data = new FormData();

    data.append('state', 'on');
    data.append('duration', fadeInTime);

    var req = new XMLHttpRequest();
    req.open(method, url, true);
    req.setRequestHeader("Authorization", "Basic " + btoa(token + ":" + ""));
    req.withCredentials = "true";
    req.send(data);

    req.onload = function() {
      // response
    };

  };

  /*
   * Generic ajax support function (used by Maker and Hue bulb interface)
   */
  MorpheuzAjax.makeAjaxCall = function(mode, url, toTime, dataout, resp) {
    var tout = setTimeout(function() {
      resp({
        "status" : 0,
        "errors" : [ "timeout" ]
      });
    }, toTime);
    var req = new XMLHttpRequest();
    req.open(mode, url, true);
    req.setRequestHeader("Content-Type", "application/json");
    req.timeout = toTime;
    req.ontimeout = function() {
      resp({
        "status" : 0,
        "errors" : [ "timeout" ]
      });
      clearTimeout(tout);
    };
    req.onload = function() {
      if (req.readyState === 4 && req.status === 200) {
        clearTimeout(tout);
        resp({
          "status" : 1,
          "data" : safeJSONparse(req.responseText)
        });
      } else if (req.readyState === 4 && (req.status >= 300 && req.status <= 599)) {
        clearTimeout(tout);
        resp({
          "status" : 0,
          "errors" : [ req.status, MorpheuzCommon.nvl(req.responseText, "No Msg") ]
        });
      }
    };
    if (dataout === "") {
      req.send();
    } else {
      req.send(dataout);
    }

  };

  /*
   * JSON parse with built in safety - like if the message isn't bloody json
   */
  function safeJSONparse(txt) {
    try {
      return JSON.parse(txt);
    } catch (err) {
      return txt;
    }
  }

  module.exports = MorpheuzAjax;

}());


text:
'''
The python file uses pyopencl to do the compute intense weighted and masked convolve op.
'''

import sys
import pyopencl as cl
import numpy as np
import warnings
import os
import logging
import time

# Filename containing the src of the OpenCL kernel
CONVOLVE_WITH_WEIGHTING_CL_KERNEL_FILENAME = os.path.dirname(__file__) + "/convolve_with_weighting.cl"

class PatternAtROIBorderWarning(UserWarning):

    """
    A warning that is issued when the PatternFinder retuns the best match
    coordinates at the border of the ROI. This indicates that the true global
    minimal value might be outside of the ROI.
    """

def idx_array_split(length, n_parts):
    """
    Helper that splits the number `length` into `n_parts` and returns a list
    of indices that can be used to index an array dimension of `length`.

    Similar (adapted from) numpy.split_array.
    """
    parts = []
    n_each_section, extras = divmod(length, n_parts)
    section_sizes = ([0] +
                     extras * [n_each_section + 1] +
                     (n_parts - extras) * [n_each_section])
    div_points = np.array(section_sizes).cumsum()
    for i in range(n_parts):
        st = div_points[i]
        end = div_points[i + 1]
        parts.append(end - st)
    return parts

class PatternFinder():

    """Find a given pattern in an image (OpenCL accelerated implementation)"""

    def __init__(self, opencl_queue=None, partitions=1):
        """
        Create a new PatternFinder object.

        Optionally providing an OpenCL command queue and partitions to limit
        the size one signle kernel has to compute.

        -   `opencl_queue`: The command queue will default to the last platform
             and the last device. Usually that is the GPU.
             You can assign this your self

                 import pyopencl as cl
                 platform = cl.get_platforms()[i]
                 device = platform.get_devices[j]
                 queue = cl.CommandQueue(cl.Context([device]))  # , properties=cl.command_queue_properties.PROFILING_ENABLE)

        -   `partitions`: Split the image in this many parts (default=1) in
            order to keep the kernel runtime shorter for buggy nVidia-Windows
            driver. Usually, there is no speed-up when using more partitions
            for large ROIs as the GPU is already fully busy because each pixel
            in the ROI is computed in parallel. However, if you have fewer
            pixels in your ROI than the GPU can handle parallel executions,
            theoretically you might gain a small speed-up with higher
            `partitions` number
            If you experience GPU driver crashes, try to set this number
            higher, e.g. 10 is a good guess.
        """
        self.logger = logging.getLogger("PatternFinder")
        self.logger.level = logging.DEBUG

        self.partitions = partitions
        assert partitions >= 1, "partitions must be >= 1"

        # Create an OpenCL context and queue, if None was given
        if opencl_queue is None:
            # In my observation the last device in the last platform
            # (which is mostly just one) is the powerful GPU
            self.ctx = cl.Context([cl.get_platforms()[-1].get_devices()[-1]])  # , properties=cl.command_queue_properties.PROFILING_ENABLE)
            self.queue = cl.CommandQueue(self.ctx)
            self.logger.info(self.ctx)
        else:
            self.ctx = opencl_queue.context
            self.queue = opencl_queue

        if not self.queue.device.get_info(cl.device_info.IMAGE_SUPPORT):
            raise Exception("OpenCL device {} does not support image".format(self.ctx.device))

        # The Sampler for how OpenCL accesses the images (pixel coordinates, no interpolation)
        self.sampler_gpu = cl.Sampler(self.ctx,
                                      False,
                                      cl.addressing_mode.CLAMP_TO_EDGE,
                                      cl.filter_mode.NEAREST)

        # Read-in and compile the OpenCL Kernel-Program
        with open(CONVOLVE_WITH_WEIGHTING_CL_KERNEL_FILENAME, 'r') as f:
            self._opencl_prg = cl.Program(self.ctx, f.read()).build()

    def transfrom_target(self, transform_matrix):
        raise NotImplemented

    def transform_image(self, transform_matrix):
        raise NotImplemented

    def _upload_image(self, image):
        assert image.max() <= 1.0

        # Check the number of channels in the image
        if image.ndim == 2:
            num_channels = 1
        else:
            if 'nvidia' in self.ctx.devices[0].vendor.lower() and image.shape[2] == 3:
                # This is a hack for nVidia, as we believe and found so
                # far for various GeFoce / Tesla cards that the nvidia OpenCL
                # implementation sucks. Reporting an out-of-resources error when
                # trying to upload an RGB three channel image to the GPU or silently failing.
                # Quite counterintuitively adding an unneeded fourth channel
                # makes the out-of-resources error go away. FIXME if you can.
                tmp = image
                image = np.ones((tmp.shape[0], tmp.shape[1], 4))
                num_channels = 4
                image[:, :, :3] = tmp[:]
                self.logger.info("nvidia Hack for RGB images adding empty A channel on device " + str(self.ctx.devices[0]))
            else:
                num_channels = image.shape[2]

        # Tell OpenCL to copy the image into device memory
        image_gpu = cl.image_from_array(self.ctx, image.astype(np.float32),
                                        num_channels=num_channels, mode="r")
        return image_gpu

    def set_pattern(self, pattern):
        """
        Assign and upload a pattern image to the GPU for the find method.
        """
        # Check that pattern is an RGBA image
        assert pattern.ndim == 3 and pattern.shape[2] == 4, "pattern has to be a 4-channel RGBA image."
        assert pattern.max() <= 1.0

        if pattern.shape[0] % 2 == 0 or pattern.shape[1] % 2 == 0:
            warnings.warn("For best results, pattern should have an odd "
                          "number of columns/rows but its shape is: {}".format(pattern.shape),
                          stacklevel=2)

        self._pattern_gpu = self._upload_image(pattern)

    property(fset=set_pattern, doc=set_pattern.__doc__)

    def set_image(self, image):
        """
        Assign and upload an image to the GPU for the find method.
        """
        self._image_gpu = self._upload_image(image)

    property(fset=set_image, doc=set_image.__doc__)

    def find(self, pattern=None, image=None, roi=None):
        """
        Find the position where `pattern` is most likely in `image` in the ROI.

        This is a GPU implemented (OpenCL) brute force (global) search.

        You can vastly improve the runtime by providing a region-of-interest
        (ROI) in image coordinates where to look for the pattern.

        The position of the *center* of the pattern is returned and *NOT* the
        top-left corner. This is helpful if your pattern is centered.

        If you need to call this method multiple times, it might be advied to
        set the `pattern` and/or the `image` before with `set_image`/`set_pattern`.

        -   `pattern`: A numpy 2d image with a shape (columns, rows, 4) where
            the last color band is the alpha channel (0.0 is transparent).
            Optional, if the property `.pattern` has been set.

        -   `image`: A numpy 2d image with a shape (columns, rows, 3).
            Optional, if the property `.image` has been set.

        -   `roi`: Optional region-of-interest in zero-based image coordinates.
             This is a fourh-tuple `(start_row, start_col, row_end, col_end)`
             where the start row/cols are included but row/col_end are
             excluded.

        Warns, if the minimum is at the border of the ROI as that hints to the
        true minimum being outside of the ROI.

        Returns a three-tuple of the convoluted ROI, the coordinates in the
        image coordinate system and the minimal value at the minimum.

        """
        time_start = time.time()

        if image is not None:
            self.set_image(image)

        if pattern is not None:
            self.set_pattern(pattern)

        try:
            image_gpu = self._image_gpu
            pattern_gpu = self._pattern_gpu
        except AttributeError:
            raise Exception("No image or pattern available. "
                            "Forgot to provide these or call set_image/set_pattern before?")

        # Compute the Region Of Interest if not given
        # (row_start, col_start, row_end, col_end)
        # Including start row/cols but without row/col_end
        if roi is None:
            roi = (0, 0, image_gpu.shape[1], image_gpu.shape[0])

        partitions = min(pattern_gpu.shape[1], self.partitions)
        # split the image into self.partitions parts but not more than rows in the image
        parts = idx_array_split(length=pattern_gpu.shape[1], n_parts=partitions)

        output_final = np.zeros((roi[2]-roi[0], roi[3]-roi[1]), dtype=np.float32)

        # For each partition create one output array (and one that is copied to the GPU)
        outputs = [np.zeros_like(output_final) for i in range(partitions)]
        outputs_gpu = [cl.Buffer(self.ctx, cl.mem_flags.WRITE_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf=out)
                       for out in outputs]

        # partitions split the pattern in parts. We compute init the start row:
        pattern_start_row = 0
        # Context manager that automatically finishes the queue at the end
        with self.queue as queue:
            for part, out_gpu, out in zip(parts, outputs_gpu, outputs):
                cl_op = self._opencl_prg.convolve_image(queue,
                                                        output_final.shape,  # --> row, col == {get_global_id(0), get_global_id(1)} in kernel
                                                        None,  # no local workgroups
                                                        image_gpu, pattern_gpu, out_gpu,
                                                        self.sampler_gpu,
                                                        np.array([roi[0], roi[1]], dtype=np.int32),  # start_row, start_col in image
                                                        np.int32(pattern_start_row),
                                                        np.int32(pattern_start_row + part))
                # For the next round, we have to adapt the start column
                # by the height of the current part
                pattern_start_row += part
                # Start to copy back right after convolve finished (non-blocking)
                cl.enqueue_copy(queue, out, out_gpu,
                                wait_for=[cl_op], is_blocking=False)

        assert pattern_start_row == pattern_gpu.shape[1], ("${}".format(pattern_gpu.height, pattern_gpu.height, pattern_start_row))

        # Add all the outputs together
        for i in range(partitions):
            output_final += outputs[i]

        idx = np.array(np.unravel_index(output_final.argmin(), output_final.shape))

        # Check and warn if minimal value is at border of output_final
        if (idx[0] in (0, output_final.shape[0] - 1) or idx[1] in (0, output_final.shape[1] - 1)):
            warnings.warn("PatternFinder: Minimal value at border of ROI! "
                          "This hints at a too small ROI. Actual minimum "
                          "might be outside of the ROI.",
                          PatternAtROIBorderWarning)

        self.logger.debug("Execution PatternFinder.find took %f ms",
                          (time.time()-time_start) / 1000)
        return output_final, idx + roi[0:2], output_final[idx[0], idx[1]]


text:
import { default as React, Component } from "react";

import { GoogleMap, Marker, InfoWindow } from "react-google-maps";

/*
 * https://developers.google.com/maps/documentation/javascript/examples/event-closure
 *
 * Add  to your HTML to provide google.maps reference
 */
export default class ClosureListeners extends Component {

  state = {
    markers: [],
  }

  componentWillMount() {
    const southWest = new google.maps.LatLng(-31.203405, 125.244141);
    const northEast = new google.maps.LatLng(-25.363882, 131.044922);

    const lngSpan = northEast.lng() - southWest.lng();
    const latSpan = northEast.lat() - southWest.lat();

    const markers = [];
    for (let i = 0; i < 5; i++) {
      const position = new google.maps.LatLng(
        southWest.lat() + latSpan * Math.random(),
        southWest.lng() + lngSpan * Math.random()
      );
      markers.push({
        position,
        content: `This is the secret message`.split(` `)[i],
        showInfo: false,
      });
    }

    this.setState({
      markers,
    });
  }

  handleMarkerClick(targetMarker) {
    this.setState({
      markers: this.state.markers.map(marker => {
        if (marker === targetMarker) {
          return {
            ...marker,
            showInfo: true,
          };
        }
        return marker;
      }),
    });
  }

  handleCloseclick(targetMarker) {
    this.setState({
      markers: this.state.markers.map(marker => {
        if (marker === targetMarker) {
          return {
            ...marker,
            showInfo: false,
          };
        }
        return marker;
      }),
    });
  }

  renderInfoWindow(ref, marker) {
    const onCloseclick = this.handleCloseclick.bind(this, marker);

    if (Math.random() > 0.5) {
      // Normal version: Pass string as content
      return (
        <InfoWindow
          key={`${ref}_info_window`}
          content={marker.content}
          onCloseclick={onCloseclick}
        />
      );
    } else {
      // "react-google-maps" extended version: Pass ReactElement as content
      return (
        <InfoWindow
          key={`${ref}_info_window`}
          onCloseclick={onCloseclick}
        >

            {marker.content}

            The contents of this InfoWindow are actually ReactElements.

        </InfoWindow>
      );
    }
  }

  render() {
    const { markers } = this.state;

    return (
      <GoogleMap
        containerProps={{
          ...this.props,
          style: {
            height: `100%`,
          },
        }}
        defaultZoom={4}
        defaultCenter={new google.maps.LatLng(-25.363882, 131.044922)}
      >
        {markers.map((marker, index) => {
          const ref = `marker_${index}`;
          const onClick = () => this.handleMarkerClick(marker);

          return (
            <Marker
              key={ref}
              ref={ref}
              position={marker.position}
              title={(index + 1).toString()}
              onClick={onClick}
            >
              {marker.showInfo ? this.renderInfoWindow(ref, marker) : null}
            </Marker>
          );
        })}
      </GoogleMap>
    );
  }
}


text:
"use strict";

var xml = require('xml'),
    serializeIdentified = require('./serializeIdentified'),
    serializeLocation = require('./serializeLocation');

module.exports = function serializeSequenceConstraint(sbolDocument, xmlAttribsRef, sequenceConstraint) {

    return serializeIdentified(sbolDocument, xmlAttribsRef, sequenceConstraint, 'sbol:SequenceConstraint', [

        { 'sbol:restriction': { _attr: { 'rdf:resource': sequenceConstraint.restriction }}},
        { 'sbol:subject': { _attr: { 'rdf:resource': sequenceConstraint.subject.uri?sequenceConstraint.subject.uri:sequenceConstraint.subject }}},
        { 'sbol:object': { _attr: { 'rdf:resource': sequenceConstraint.object.uri?sequenceConstraint.object.uri:sequenceConstraint.object }}}
    ]);
}


text:
'use strict';

angular.module('socialMediaAnalysisApp').controller(
		'SentimentAnalysisController', function($scope, $http) {

			$scope.searchKeyword = '';

			$scope.sentimentAnalysisResultsValues = [];

			$scope.sentimentAnalysisResultsLabels = [];

			$scope.performSentimentAnalysis = function() {
				$http.get('/social-media-analysis/v1.0/sentiments', {
					params : {
						'keyword' : $scope.searchKeyword
					}
				}).then(function(result) {
					$scope.prepareChartModels(result.data);
				})
			};

			$scope.prepareChartModels = function(sentimentAnalysisResults) {

				$scope.sentimentAnalysisResultsValues = [];
				$scope.sentimentAnalysisResultsLabels = [];

				angular.forEach(sentimentAnalysisResults, function(value, key) {
					$scope.sentimentAnalysisResultsLabels.push(key);
					$scope.sentimentAnalysisResultsValues.push(value);
				});
			};

		});


text:
Aria.classDefinition({
    $classpath : "test.aria.widgets.wai.input.radiobutton.initiallyDisabled.InitiallyDisabledRadioButtonsJawsTestCase",
    $extends : "aria.jsunit.JawsTestCase",
    $constructor : function () {
        this.$JawsTestCase.constructor.call(this);
        this.setTestEnv({
            template : "test.aria.widgets.wai.input.radiobutton.initiallyDisabled.InitiallyDisabledRadioButtonsTpl"
        });
        this.noiseRegExps.push(/(edit|text)/i);
    },
    $prototype : {
        runTemplateTest : function () {

            this.synEvent.execute([
                ["click", this.getElementById("tf1")], ["pause", 1000],
                ["type", null, "[tab]"], ["pause", 1000],
                ["type", null, "[down]"], ["pause", 1000],
                ["type", null, "[tab]"], ["pause", 1000],
                ["type", null, "[down]"], ["pause", 1000],
                ["type", null, "[down]"], ["pause", 1000],
                ["type", null, "[up]"], ["pause", 1000],
                ["type", null, "[<shift>][tab][>shift<]"], ["pause", 1000]
            ], {
                fn: function () {
                    this.assertJawsHistoryEquals([
                        "List box Automatic radio button checked",
                        "To change the selection press Up or Down Arrow.",
                        "List box Manual radio button checked",
                        "To change the selection press Up or Down Arrow.",
                        "List box Manual option 1 radio button checked",
                        "To change the selection press Up or Down Arrow.",
                        "List box Manual option 2 radio button checked",
                        "To change the selection press Up or Down Arrow.",
                        "List box Manual option 4 radio button checked",
                        "To change the selection press Up or Down Arrow.",
                        "List box Manual option 2 radio button checked",
                        "To change the selection press Up or Down Arrow.",
                        "List box Manual radio button checked",
                        "To change the selection press Up or Down Arrow."
                    ].join("\n"), this.end);
                },
                scope: this
            });
        }
    }
});


text:
import json
import logging
from datetime import datetime, timezone

from django.db import transaction
from pydantic import ValidationError as PydanticValidationError
from rest_framework.exceptions import ValidationError

from hs_core.hydroshare.hs_bagit import save_resource_metadata_xml

from hs_file_types.utils import ingest_logical_file_metadata
from hs_rest_api2.serializers import ResourceMetadataInForbidExtra

from hsmodels.schemas import ResourceMetadata, load_rdf, rdf_graph

logger = logging.getLogger(__name__)

def _get_in_schema(out_schema):
    """
    Gets the parent schema class and subclasses it to forbid extra parameters

    :params out_schema: A hsmodel schema

    :returns: A new schema class
    """
    in_schema = out_schema.__bases__[0]

    class IncomingForbid(in_schema):
        class Config:
            extra = "forbid"

    return IncomingForbid

def load_metadata_from_file(istorage, file_with_path):
    """
    Loads a rdf/xml metadata file to a hsmodel pydantic schema instance

    Parameters:
    :param istorage: An irods storage object
    :param file_with_path: The path to the rdf/xml metadata file

    :returns: hsmodel schema instance
    """
    with istorage.open(file_with_path) as f:
        metadata = load_rdf(f.read())
        return metadata

def resource_metadata(resource):
    """
    Loads the resource rdf/xml file to a hsmodel pydantic schema instance

    Parameters:
    :param resource: A resource django model instance

    :returns: ResourceMetadata schema instance
    """
    file_with_path = resource.scimeta_path
    istorage = resource.get_irods_storage()
    resource.update_relation_meta()
    metadata_dirty = resource.getAVU('metadata_dirty')
    if metadata_dirty:
        save_resource_metadata_xml(resource)
    return load_metadata_from_file(istorage, file_with_path)

def resource_metadata_json_loads(resource):
    """
    Returns the resource metadata as a JSON dict
    """
    return json.loads(resource_metadata(resource).json())

def ingest_resource_metadata(resource, incoming_metadata):
    """
    Writes resource metadata json to the resource rdf/xml.

    Parameters:
    :param resource: A resource django model instance
    :param incoming_metadata: JSON dictionary of resource metadata

    :returns: ResourceMetadata schema instance

    :raises: ValidationError when incoming_metadata does not pass validation
    """
    r_md = resource_metadata(resource).dict()
    try:
        incoming_r_md = ResourceMetadataInForbidExtra(**incoming_metadata)
    except PydanticValidationError as e:
        raise ValidationError(e)
    # merge existing metadata with incoming, incoming overrides existing
    merged_metadata = {**r_md,
                       **incoming_r_md.dict(exclude_defaults=True),
                       "modified": datetime.now(timezone.utc).isoformat()}
    res_metadata = ResourceMetadata(**merged_metadata)

    graph = rdf_graph(res_metadata)
    try:
        with transaction.atomic():
            resource.metadata.delete_all_elements()
            resource.metadata.ingest_metadata(graph)
    except:
        logger.exception(f"Error processing resource metadata file for resource {resource.short_id}")
        raise
    save_resource_metadata_xml(resource)
    return json.loads(res_metadata.json())

def ingest_aggregation_metadata(resource, incoming_metadata, file_path):
    """
    Writes resource metadata json to the resource rdf/xml.

    Parameters:
    :param resource: A resource django model instance
    :param incoming_metadata: JSON dictionary of resource metadata

    :returns: ResourceMetadata schema instance

    :raises: ValidationError when incoming_metadata does not pass validation
    """
    aggregation = resource.get_aggregation_by_name(file_path)
    if aggregation.metadata.is_dirty:
        aggregation.create_aggregation_xml_documents()

    # read existing metadata from file
    agg_md = load_metadata_from_file(resource.get_irods_storage(), aggregation.metadata_file_path)

    agg_md_dict = agg_md.dict()

    # get schema classes
    out_schema = agg_md.__class__
    in_schema = _get_in_schema(out_schema)

    # validate incoming metadata against the schema
    try:
        incoming_md = in_schema(**incoming_metadata)
    except PydanticValidationError as e:
        raise ValidationError(e)

    # merge existing metadata with incoming, incoming overrides existing
    incoming_dict = {**incoming_md.dict(exclude_defaults=True)}
    existing_dict = {**agg_md_dict}
    merged_metadata = {**existing_dict,
                       **incoming_dict}

    agg_metadata = out_schema(**merged_metadata)
    graph = rdf_graph(agg_metadata)

    # write the updated metadata back to file
    ingest_logical_file_metadata(graph, resource)
    aggregation.refresh_from_db()
    return json.loads(agg_metadata.json())

def aggregation_metadata_json_loads(resource, file_path):
    """
    Returns the aggregation metadata as a JSON dict
    """
    agg = resource.get_aggregation_by_name(file_path)
    if agg.metadata.is_dirty:
        agg.create_aggregation_xml_documents()
    agg_md = load_metadata_from_file(resource.get_irods_storage(), agg.metadata_file_path)
    return json.loads(agg_md.json())


text:
package com.oracle.truffle.llvm.test;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import com.oracle.truffle.llvm.test.AbstractMainArgsTestBase.ProgramWithMainArgs;
import com.oracle.truffle.llvm.test.ShootoutsTestSuite.Benchmark;
import com.oracle.truffle.llvm.tools.Clang.ClangOptions;
import com.oracle.truffle.llvm.tools.Clang.ClangOptions.OptimizationLevel;

@RunWith(Parameterized.class)
public class ShootoutsTestSuite extends AbstractMainArgsTestBase<Benchmark> {

    /**
     * TODOS. knucletoide folder: include folder

     * some benchmarks only compile with higher optimization levels

     * cint meteor: C sort

     * nbody: also escaping function pointers

     * pidigits: gmp

     * regexdna: does not terminate

     * revcomp: does not terminate
     */
    enum Benchmark implements ProgramWithMainArgs {

        C_BINARY_TREES_1("binarytrees/binarytrees.gcc-2.gcc.c", 12),
        C_BINARY_TREES_2("binarytrees/binarytrees.gcc.c", 12),
        C_FANNKUCHREDUX_1("fannkuchredux/fannkuchredux.cint.c", 9),
        C_FANNKUCHREDUX_2("fannkuchredux/fannkuchredux.gcc.c", 9),
        C_FASTA1("fasta/fasta.cint.c", 100),
        C_FASTA2("fasta/fasta.gcc-4.gcc.c", 100),
        C_FASTA3("fasta/fasta.gcc-5.gcc.c", 100),
        C_FASTA_REDUX1("fastaredux/fastaredux.gcc-2.gcc.c"),
        C_FASTA_REDUX2("fastaredux/fastaredux.gcc-3.gcc.c"),
        C_MANDELBROT1("mandelbrot/mandelbrot.cint-2.cint.c", 500),
        C_MANDELBROT2("mandelbrot/mandelbrot.gcc-2.gcc.c", 500),
        C_MANDELBROT3("mandelbrot/mandelbrot.gcc-8.gcc.c", 500),
        C_MANDELBROT4("mandelbrot/mandelbrot.gcc-9.gcc.c", 500),
        C_NBODY1("nbody/nbody.cint.c", 10),
        C_SPECTRALNORM1("spectralnorm/spectralnorm.cint.c", 150),
        C_SPECTRALNORM2("spectralnorm/spectralnorm.gcc-2.gcc.c", 150),
        C_PIDIGTS("pidigits/pidigits.cint-4.cint.c", 10000),
        C_PIDIGITS2("pidigits/pidigits.gcc.c", 10000);

        private File file;
        private String[] args;
        private Set<TestCaseFlag> flags = new HashSet<>();

        Benchmark(String path, Object... arg) {
            this.file = new File(LLVMPaths.BENCHMARK_GAME_SUITE, path);
            String[] convertedArgs = new String[arg.length];
            for (int i = 0; i < arg.length; i++) {
                convertedArgs[i] = arg[i].toString();
            }
            this.args = convertedArgs;
        }

        @Override
        public File getFile() {
            return file;
        }

        @Override
        public List<String> getMainArgs() {
            return Arrays.asList(args);
        }

        @Override
        public Set<TestCaseFlag> getFlags() {
            return flags;
        }
    }

    public ShootoutsTestSuite(Benchmark program) {
        super(program);
    }

    @Parameterized.Parameters
    public static List<Benchmark[]> getTestFiles() {
        return getTestFiles(Arrays.asList(Benchmark.values()));
    }

    @Override
    protected TestCaseFiles getTestCaseFiles(Benchmark prog) {
        return TestHelper.compileToLLVMIRWithClang(prog.getFile(),
                        TestHelper.getTempLLFile(prog.getFile(), "_main"), prog.getFlags(),
                        ClangOptions.builder().optimizationLevel(OptimizationLevel.O1));
    }

    @Override
    @Test
    public void test() throws Throwable {
        super.test();
    }

}


text:
"""Tests for the elpy.server module"""

import os
import tempfile
import unittest

import mock

from elpy import rpc
from elpy import server
from elpy.tests import compat
from elpy.tests.support import BackendTestCase
import elpy.refactor

class ServerTestCase(unittest.TestCase):
    def setUp(self):
        self.srv = server.ElpyRPCServer()

class BackendCallTestCase(ServerTestCase):
    def assert_calls_backend(self, method):
        with mock.patch("elpy.server.get_source") as get_source:
            with mock.patch.object(self.srv, "backend") as backend:
                get_source.return_value = "transformed source"

                getattr(self.srv, method)("filename", "source", "offset")

                get_source.assert_called_with("source")
                getattr(backend, method).assert_called_with(
                    "filename", "transformed source", "offset"
                )

class TestInit(ServerTestCase):
    def test_should_not_select_a_backend_by_default(self):
        self.assertIsNone(self.srv.backend)

class TestRPCEcho(ServerTestCase):
    def test_should_return_arguments(self):
        self.assertEqual(("hello", "world"),
                         self.srv.rpc_echo("hello", "world"))

class TestRPCInit(ServerTestCase):
    @mock.patch("elpy.jedibackend.JediBackend")
    def test_should_set_project_root(self, JediBackend):
        self.srv.rpc_init({"project_root": "/project/root"})

        self.assertEqual("/project/root", self.srv.project_root)

    @mock.patch("elpy.jedibackend.JediBackend")
    def test_should_initialize_jedi(self, JediBackend):
        self.srv.rpc_init({"project_root": "/project/root"})

        JediBackend.assert_called_with("/project/root")

    @mock.patch("elpy.jedibackend.JediBackend")
    def test_should_use_jedi_if_available(self, JediBackend):
        JediBackend.return_value.name = "jedi"

        self.srv.rpc_init({"project_root": "/project/root"})

        self.assertEqual("jedi", self.srv.backend.name)

    @mock.patch("elpy.jedibackend.JediBackend")
    def test_should_use_none_if_nothing_available(
            self, JediBackend):
        JediBackend.return_value.name = "jedi"
        old_jedi = server.jedibackend
        server.jedibackend = None

        try:
            self.srv.rpc_init({"project_root": "/project/root"})
        finally:
            server.jedibackend = old_jedi

        self.assertIsNone(self.srv.backend)

class TestRPCGetCalltip(BackendCallTestCase):
    def test_should_call_backend(self):
        self.assert_calls_backend("rpc_get_calltip")

    def test_should_handle_no_backend(self):
        self.srv.backend = None
        self.assertIsNone(self.srv.rpc_get_calltip("filname", "source",
                                                   "offset"))

class TestRPCGetCompletions(BackendCallTestCase):
    def test_should_call_backend(self):
        self.assert_calls_backend("rpc_get_completions")

    def test_should_handle_no_backend(self):
        self.srv.backend = None
        self.assertEqual([],
                         self.srv.rpc_get_completions("filname", "source",
                                                      "offset"))

    def test_should_sort_results(self):
        with mock.patch.object(self.srv, 'backend') as backend:
            backend.rpc_get_completions.return_value = [
                {'name': '_e'},
                {'name': '__d'},
                {'name': 'c'},
                {'name': 'B'},
                {'name': 'a'},
            ]
            expected = list(reversed(backend.rpc_get_completions.return_value))

            actual = self.srv.rpc_get_completions("filename", "source",
                                                  "offset")

            self.assertEqual(expected, actual)

    def test_should_uniquify_results(self):
        with mock.patch.object(self.srv, 'backend') as backend:
            backend.rpc_get_completions.return_value = [
                {'name': 'a'},
                {'name': 'a'},
            ]
            expected = [{'name': 'a'}]

            actual = self.srv.rpc_get_completions("filename", "source",
                                                  "offset")

            self.assertEqual(expected, actual)

class TestRPCGetCompletionDocs(ServerTestCase):
    def test_should_call_backend(self):
        with mock.patch.object(self.srv, "backend") as backend:
            self.srv.rpc_get_completion_docstring("completion")

            (backend.rpc_get_completion_docstring
             .assert_called_with("completion"))

    def test_should_handle_no_backend(self):
        self.srv.backend = None
        self.assertIsNone(self.srv.rpc_get_completion_docstring("foo"))

class TestRPCGetCompletionLocation(ServerTestCase):
    def test_should_call_backend(self):
        with mock.patch.object(self.srv, "backend") as backend:
            self.srv.rpc_get_completion_location("completion")

            (backend.rpc_get_completion_location
             .assert_called_with("completion"))

    def test_should_handle_no_backend(self):
        self.srv.backend = None
        self.assertIsNone(self.srv.rpc_get_completion_location("foo"))

class TestRPCGetDefinition(BackendCallTestCase):
    def test_should_call_backend(self):
        self.assert_calls_backend("rpc_get_definition")

    def test_should_handle_no_backend(self):
        self.srv.backend = None
        self.assertIsNone(self.srv.rpc_get_definition("filname", "source",
                                                      "offset"))

class TestRPCGetAssignment(BackendCallTestCase):
    def test_should_call_backend(self):
        self.assert_calls_backend("rpc_get_assignment")

    def test_should_handle_no_backend(self):
        self.srv.backend = None
        self.assertIsNone(self.srv.rpc_get_assignment("filname", "source",
                                                      "offset"))

class TestRPCGetDocstring(BackendCallTestCase):
    def test_should_call_backend(self):
        self.assert_calls_backend("rpc_get_docstring")

    def test_should_handle_no_backend(self):
        self.srv.backend = None
        self.assertIsNone(self.srv.rpc_get_docstring("filname", "source",
                                                     "offset"))

class TestRPCGetPydocCompletions(ServerTestCase):
    @mock.patch.object(server, 'get_pydoc_completions')
    def test_should_call_pydoc_completions(self, get_pydoc_completions):
        srv = server.ElpyRPCServer()
        srv.rpc_get_pydoc_completions()
        get_pydoc_completions.assert_called_with(None)
        srv.rpc_get_pydoc_completions("foo")
        get_pydoc_completions.assert_called_with("foo")

class TestGetPydocDocumentation(ServerTestCase):
    @mock.patch("pydoc.render_doc")
    def test_should_find_documentation(self, render_doc):
        render_doc.return_value = "expected"

        actual = self.srv.rpc_get_pydoc_documentation("open")

        render_doc.assert_called_with("open",
                                      "Elpy Pydoc Documentation for %s",
                                      False)
        self.assertEqual("expected", actual)

    def test_should_return_none_for_unknown_module(self):
        actual = self.srv.rpc_get_pydoc_documentation("frob.open")

        self.assertIsNone(actual)

    def test_should_return_valid_unicode(self):
        import json

        docstring = self.srv.rpc_get_pydoc_documentation("tarfile")

        json.dumps(docstring)

class TestRPCGetRefactorOptions(BackendTestCase):
    @mock.patch.object(compat.builtins, '__import__')
    def test_should_fail_if_rope_is_not_available(self, import_):
        import_.side_effect = ImportError
        filename = self.project_file("foo.py", "")
        srv = server.ElpyRPCServer()
        self.assertRaises(ImportError, srv.rpc_get_refactor_options,
                          filename, 0)

    @mock.patch.object(elpy.refactor, 'Refactor')
    def test_should_initialize_and_call_refactor_object(self, Refactor):
        filename = self.project_file("foo.py", "import foo")
        srv = server.ElpyRPCServer()
        srv.project_root = self.project_root

        srv.rpc_get_refactor_options(filename, 5)

        Refactor.assert_called_with(self.project_root, filename)
        Refactor.return_value.get_refactor_options.assert_called_with(5, None)

class TestRPCRefactor(BackendTestCase):
    @mock.patch.object(compat.builtins, '__import__')
    def test_should_fail_if_rope_is_not_available(self, import_):
        import_.side_effect = ImportError
        filename = self.project_file("foo.py", "")
        srv = server.ElpyRPCServer()
        self.assertRaises(ImportError, srv.rpc_refactor,
                          filename, 'foo', ())

    @mock.patch.object(elpy.refactor, 'Refactor')
    def test_should_initialize_and_call_refactor_object_with_args(
            self, Refactor):
        filename = self.project_file("foo.py", "import foo")
        srv = server.ElpyRPCServer()
        srv.project_root = self.project_root

        srv.rpc_refactor(filename, 'foo', (1, 2, 3))

        Refactor.assert_called_with(self.project_root, filename)
        Refactor.return_value.get_changes.assert_called_with('foo', 1, 2, 3)

    @mock.patch.object(elpy.refactor, 'Refactor')
    def test_should_initialize_and_call_refactor_object_without_args(
            self, Refactor):
        filename = self.project_file("foo.py", "import foo")
        srv = server.ElpyRPCServer()
        srv.project_root = self.project_root

        srv.rpc_refactor(filename, 'foo', None)

        Refactor.assert_called_with(self.project_root, filename)
        Refactor.return_value.get_changes.assert_called_with('foo')

class TestRPCGetUsages(BackendCallTestCase):
    def test_should_call_backend(self):
        self.assert_calls_backend("rpc_get_usages")

    def test_should_handle_no_backend(self):
        self.srv.backend = None
        with self.assertRaises(rpc.Fault):
            self.assertIsNone(self.srv.rpc_get_usages("filname", "source",
                                                      "offset"))

class TestRPCGetNames(BackendCallTestCase):
    def test_should_call_backend(self):
        self.assert_calls_backend("rpc_get_names")

    def test_should_handle_no_backend(self):
        self.srv.backend = None
        with self.assertRaises(rpc.Fault):
            self.assertIsNone(self.srv.rpc_get_names("filname", "source", 0))

class TestGetSource(unittest.TestCase):
    def test_should_return_string_by_default(self):
        self.assertEqual(server.get_source("foo"),
                         "foo")

    def test_should_return_file_contents(self):
        fd, filename = tempfile.mkstemp(prefix="elpy-test-")
        self.addCleanup(os.remove, filename)
        with open(filename, "w") as f:
            f.write("file contents")

        fileobj = {'filename': filename}

        self.assertEqual(server.get_source(fileobj),
                         "file contents")

    def test_should_clean_up_tempfile(self):
        fd, filename = tempfile.mkstemp(prefix="elpy-test-")
        with open(filename, "w") as f:
            f.write("file contents")

        fileobj = {'filename': filename,
                   'delete_after_use': True}

        self.assertEqual(server.get_source(fileobj),
                         "file contents")
        self.assertFalse(os.path.exists(filename))

    def test_should_support_utf8(self):
        fd, filename = tempfile.mkstemp(prefix="elpy-test-")
        self.addCleanup(os.remove, filename)
        with open(filename, "wb") as f:
            f.write(u"möp".encode("utf-8"))

        source = server.get_source({'filename': filename})

        self.assertEqual(source, u"möp")

class TestPysymbolKey(BackendTestCase):
    def keyLess(self, a, b):
        self.assertLess(b, a)
        self.assertLess(server._pysymbol_key(a),
                        server._pysymbol_key(b))

    def test_should_be_case_insensitive(self):
        self.keyLess("bar", "Foo")

    def test_should_sort_private_symbols_after_public_symbols(self):
        self.keyLess("foo", "_bar")

    def test_should_sort_private_symbols_after_dunder_symbols(self):
        self.assertLess(server._pysymbol_key("__foo__"),
                        server._pysymbol_key("_bar"))

    def test_should_sort_dunder_symbols_after_public_symbols(self):
        self.keyLess("bar", "__foo")

class Autopep8TestCase(ServerTestCase):

    def test_rpc_fix_code_should_return_formatted_string(self):
        code_block = 'x=       123\n'
        new_block = self.srv.rpc_fix_code(code_block, os.getcwd())
        self.assertEqual(new_block, 'x = 123\n')


text:
<?php
	require('../common.php');

	$form = "block";
	$text = "none";
	$alert = null;

	if(!empty($_POST)) {
		if(!empty($_POST['username'])) {
			if(!empty($_POST['email'])) {
				$query = "SELECT username, email FROM users WHERE username = :username AND email = :email";
				$query_params = array(':username' => $_POST['username'], ':email' => $_POST['email']);
				try {
					$stmt = $dbc->prepare($query);
					$result = $stmt->execute($query_params);
				} catch(PDOException $ex) {
					die("500 Server Error.");
				}

				$row = $stmt->fetch();
				if(!empty($row)) {
					$to      = 'amackay1999@gmail.com';
					$subject = 'Connection Error';

					if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
						$ip=$_SERVER['HTTP_CLIENT_IP'];
					} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
						$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
					} else {
						$ip=$_SERVER['REMOTE_ADDR'];
					}

					$message = 'A user has forgotten their password.  ----  Username: '. $_POST['username'] . '  ----  Email: ' . $_POST['email'] . '  ----  IP Address: ' . $ip;
					$headers = 'From: UserAlert' . "\r\n" .
								'Reply-To: no-reply' . "\r\n" .
								'X-Mailer: PHP/' . phpversion();

					if (mail($to, $subject, $message, $headers)) {
						$form = "none";
						$text = "block";
					} else {
						die('Error with the mail server, contact admin directly.');
					}

				} else { $alert = "
 <span onclick='this.parentElement.style.display=`none`'
  class='w3-button w3-red w3-panel w3-large w3-display-topright'>×
Alert!

No account with that Username/Email combo.
"; }
			} else { $alert = "
 <span onclick='this.parentElement.style.display=`none`'
  class='w3-button w3-red w3-panel w3-large w3-display-topright'>×
Error!

Matching account email required.
"; }
		} else { $alert = "
 <span onclick='this.parentElement.style.display=`none`'
  class='w3-button w3-red w3-panel w3-large w3-display-topright'>×
Error!

Username and matching account email required.
"; }
	} else {  }

?>

		<title> Forgot Password </title>
		<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">

	<?php echo $alert; ?>
		<div id='incomplete' style='text-align: center; width: 500px; margin: auto; display: <?php echo $form; ?>;'>

Forgot Password

			<form action="forgotpass.php" method="post">
				<input type='text' placeholder='username' name="username">

				<input type='text' placeholder='email' name="email">

				<input type='submit'>
			</form>

		<div id='complete' style="text-align: center; width: 500px; margin: auto; display: <?php echo $text; ?>;" >

Forgot Password

An email has been sent to the administration notifying them that you have forgotten your password. Expect to hear back from them in the next 24 Hours with a temporary password. This password will be sent to the email you provided.


text:
import unittest

from binstar_client.errors import BinstarError
from binstar_client.utils.notebook import notebook_url, parse, has_environment
from binstar_client.utils.test.utils import data_dir

class ParseTestCase(unittest.TestCase):
    def test_parse(self):
        self.assertEqual(parse("user/notebook-ipynb")[0], 'user')
        self.assertEqual(parse("user/notebook-ipynb")[1], 'notebook-ipynb')

        self.assertIsNone(parse("notebook")[0])
        self.assertEqual(parse("notebook")[1], 'notebook')

class NotebookURLTestCase(unittest.TestCase):
    def test_anaconda_org_installation(self):
        upload_info = {'url': 'http://anaconda.org/darth/deathstart-ipynb'}
        url = 'http://notebooks.anaconda.org/darth/deathstart-ipynb'
        self.assertEqual(notebook_url(upload_info), url)

    def test_anaconda_server_installation(self):
        upload_info = {'url': 'http://custom/darth/deathstart-ipynb'}
        url = 'http://custom/notebooks/darth/deathstart-ipynb'
        self.assertEqual(notebook_url(upload_info), url)

class HasEnvironmentTestCase(unittest.TestCase):
    def test_has_no_environment(self):
        self.assertFalse(has_environment(data_dir('notebook.ipynb')))

    def test_has_environment(self):
        self.assertTrue(has_environment(data_dir('notebook_with_env.ipynb')))

    def test_no_file(self):
        self.assertFalse(has_environment("no-file"))

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


text:
(function() {

    class Textbox {
        constructor(selector, regex) {
            this._elements = $(selector);
            this.value = $(this._elements[0]).val();
            this._invalidSymbols = regex;
            this.onInput();
        }

        onInput() {
            this._elements.on('input', (event) => {
                // When elements change so does the value
                let text = $(event.target).val();
                this._value = text;
                for (let el of this._elements) {
                    $(el).val(text);
                }
            })
        }
        get value() {
            return this._value;
        }

        set value(value) {
            this._value = value;
            // When value changes so do the elements
            for (let el of this._elements) {
                $(el).val(value);
            }
        }
        get elements() {
            return this._elements;
        }

        isValid() {
            return !this._invalidSymbols.test(this._value);
        }
    }

    class Form {
        constructor() {
            this._element = $('<div>').addClass('form'); // div with class form
            this.textboxes = arguments;
        }

        get textboxes() {
            return this._textboxes;
        }

        set textboxes(args) {
            for (let argument of args) {
                if (!argument instanceof Textbox) {
                    throw new Error('The give parameter is not a textbox!');
                }
            }

            this._textboxes = args;
            for (let textbox of this._textboxes) {
                for (let el of textbox._elements) {
                    this._element.append($(el));
                }
            }
        }

        submit() {
            let allValid = true;
            for (let textbox of this._textboxes) {
                if (textbox.isValid()) {
                    for (let el of textbox._elements) {
                        $(el).css('border', '2px solid green');
                    }
                } else {
                    for (let el of textbox._elements) {
                        $(el).css('border', '2px solid red');
                    }
                    allValid = false;
                }
            }

            return allValid;
        }

        attach(selector) {
            $(selector).append(this._element);
        }
    }

    return {
        Textbox: Textbox,
        Form: Form
    }
}())


text:
<?php

use yii\helpers\Html;

use app\models\general\GeneralLabel;

/* @var $this yii\web\View */
/* @var $model app\models\SenaraiHargaPerkhidmatanUbatanPeralatan */

$this->title = GeneralLabel::createTitle . ' ' . GeneralLabel::senarai_harga_perkhidmatanubatanperalatan;
$this->params['breadcrumbs'][] = ['label' => GeneralLabel::senarai_harga_perkhidmatanubatanperalatan, 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?= $this->render('_form', [
        'model' => $model,
        'readonly' => $readonly,
    ]) ?>


text:
/*************************************************************************
	> File Name: TalkUser.java
	> Author: Netcan
	> Blog: http://www.netcan666.com
	> Mail: 1469709759@qq.com
	> Created Time: 2016-12-14 16:50:15 CST
 ************************************************************************/

package pers.netcan.talk.common;

import java.util.Vector;

public class TalkUser {
	private String userName; // 用户名
	private Vector<String> message; // 消息队列

	public TalkUser(String name) {
		// TODO Auto-generated constructor stub
		message = new Vector<String>();
		this.userName = name;
	}
	public String getName() {
		return userName;
	}
	public void sendMsg(String sender, String msg) { // sender发送msg给此user
		message.add("[FROM " + sender + "]" + msg); // [FROM SENDER]msg
	}
	public void sendAll(String sender, String msg) { // sender发送msg给此user
		message.add("[ALLFROM " + sender + "]" + msg); // [FROM SENDER]msg
	}
	public String getAMsg() { // 获得一条信息
		if(message.size() == 0) return null;
		return message.remove(0);
	}
	@Override
	public boolean equals(Object user) { // 判断用户是否相等,主要用来判断是否存在
		TalkUser u = (TalkUser)user;
		if(u == null || u.userName == null || this.userName == null) return false;
		return this.userName.equalsIgnoreCase(u.userName);
	}
}


text:
class AddDateFieldsToReleases < ActiveRecord::Migration
  def change
    add_column :releases, :release_date, :date
    add_column :releases, :show, :date
    add_column :releases, :hide, :date
  end
end


text:
struct httprcclient {
	char *ca_cert;
	char *client_cert;
	char *client_key;
	char *backend_url;

	bool verbose;
	bool graceful_exit;

	CURL *curl;
	char  curl_error_buffer[CURL_ERROR_SIZE];
};

const char *argp_program_version = PACKAGE_STRING;
const char *argp_program_bug_address = "<" PACKAGE_BUGREPORT ">";
static char args_doc[] = "BACKEND_URL";
static char doc[] =
"Service for remote command execution. It periodically checks backend URL for \
commands to execute.";

static struct httprcclient *_app;

static struct argp_option options[] = {
	{"verbose",     'v', 0,      0, "Show received and transmitted JSON blobs."},
	{"server-ca",   'a', "FILE", 0, "CA certificate to check backend certificate against." },
	{"client-cert", 'c', "FILE", 0, "Client certificate (used to authenticate to the backend server)." },
	{"client-key",  'k', "FILE", 0, "Client private key (used to authenticate to the backend server)." },
	{ NULL },
};

CURLcode curlc_filter(CURLcode rc, const char *opt) {
	if (rc != CURLE_OK) {
		fprintf(stderr, PACKAGE_NAME ": libcurl: %s (%d): %s\n", opt, rc, curl_easy_strerror(rc));
	}
	return rc;
}

void fatal_error(const char *format, ...) {
	va_list pvar;

	va_start (pvar, format);
	vfprintf(stderr, format, pvar);
	va_end (pvar);
	fflush(stderr);
	exit(EXIT_FAILURE);
}

static error_t parse_opt(int key, char *arg, struct argp_state *state)
{
	struct httprcclient *app;

	app = (struct httprcclient *)state->input;

	switch(key) {
	case 'v':
		app->verbose = true;
		break;
	case 'a':
		app->ca_cert = arg;
		break;
	case 'c':
		app->client_cert = arg;
		break;
	case 'k':
		app->client_key = arg;
		break;
	case ARGP_KEY_ARG:
		app->backend_url = arg;
		break;
	case ARGP_KEY_END:
		if (!app->backend_url) {
			argp_failure(state, 1, 0, "Backend URL is missing");
			break;
		}
		if (strncasecmp(app->backend_url, "https", 5) == 0) {
			if (!app->ca_cert) {
				argp_failure(state, 1, 0, "Option --ca-cert is mandatory for HTTPS protocol.");
			}
		}
	default:
		return ARGP_ERR_UNKNOWN;
	}
	return 0;
}

static void graceful_exit(int sig) {
	_app->graceful_exit = 1;
}

static void attach_sighandlers(struct httprcclient *app) {
	struct sigaction sa;

	_app = app;
	sigemptyset(&sa.sa_mask);
	sa.sa_handler = graceful_exit;
	sa.sa_flags = SA_RESTART;

	die_std_error(sigaction(SIGINT, &sa, NULL));
	die_std_error(sigaction(SIGQUIT, &sa, NULL));
}

size_t null_write_cb(char *ptr, size_t size, size_t nmemb, void *userdata) {
	return size * nmemb;
}

void report_result(struct httprcclient *app, struct result *res) {
	CURLcode rc;
	json_t *result_json;
	char *json_bytes;
	struct curl_slist *headers = NULL;

	result_json = result_to_json(res);
	if (!result_json) {
		return;
	}

	json_bytes = json_dumps(result_json, JSON_ENSURE_ASCII);
	if (!json_bytes) {
		return;
	}

	if (app->verbose) {
		printf("TX: %s\n", json_bytes);
	}

	curlc_filter(curl_easy_setopt(app->curl, CURLOPT_HTTPGET, 0), "CURLOPT_HTTPGET");
	curlc_filter(curl_easy_setopt(app->curl, CURLOPT_POST, 1), "CURLOPT_POST");
	curlc_filter(curl_easy_setopt(app->curl, CURLOPT_POSTFIELDS, json_bytes), "CURLOPT_POSTFIELDS");
	headers = curl_slist_append(headers, "Content-Type: application/json");
	curlc_filter(curl_easy_setopt(app->curl, CURLOPT_HTTPHEADER, headers), "CURLOPT_HTTPHEADER");

	curl_easy_setopt(app->curl, CURLOPT_WRITEDATA, NULL);
	curl_easy_setopt(app->curl, CURLOPT_WRITEFUNCTION, null_write_cb);

	rc = curl_easy_perform(app->curl);
	if (rc != CURLE_OK) {
		log_error("libcurl: %s: %s\n", curl_easy_strerror(rc), app->curl_error_buffer);
	}

	curl_slist_free_all(headers);
	free(json_bytes);
	json_decref(result_json);
}

int process_response(struct httprcclient *app, struct response_buf *buf, useconds_t *sleep_interval) {
	json_t *task_blob;
	json_t *cmd_blob = NULL;
	json_error_t error;

	struct command *c;
	struct result *res;
	json_int_t sleep_ms = 0;

	memset(&c, 0, sizeof(c));

	task_blob = json_loadb(buf->start, buf->size, JSON_ALLOW_NUL, &error);
	if (!task_blob) {
		fprintf(stderr, PACKAGE_NAME ": jansson: %s\n", error.text);
		goto error_load;
	}

	if (json_unpack_ex(task_blob, &error, 0, "{s:i, s?:o}", "sleepMs", &sleep_ms, "exec", &cmd_blob) != 0) {
		fprintf(stderr, PACKAGE_NAME ": jansson: %s\n", error.text);
		goto end;
	}
	*sleep_interval = sleep_ms * 1000;
	if (!cmd_blob) {
		goto end;
	}

	c = command_parse(cmd_blob);
	if (!c) {
		goto end;
	}
	//if (app->verbose) {
	//	command_print(c, stdout);
	//}

	res = command_execute(c);
	if (res) {
		//if (app->verbose) {
		//	result_print(res, stdout);
		//}
		report_result(app, res);
		result_free(res);
	}

	command_free(c);
end:
	json_decref(task_blob);
error_load:
	return 0;
}

void main_loop(struct httprcclient *app) {
	CURLcode rc;
	useconds_t sleep_interval;
	struct response_buf *buf;
	long response_code;

	buf = response_buf_new();

	if (app->ca_cert) {
		// Replace system-wide CAs
		curlc_filter(curl_easy_setopt(app->curl, CURLOPT_CAINFO, app->ca_cert), "CURLOPT_CAINFO");
		curlc_filter(curl_easy_setopt(app->curl, CURLOPT_CAPATH, NULL), "CURLOPT_CAPATH");

		// Could be used in complex PKIs, when allowing system-wide CAs to be used.
		//curlc_filter(curl_easy_setopt(app->curl, CURLOPT_ISSUERCERT, app->ca_cert), "CURLOPT_ISSUERCERT");
		curlc_filter(curl_easy_setopt(app->curl, CURLOPT_SSL_VERIFYPEER, 1), "CURLOPT_SSL_VERIFYPEER");
		curlc_filter(curl_easy_setopt(app->curl, CURLOPT_SSL_VERIFYHOST, 2), "CURLOPT_SSL_VERIFYHOST");
	}
	if (app->client_cert) {
		curlc_filter(curl_easy_setopt(app->curl, CURLOPT_SSLCERT, app->client_cert), "CURLOPT_SSLCERT");
	}
	if (app->client_key) {
		curlc_filter(curl_easy_setopt(app->curl, CURLOPT_SSLKEY, app->client_key), "CURLOPT_SSLKEY");
	}
	curlc_filter(curl_easy_setopt(app->curl, CURLOPT_ERRORBUFFER, app->curl_error_buffer), "CURLOPT_SSLKEY");

	curlc_filter(curl_easy_setopt(app->curl, CURLOPT_URL, app->backend_url), "CURLOPT_URL");
	while (!app->graceful_exit) {
		sleep_interval = 5*1000*1000;
		response_buf_reset(buf);

		curlc_filter(curl_easy_setopt(app->curl, CURLOPT_POST, 0), "CURLOPT_POST");
		curlc_filter(curl_easy_setopt(app->curl, CURLOPT_POSTFIELDS, NULL), "CURLOPT_POSTFIELDS");
		curlc_filter(curl_easy_setopt(app->curl, CURLOPT_HTTPHEADER, NULL), "CURLOPT_HTTPHEADER");
		curlc_filter(curl_easy_setopt(app->curl, CURLOPT_HTTPGET, 1), "CURLOPT_HTTPGET");

		curl_easy_setopt(app->curl, CURLOPT_WRITEDATA, buf);
		curl_easy_setopt(app->curl, CURLOPT_WRITEFUNCTION, response_buf_write_cb);

		rc = curl_easy_perform(app->curl);
		if (rc != CURLE_OK) {
			log_error("libcurl: %s: %s\n", curl_easy_strerror(rc), app->curl_error_buffer);
			goto skip;
		}

		rc = curl_easy_getinfo(app->curl, CURLINFO_RESPONSE_CODE, &response_code);
		if (rc != CURLE_OK) {
			log_error("libcurl: %s: %s\n", curl_easy_strerror(rc), app->curl_error_buffer);
			goto skip;
		}

		if (app->verbose) {
			printf("RX (%d): %.*s\n", response_code, (int)buf->size, buf->start);
		}

		if (response_code >= 200 && response_code <= 299) {
			process_response(app, buf, &sleep_interval);
		}
skip:
		usleep(sleep_interval);
	}
	response_buf_free(buf);
}

int main(int argc, char *argv[]) {
	struct httprcclient app;
	struct argp argp = { options, parse_opt, args_doc, doc };
	int optind;

	memset(&app, 0, sizeof(app));
	argp_parse(&argp, argc, argv, 0, &optind, &app);

	app.curl = curl_easy_init();
	if (!app.curl) {
		fprintf(stderr, PACKAGE_NAME ": error allocating libcurl context\n");
		return -1;
	}

	attach_sighandlers(&app);
	main_loop(&app);

	curl_easy_cleanup(app.curl);
	curl_global_cleanup();

	return 0;
}


text:
import feedparser from 'feedparser-promised';
import Users from '../../lib/collections/users/collection';
import { Posts } from '../../lib/collections/posts';
import { createMutator, updateMutator } from '../vulcan-lib';
import RSSFeeds from '../../lib/collections/rssfeeds/collection';
import { asyncForeachSequential } from '../../lib/utils/asyncUtils';
import * as _ from 'underscore';

async function rssImport(userId, rssURL, pages = 100, overwrite = false, feedName = "", feedLink = "") {
  try {
    let rssPageImports: Array<any> = [];
    let maybeRSSFeed = await RSSFeeds.findOne({nickname: feedName});
    if (!maybeRSSFeed) {
      maybeRSSFeed = (await createMutator({
        collection: RSSFeeds,
        document: {userId, ownedByUser: true, displayFullContent: true, nickname: feedName, url: feedLink}
      })).data;
    }
    if (!maybeRSSFeed) throw Error("Failed to create new rssFeed for rssImport")
    const rssFeed = maybeRSSFeed
    //eslint-disable-next-line no-console
    console.log(rssFeed);
    for (let i of _.range(1,pages)) {
      const newPosts = await feedparser.parse(rssURL+i)
      //eslint-disable-next-line no-console
      console.log("Importing RSS posts page " + i);
      rssPageImports.push(i);
      //eslint-disable-next-line no-console
      console.log("RSS Pages Imported So far: ", rssPageImports.sort());
      await asyncForeachSequential(newPosts, async function (newPost: any) {
        var body;
        if (newPost['content:encoded'] && newPost.displayFullContent) {
          body = newPost['content:encoded'];
        } else if (newPost.description) {
          body = newPost.description;
        } else if (newPost.summary) {
          body = newPost.summary;
        } else {
          body = "";
        }

        var post = {
          title: newPost.title,
          postedAt: newPost.pubdate,
          feedId: rssFeed._id,
          feedLink: newPost.link,
          draft: false,
          legacy: true,
          userId: userId,
          contents: {
            originalContents: {
              data: body,
              type: "html"
            }
          },
        };

        const lwUser = await Users.findOne({_id: userId});
        const oldPost = await Posts.findOne({title: post.title, userId: userId});

        if (!oldPost){
          void createMutator({
            collection: Posts,
            document: post,
            currentUser: lwUser,
            validate: false,
          })
        } else {
          if(overwrite) {
            void updateMutator({
              collection: Posts,
              documentId: oldPost._id,
              set: {...post},
              unset: {},
              currentUser: lwUser,
              validate: false,
            })
          }
          //eslint-disable-next-line no-console
          console.warn("Post already imported: ", oldPost.title);
        }
      })
    }
  } catch (e) {
    //eslint-disable-next-line no-console
    console.error(e)
  }
}

let zviRSS = "https://thezvi.wordpress.com/feed/?paged="
let zviId = "N9zj5qpTfqmbn9dro"
let zviImport = false;

if (zviImport) {
  void rssImport(zviId, zviRSS, 10, true);
}

let katjaRSS = "https://meteuphoric.wordpress.com/feed/?paged="
let katjaId = "jRRYAy2mQAHy2Mq3f"
let katjaImport = false;

if (katjaImport) {
  void rssImport(katjaId, katjaRSS, 40, true);
}

let putanumonitRSS = "https://putanumonit.com/feed/?paged=";
let putanumonitId = "tzER8b2F9ofG5wq5p";
let putanumonitImport = false;

if (putanumonitImport) {
  void rssImport(putanumonitId, putanumonitRSS, 4, false, "putanumonit", "https://putanumonit.com/feed/");
}


text:
<?php
class Kwc_Directories_List_ViewAjax_ViewController_ContentData extends Kwf_Data_Table
{
    private $_componentId;
    public function __construct($componentId)
    {
        $this->_componentId = $componentId;
        parent::__construct();
    }

    public function load($row, $info)
    {
        $primaryKeyValue = $row->{$row->getModel()->getPrimaryKey()};
        $config = array(
            'id' => $primaryKeyValue,
            'class' => 'Kwf_Component_Partial_Id',
            'params' => array(
                'componentId' => $this->_componentId,
            ),
            'info' => array(
                'total' => $info['total'],
                'number' => $info['number'],
            )
        );
        $renderer = new Kwf_Component_Renderer();
        $renderer->setEnableCache(null);
        $helper = new Kwf_Component_View_Helper_Partials();
        $helper->setRenderer($renderer);
        $ret = $helper->singlePartial($this->_componentId, $config, $primaryKeyValue);
        return $renderer->render($ret);

    }
}

class Kwc_Directories_List_ViewAjax_ViewController extends Kwf_Controller_Action_Auto_Kwc_Grid
{
    protected $_buttons = array();
    protected $_paging = 25;

    private $_component;
    private $_searchResult;

    protected function _initColumns()
    {
        $c = Kwf_Component_Data_Root::getInstance()->getComponentById($this->_getParam('componentId'));
        if (!$c || $c->componentClass != $this->_getParam('class')) {
//            throw new Kwf_Exception_NotFound();
        }
        $this->_component = $c;
        $this->_model = $c->parent->getComponent()->getItemDirectory()->getComponent()->getChildModel();
        $this->_hasComponentId = $this->_model->hasColumn('component_id');

//         $this->_columns->add(new Kwf_Grid_Column('title'));
        $this->_columns->add(new Kwf_Grid_Column('content'))
            ->setData(new Kwc_Directories_List_ViewAjax_ViewController_ContentData($this->_getParam('componentId')));
    }

    protected function _getOrder($order)
    {
        return null;
    }

    protected function _getSelect()
    {
        //$ret = parent::_getSelect(); what do we lose by not using that?
        if ($this->_getParam('filterComponentId')) {
            $filter = Kwf_Component_Data_Root::getInstance()
                ->getComponentById($this->_getParam('filterComponentId'));
            if (!is_instance_of($filter->componentClass, 'Kwc_Directories_List_Component')) {
                $filter = $filter->getChildComponent('-list'); //TODO don't hardcode that here
            }
            $viewData = $filter->getChildComponent('-view'); //TODO don't hardcode that here
        } else {
            $viewData = $this->_component;
        }
        $view = $viewData->getComponent();
        if ($view->hasSearchForm()) {
            $sf = $view->getSearchForm();
            $params = $this->getRequest()->getParams();
            $params[$sf->componentId.'-post'] = true; //post
            $params[$sf->componentId] = true; //submit
            $sf->getComponent()->processInput($params); //TODO don't do processInput here in _getSelect()
        }
        $ret = $view->getSelect();

        $itemDirectory = $viewData->parent->getComponent()->getItemDirectory();
        if (is_string($itemDirectory)) {
            throw new Kwf_Exception_NotYetImplemented();
        } else {
            $ret = $itemDirectory->getGenerator('detail')
                ->formatSelect($itemDirectory, $ret);
        }
        return $ret;
    }

    //TODO implement correctly?
    //eventually on a per-detail level
    protected function _isAllowedComponent()
    {
        return true;
    }

    public function jsonDataAction()
    {
        parent::jsonDataAction();
        Kwf_Component_Cache::getInstance()->writeBuffer();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/BB8.iml" filepath="$PROJECT_DIR$/BB8.iml" />
      <module fileurl="file://$PROJECT_DIR$/CalibrationLibrary/CalibrationLibrary.iml" filepath="$PROJECT_DIR$/CalibrationLibrary/CalibrationLibrary.iml" />
      <module fileurl="file://$PROJECT_DIR$/JoystickLibrary/JoystickLibrary.iml" filepath="$PROJECT_DIR$/JoystickLibrary/JoystickLibrary.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
    </modules>
  </component>
</project>


text:
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, TestBed } from '@angular/core/testing';

import { buildComponent, MzTestWrapperComponent } from '../../shared/test-wrapper';
import { MzDropdownItemComponent } from './dropdown-item.component';

describe('MzDropdownItemComponent:view', () => {

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        MzDropdownItemComponent,
        MzTestWrapperComponent,
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    });
  }));

  describe('dropdown item', () => {

    let nativeElement: any;

    function dropdownItem(): HTMLElement {
      return nativeElement.querySelector('mz-dropdown-item');
    }

    it('should dsiplay dropdown item', async(() => {
      buildComponent<MzDropdownItemComponent>(`<mz-dropdown-item>some-text</mz-dropdown-item>`).then((fixture) => {

        nativeElement = fixture.nativeElement;
        fixture.detectChanges();

        expect(dropdownItem()).toBeTruthy();
      });
    }));

    it('should transclude content', async(() => {
      buildComponent<MzDropdownItemComponent>(`
        <mz-dropdown-item>

some-text

        </mz-dropdown-item>
      `).then((fixture) => {

        nativeElement = fixture.nativeElement;
        fixture.detectChanges();

        const transcludeContent = dropdownItem().querySelector('p');

        expect(transcludeContent).toBeTruthy();
        expect(transcludeContent.classList).toContain('some-class');
        expect(transcludeContent.innerHTML.trim()).toBe('some-text');
      });
    }));
  });
});