text:
#include <python/nxt_python.h>

#if (NXT_HAVE_ASGI)

#include <nxt_main.h>
#include <python/nxt_python_asgi.h>
#include <python/nxt_python_asgi_str.h>

typedef struct  {
    PyObject_HEAD
    nxt_py_asgi_ctx_data_t  *ctx_data;
    int                     disabled;
    int                     startup_received;
    int                     startup_sent;
    int                     shutdown_received;
    int                     shutdown_sent;
    int                     shutdown_called;
    PyObject                *startup_future;
    PyObject                *shutdown_future;
    PyObject                *receive_future;
} nxt_py_asgi_lifespan_t;

static PyObject *nxt_py_asgi_lifespan_target_startup(
    nxt_py_asgi_ctx_data_t *ctx_data, nxt_python_target_t *target);
static int nxt_py_asgi_lifespan_target_shutdown(
    nxt_py_asgi_lifespan_t *lifespan);
static PyObject *nxt_py_asgi_lifespan_receive(PyObject *self, PyObject *none);
static PyObject *nxt_py_asgi_lifespan_send(PyObject *self, PyObject *dict);
static PyObject *nxt_py_asgi_lifespan_send_startup(
    nxt_py_asgi_lifespan_t *lifespan, int v, PyObject *dict);
static PyObject *nxt_py_asgi_lifespan_send_(nxt_py_asgi_lifespan_t *lifespan,
    int v, int *sent, PyObject **future);
static PyObject *nxt_py_asgi_lifespan_send_shutdown(
    nxt_py_asgi_lifespan_t *lifespan, int v, PyObject *dict);
static PyObject *nxt_py_asgi_lifespan_disable(nxt_py_asgi_lifespan_t *lifespan);
static PyObject *nxt_py_asgi_lifespan_done(PyObject *self, PyObject *future);

static PyMethodDef nxt_py_asgi_lifespan_methods[] = {
    { "receive",   nxt_py_asgi_lifespan_receive, METH_NOARGS, 0 },
    { "send",      nxt_py_asgi_lifespan_send,    METH_O,      0 },
    { "_done",     nxt_py_asgi_lifespan_done,    METH_O,      0 },
    { NULL, NULL, 0, 0 }
};

static PyAsyncMethods nxt_py_asgi_async_methods = {
    .am_await = nxt_py_asgi_await,
};

static PyTypeObject nxt_py_asgi_lifespan_type = {
    PyVarObject_HEAD_INIT(NULL, 0)

    .tp_name      = "unit._asgi_lifespan",
    .tp_basicsize = sizeof(nxt_py_asgi_lifespan_t),
    .tp_dealloc   = nxt_py_asgi_dealloc,
    .tp_as_async  = &nxt_py_asgi_async_methods,
    .tp_flags     = Py_TPFLAGS_DEFAULT,
    .tp_doc       = "unit ASGI Lifespan object",
    .tp_iter      = nxt_py_asgi_iter,
    .tp_iternext  = nxt_py_asgi_next,
    .tp_methods   = nxt_py_asgi_lifespan_methods,
};

int
nxt_py_asgi_lifespan_startup(nxt_py_asgi_ctx_data_t *ctx_data)
{
    size_t               size;
    PyObject             *lifespan;
    PyObject             **target_lifespans;
    nxt_int_t            i;
    nxt_python_target_t  *target;

    size = nxt_py_targets->count * sizeof(PyObject*);

    target_lifespans = nxt_unit_malloc(NULL, size);
    if (nxt_slow_path(target_lifespans == NULL)) {
        nxt_unit_alert(NULL, "Failed to allocate lifespan data");
        return NXT_UNIT_ERROR;
    }

    memset(target_lifespans, 0, size);

    for (i = 0; i < nxt_py_targets->count; i++) {
        target = &nxt_py_targets->target[i];

        lifespan = nxt_py_asgi_lifespan_target_startup(ctx_data, target);
        if (nxt_slow_path(lifespan == NULL)) {
            return NXT_UNIT_ERROR;
        }

        target_lifespans[i] = lifespan;
    }

    ctx_data->target_lifespans = target_lifespans;

    return NXT_UNIT_OK;
}

static PyObject *
nxt_py_asgi_lifespan_target_startup(nxt_py_asgi_ctx_data_t *ctx_data,
    nxt_python_target_t *target)
{
    PyObject                *scope, *res, *py_task, *receive, *send, *done;
    PyObject                *stage2;
    nxt_py_asgi_lifespan_t  *lifespan, *ret;

    if (nxt_slow_path(PyType_Ready(&nxt_py_asgi_lifespan_type) != 0)) {
        nxt_unit_alert(NULL,
                 "Python failed to initialize the 'asgi_lifespan' type object");
        return NULL;
    }

    lifespan = PyObject_New(nxt_py_asgi_lifespan_t, &nxt_py_asgi_lifespan_type);
    if (nxt_slow_path(lifespan == NULL)) {
        nxt_unit_alert(NULL, "Python failed to create lifespan object");
        return NULL;
    }

    ret = NULL;

    receive = PyObject_GetAttrString((PyObject *) lifespan, "receive");
    if (nxt_slow_path(receive == NULL)) {
        nxt_unit_alert(NULL, "Python failed to get 'receive' method");
        goto release_lifespan;
    }

    send = PyObject_GetAttrString((PyObject *) lifespan, "send");
    if (nxt_slow_path(receive == NULL)) {
        nxt_unit_alert(NULL, "Python failed to get 'send' method");
        goto release_receive;
    }

    done = PyObject_GetAttrString((PyObject *) lifespan, "_done");
    if (nxt_slow_path(receive == NULL)) {
        nxt_unit_alert(NULL, "Python failed to get '_done' method");
        goto release_send;
    }

    lifespan->startup_future = PyObject_CallObject(ctx_data->loop_create_future,
                                                   NULL);
    if (nxt_slow_path(lifespan->startup_future == NULL)) {
        nxt_unit_alert(NULL, "Python failed to create Future object");
        nxt_python_print_exception();

        goto release_done;
    }

    lifespan->ctx_data = ctx_data;
    lifespan->disabled = 0;
    lifespan->startup_received = 0;
    lifespan->startup_sent = 0;
    lifespan->shutdown_received = 0;
    lifespan->shutdown_sent = 0;
    lifespan->shutdown_called = 0;
    lifespan->shutdown_future = NULL;
    lifespan->receive_future = NULL;

    scope = nxt_py_asgi_new_scope(NULL, nxt_py_lifespan_str, nxt_py_2_0_str);
    if (nxt_slow_path(scope == NULL)) {
        goto release_future;
    }

    if (!target->asgi_legacy) {
        nxt_unit_req_debug(NULL, "Python call ASGI 3.0 application");

        res = PyObject_CallFunctionObjArgs(target->application,
                                           scope, receive, send, NULL);

    } else {
        nxt_unit_req_debug(NULL, "Python call legacy application");

        res = PyObject_CallFunctionObjArgs(target->application, scope, NULL);
        if (nxt_slow_path(res == NULL)) {
            nxt_unit_log(NULL, NXT_UNIT_LOG_INFO,
                         "ASGI Lifespan processing exception");
            nxt_python_print_exception();

            lifespan->disabled = 1;

            Py_INCREF(lifespan);
            ret = lifespan;

            goto release_scope;
        }

        if (nxt_slow_path(PyCallable_Check(res) == 0)) {
            nxt_unit_req_error(NULL,
                              "Legacy ASGI application returns not a callable");

            Py_DECREF(res);

            goto release_scope;
        }

        stage2 = res;

        res = PyObject_CallFunctionObjArgs(stage2, receive, send, NULL);

        Py_DECREF(stage2);
    }

    if (nxt_slow_path(res == NULL)) {
        nxt_unit_error(NULL, "Python failed to call the application");
        nxt_python_print_exception();
        goto release_scope;
    }

    if (nxt_slow_path(!PyCoro_CheckExact(res))) {
        nxt_unit_error(NULL, "Application result type is not a coroutine");
        Py_DECREF(res);
        goto release_scope;
    }

    py_task = PyObject_CallFunctionObjArgs(ctx_data->loop_create_task, res,
                                           NULL);
    if (nxt_slow_path(py_task == NULL)) {
        nxt_unit_alert(NULL, "Python failed to call the create_task");
        nxt_python_print_exception();
        Py_DECREF(res);
        goto release_scope;
    }

    Py_DECREF(res);

    res = PyObject_CallMethodObjArgs(py_task, nxt_py_add_done_callback_str,
                                     done, NULL);
    if (nxt_slow_path(res == NULL)) {
        nxt_unit_alert(NULL, "Python failed to call 'task.add_done_callback'");
        nxt_python_print_exception();
        goto release_task;
    }

    Py_DECREF(res);

    res = PyObject_CallFunctionObjArgs(ctx_data->loop_run_until_complete,
                                       lifespan->startup_future, NULL);
    if (nxt_slow_path(res == NULL)) {
        nxt_unit_alert(NULL, "Python failed to call loop.run_until_complete");
        nxt_python_print_exception();
        goto release_task;
    }

    Py_DECREF(res);

    if (lifespan->startup_sent == 1 || lifespan->disabled) {
        Py_INCREF(lifespan);

        ret = lifespan;
    }

release_task:
    Py_DECREF(py_task);
release_scope:
    Py_DECREF(scope);
release_future:
    Py_CLEAR(lifespan->startup_future);
release_done:
    Py_DECREF(done);
release_send:
    Py_DECREF(send);
release_receive:
    Py_DECREF(receive);
release_lifespan:
    Py_DECREF(lifespan);

    return (PyObject *) ret;
}

int
nxt_py_asgi_lifespan_shutdown(nxt_unit_ctx_t *ctx)
{
    nxt_int_t               i, ret;
    nxt_py_asgi_lifespan_t  *lifespan;
    nxt_py_asgi_ctx_data_t  *ctx_data;

    ctx_data = ctx->data;

    for (i = 0; i < nxt_py_targets->count; i++) {
        lifespan = (nxt_py_asgi_lifespan_t *)ctx_data->target_lifespans[i];

        ret = nxt_py_asgi_lifespan_target_shutdown(lifespan);
        if (nxt_slow_path(ret != NXT_UNIT_OK)) {
            return NXT_UNIT_ERROR;
        }
    }

    nxt_unit_free(NULL, ctx_data->target_lifespans);

    return NXT_UNIT_OK;
}

static int
nxt_py_asgi_lifespan_target_shutdown(nxt_py_asgi_lifespan_t *lifespan)
{
    PyObject                *msg, *future, *res;
    nxt_py_asgi_ctx_data_t  *ctx_data;

    ctx_data = lifespan->ctx_data;

    if (nxt_slow_path(lifespan == NULL || lifespan->disabled)) {
        return NXT_UNIT_OK;
    }

    lifespan->shutdown_called = 1;

    if (lifespan->receive_future != NULL) {
        future = lifespan->receive_future;
        lifespan->receive_future = NULL;

        msg = nxt_py_asgi_new_msg(NULL, nxt_py_lifespan_shutdown_str);

        if (nxt_fast_path(msg != NULL)) {
            res = PyObject_CallMethodObjArgs(future, nxt_py_set_result_str,
                                             msg, NULL);
            Py_XDECREF(res);
            Py_DECREF(msg);
        }

        Py_DECREF(future);
    }

    if (lifespan->shutdown_sent) {
        return NXT_UNIT_OK;
    }

    lifespan->shutdown_future = PyObject_CallObject(ctx_data->loop_create_future,
                                                    NULL);
    if (nxt_slow_path(lifespan->shutdown_future == NULL)) {
        nxt_unit_alert(NULL, "Python failed to create Future object");
        nxt_python_print_exception();
        return NXT_UNIT_ERROR;
    }

    res = PyObject_CallFunctionObjArgs(ctx_data->loop_run_until_complete,
                                       lifespan->shutdown_future, NULL);
    if (nxt_slow_path(res == NULL)) {
        nxt_unit_alert(NULL, "Python failed to call loop.run_until_complete");
        nxt_python_print_exception();
        return NXT_UNIT_ERROR;
    }

    Py_DECREF(res);
    Py_CLEAR(lifespan->shutdown_future);

    return NXT_UNIT_OK;
}

static PyObject *
nxt_py_asgi_lifespan_receive(PyObject *self, PyObject *none)
{
    PyObject                *msg, *future;
    nxt_py_asgi_lifespan_t  *lifespan;
    nxt_py_asgi_ctx_data_t  *ctx_data;

    lifespan = (nxt_py_asgi_lifespan_t *) self;
    ctx_data = lifespan->ctx_data;

    nxt_unit_debug(NULL, "asgi_lifespan_receive");

    future = PyObject_CallObject(ctx_data->loop_create_future, NULL);
    if (nxt_slow_path(future == NULL)) {
        nxt_unit_alert(NULL, "Python failed to create Future object");
        nxt_python_print_exception();

        return PyErr_Format(PyExc_RuntimeError,
                            "failed to create Future object");
    }

    if (!lifespan->startup_received) {
        lifespan->startup_received = 1;

        msg = nxt_py_asgi_new_msg(NULL, nxt_py_lifespan_startup_str);

        return nxt_py_asgi_set_result_soon(NULL, ctx_data, future, msg);
    }

    if (lifespan->shutdown_called && !lifespan->shutdown_received) {
        lifespan->shutdown_received = 1;

        msg = nxt_py_asgi_new_msg(NULL, nxt_py_lifespan_shutdown_str);

        return nxt_py_asgi_set_result_soon(NULL, ctx_data, future, msg);
    }

    Py_INCREF(future);
    lifespan->receive_future = future;

    return future;
}

static PyObject *
nxt_py_asgi_lifespan_send(PyObject *self, PyObject *dict)
{
    PyObject                *type, *msg;
    const char              *type_str;
    Py_ssize_t              type_len;
    nxt_py_asgi_lifespan_t  *lifespan;

    static const nxt_str_t  startup_complete
                                = nxt_string("lifespan.startup.complete");
    static const nxt_str_t  startup_failed
                                = nxt_string("lifespan.startup.failed");
    static const nxt_str_t  shutdown_complete
                                = nxt_string("lifespan.shutdown.complete");
    static const nxt_str_t  shutdown_failed
                                = nxt_string("lifespan.shutdown.failed");

    lifespan = (nxt_py_asgi_lifespan_t *) self;

    type = PyDict_GetItem(dict, nxt_py_type_str);
    if (nxt_slow_path(type == NULL || !PyUnicode_Check(type))) {
        nxt_unit_error(NULL,
                       "asgi_lifespan_send: 'type' is not a unicode string");
        return PyErr_Format(PyExc_TypeError,
                            "'type' is not a unicode string");
    }

    type_str = PyUnicode_AsUTF8AndSize(type, &type_len);

    nxt_unit_debug(NULL, "asgi_lifespan_send type is '%.*s'",
                   (int) type_len, type_str);

    if (type_len == (Py_ssize_t) startup_complete.length
        && memcmp(type_str, startup_complete.start, type_len) == 0)
    {
        return nxt_py_asgi_lifespan_send_startup(lifespan, 0, NULL);
    }

    if (type_len == (Py_ssize_t) startup_failed.length
        && memcmp(type_str, startup_failed.start, type_len) == 0)
    {
        msg = PyDict_GetItem(dict, nxt_py_message_str);
        return nxt_py_asgi_lifespan_send_startup(lifespan, 1, msg);
    }

    if (type_len == (Py_ssize_t) shutdown_complete.length
        && memcmp(type_str, shutdown_complete.start, type_len) == 0)
    {
        return nxt_py_asgi_lifespan_send_shutdown(lifespan, 0, NULL);
    }

    if (type_len == (Py_ssize_t) shutdown_failed.length
        && memcmp(type_str, shutdown_failed.start, type_len) == 0)
    {
        msg = PyDict_GetItem(dict, nxt_py_message_str);
        return nxt_py_asgi_lifespan_send_shutdown(lifespan, 1, msg);
    }

    return nxt_py_asgi_lifespan_disable(lifespan);
}

static PyObject *
nxt_py_asgi_lifespan_send_startup(nxt_py_asgi_lifespan_t *lifespan, int v,
    PyObject *message)
{
    const char  *message_str;
    Py_ssize_t  message_len;

    if (nxt_slow_path(v != 0)) {
        nxt_unit_error(NULL, "Application startup failed");

        if (nxt_fast_path(message != NULL && PyUnicode_Check(message))) {
            message_str = PyUnicode_AsUTF8AndSize(message, &message_len);

            nxt_unit_error(NULL, "%.*s", (int) message_len, message_str);
        }
    }

    return nxt_py_asgi_lifespan_send_(lifespan, v,
                                      &lifespan->startup_sent,
                                      &lifespan->startup_future);
}

static PyObject *
nxt_py_asgi_lifespan_send_(nxt_py_asgi_lifespan_t *lifespan, int v, int *sent,
    PyObject **pfuture)
{
    PyObject  *future, *res;

    if (*sent) {
        return nxt_py_asgi_lifespan_disable(lifespan);
    }

    *sent = 1 + v;

    if (*pfuture != NULL) {
        future = *pfuture;
        *pfuture = NULL;

        res = PyObject_CallMethodObjArgs(future, nxt_py_set_result_str,
                                         Py_None, NULL);
        if (nxt_slow_path(res == NULL)) {
            nxt_unit_alert(NULL, "Failed to call 'future.set_result'");
            nxt_python_print_exception();

            return nxt_py_asgi_lifespan_disable(lifespan);
        }

        Py_DECREF(res);
        Py_DECREF(future);
    }

    Py_INCREF(lifespan);

    return (PyObject *) lifespan;
}

static PyObject *
nxt_py_asgi_lifespan_disable(nxt_py_asgi_lifespan_t *lifespan)
{
    nxt_unit_warn(NULL, "Got invalid state transition on lifespan protocol");

    lifespan->disabled = 1;

    return PyErr_Format(PyExc_AssertionError,
                        "Got invalid state transition on lifespan protocol");
}

static PyObject *
nxt_py_asgi_lifespan_send_shutdown(nxt_py_asgi_lifespan_t *lifespan, int v,
    PyObject *message)
{
    return nxt_py_asgi_lifespan_send_(lifespan, v,
                                      &lifespan->shutdown_sent,
                                      &lifespan->shutdown_future);
}

static PyObject *
nxt_py_asgi_lifespan_done(PyObject *self, PyObject *future)
{
    PyObject                *res;
    nxt_py_asgi_lifespan_t  *lifespan;

    nxt_unit_debug(NULL, "asgi_lifespan_done");

    lifespan = (nxt_py_asgi_lifespan_t *) self;

    if (lifespan->startup_sent == 0) {
        lifespan->disabled = 1;
    }

    /*
     * Get Future.result() and it raises an exception, if coroutine exited
     * with exception.
     */
    res = PyObject_CallMethodObjArgs(future, nxt_py_result_str, NULL);
    if (nxt_slow_path(res == NULL)) {
        nxt_unit_log(NULL, NXT_UNIT_LOG_INFO,
                     "ASGI Lifespan processing exception");
        nxt_python_print_exception();
    }

    Py_XDECREF(res);

    if (lifespan->startup_future != NULL) {
        future = lifespan->startup_future;
        lifespan->startup_future = NULL;

        res = PyObject_CallMethodObjArgs(future, nxt_py_set_result_str,
                                         Py_None, NULL);
        if (nxt_slow_path(res == NULL)) {
            nxt_unit_alert(NULL, "Failed to call 'future.set_result'");
            nxt_python_print_exception();
        }

        Py_XDECREF(res);
        Py_DECREF(future);
    }

    if (lifespan->shutdown_future != NULL) {
        future = lifespan->shutdown_future;
        lifespan->shutdown_future = NULL;

        res = PyObject_CallMethodObjArgs(future, nxt_py_set_result_str,
                                         Py_None, NULL);
        if (nxt_slow_path(res == NULL)) {
            nxt_unit_alert(NULL, "Failed to call 'future.set_result'");
            nxt_python_print_exception();
        }

        Py_XDECREF(res);
        Py_DECREF(future);
    }

    Py_RETURN_NONE;
}

#endif /* NXT_HAVE_ASGI */


text:
.. include:: ../../Includes.txt

========================================================
Breaking: #68001 - Removed ExtJS Core and ExtJS Adapters
========================================================

See :issue:`68001`

Description
===========

The functionality of "ExtCore", which acts as a slim ExtJS base functionality similar to what libraries like underscore.js or jQuery do,
but is just dated, has been completely removed from the TYPO3 Core.

The custom adapters which have previously been shipped with ExtJS to allow jQuery functionality to be used
with ExtJS underneath have been removed without substitution. The adapters are not compatible with supported
jQuery, prototype.js or YUI versions anymore and their usages have been slower than ExtJS's base library natively.

Impact
======

Using TypoScript options `page.javascriptLibs.ExtCore = 1`, `page.javascriptLibs.ExtCore.debug = 1` and `page.javascriptLibs.ExtJs.adapter` have no effect anymore.

Using `<f:be.container>` ViewHelpers in a custom Backend module, setting the extJsAdapter, property will result in a fatal error.

Calling `$pageRenderer->loadExtJS()` with a custom third parameter will have no effect anymore.

Calling the methods `loadExtCore()`, `enableExtCoreDebug()`, `getExtCorePath()` and `setExtCorePath()` of `PageRenderer` will result in fatal errors.

Affected Installations
======================

Instances that use ExtCore in the TYPO3 Frontend

Extensions that use `<f:be.container>` with an ExtJS Adapter

Extensions that use the `PageRenderer` object directly to load custom ExtJS or ExtCore.

Migration
=========

Use alternatives for ExtCore or adapters in custom extensions.

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Data.Entity.Migrations;
using System.Net;
using System.Web;
using Example.MvcApplication.Data;

namespace Example.MvcApplication.Migrations
{
    internal sealed class Configuration : DbMigrationsConfiguration<DataContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(DataContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

            var codingTag = new BlogTagData {Title = "Coding"};
            var drawingTag = new BlogTagData {Title = "Drawing"};

            context.BlogTags
                   .AddOrUpdate(e => e.Title,
                                codingTag,
                                drawingTag);
            context.SaveChanges();

            context.BlogEntries
                   .AddOrUpdate(e => e.Title,
                                new BlogEntryData
                                    {
                                        Title = "Writing a Blog Engine",
                                        Identifier = BlogEntryData.GetIdentifier("Writing a Blog Engine"),
                                        Summary = "
How to write a blog entry in C#.NET
",
                                        Content =
                                            "
So you want to write yourself a blog engine eh?

Well lets get started
",
                                        Tags = new[] {codingTag},
                                        IsPublished = true,
                                        PublishedOn = DateTime.UtcNow
                                    },
                                new BlogEntryData
                                    {
                                        Title = "Keyword search support for EF",
                                        Identifier = BlogEntryData.GetIdentifier("Keyword search support for EF"),
                                        Summary = "
Adding support for keyword indexing to your entities
",
                                        Content =
                                            "
Adding support for keyword indexing to your entities
",
                                        Tags = new[] {codingTag},
                                        IsPublished = true,
                                        PublishedOn = DateTime.UtcNow
                                    },
                                new BlogEntryData
                                    {
                                        Title = "Drawing on the iPad",
                                        Identifier = BlogEntryData.GetIdentifier("Drawing on the iPad"),
                                        Summary = "
There are a number of good apps for drawing on the iPad
",
                                        Content =
                                            "
I have downloaded a few and compare them here
",
                                        Tags = new[] {drawingTag}
                                    });
            context.SaveChanges();
        }
    }
}


text:
#include "common.h"

namespace ofilters
{
   bool initialize( );
   bool uninitialize( );

   bool on_command( const ArgList& arg_list );
   long on_outbound_line( string* line, int from, size_t num );
}

#endif


text:
package au.net.thehardings.ims.mergereport.dispatch;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import au.net.thehardings.ims.mergereport.model.Commit;
import au.net.thehardings.ims.mergereport.model.Repository;

/**
 * The class FreemarkerDispatcher
 */
public abstract class FreemarkerDispatcher implements Dispatcher {

    Configuration cfg = new Configuration();

    protected FreemarkerDispatcher() {
        cfg.setClassForTemplateLoading(getClass(), "/templates/");
        cfg.setObjectWrapper(new DefaultObjectWrapper());
    }

    protected String process(Map<String, Object> context, String templateName) {
        try {
            Template template = cfg.getTemplate(templateName);
            StringWriter writer = new StringWriter();
            template.process(context, writer);
            return writer.toString();
        } catch (IOException e) {
            throw new RuntimeException("Couldn't get freemarker template named '" + templateName + "'.", e);
        } catch (TemplateException e) {
            throw new RuntimeException("Exception while processing template named '" + templateName + "'.", e);
        }
    }

    Map<String, Map<String, List<Commit>>> getUserCommits(List<Commit> outstanding) {
        Map<String, Map<String, List<Commit>>> users = new HashMap<String, Map<String, List<Commit>>>();
        for (Commit commit : outstanding) {
            Map<String, List<Commit>> userCommits = users.get(commit.getUsername());
            if (userCommits == null) {
                userCommits = new HashMap<String, List<Commit>>();
                users.put(commit.getUsername(), userCommits);
            }

            List<Commit> commits = userCommits.get(commit.getRepository().getName());
            if (commits == null) {
                commits = new ArrayList<Commit>();
                userCommits.put(commit.getRepository().getName(), commits);
            }
            commits.add(commit);
        }
        return users;
    }

    Map<String, Map<String, String>> getUserCommands(List<Commit> outstanding) {
        Map<String, Map<String, String>> commands = new HashMap<String, Map<String, String>>();
        Map<String, Repository> repositories = new HashMap<String, Repository>();

        for (Commit commit : outstanding) {
            if (!repositories.keySet().contains(commit.getRepository().getName())) {
                repositories.put(commit.getRepository().getName(), commit.getRepository());
            }

            Map<String, String> userCommands = commands.get(commit.getUsername());
            if (userCommands == null) {
                userCommands = new HashMap<String, String>();
                commands.put(commit.getUsername(), userCommands);
            }

            String command = userCommands.get(commit.getRepository().getName());
            if (command == null) {
                String mergeType = commit.getUsername().startsWith("zz") ? "--record-only " : "";
                command = "svn merge " + mergeType + "-c " + commit.getCommitId();
            } else {
                command = command.concat(",").concat(commit.getCommitId());
            }
            userCommands.put(commit.getRepository().getName(), command);
        }

        //need to do this at the end because the repository url is now the last thing on the command
        for (Map<String, String> userCommands : commands.values()) {
            for (String repositoryName : userCommands.keySet()) {
                Repository repository = repositories.get(repositoryName);
                String command = userCommands.get(repositoryName);
                command = command.concat(" ").concat(repository.getBranchUrl());
                userCommands.put(repositoryName, command);
            }
        }

        return commands;
    }
}


text:
namespace MobileDevice
{
    using System;

    public class Display
    {
        // Declaring fields
        private int? sizeOfDisplay;
        private int? numberOfColors;

        // Declaring constructors
        public Display()
        {
        }

        public Display(int? setSize = null)
        {
            this.SizeOfDisplay = setSize;
        }

        public Display(int? setSize, int? setNumberOfColors = null)
            : this(setSize)
        {
            this.NumberOfColors = setNumberOfColors;
        }

        // Declaring properties
        public int? SizeOfDisplay
        {
            get
            {
                return this.sizeOfDisplay;
            }

            set
            {
                if (value <= 0)
                {
                    throw new InvalidOperationException("The screen can't be equal or smaller than 0");
                }
                else
                {
                    this.sizeOfDisplay = value;
                }
            }
        }

        public int? NumberOfColors
        {
            get
            {
                return this.numberOfColors;
            }

            set
            {
                if (value <= 0)
                {
                    throw new InvalidOperationException("The number of colors must be bigger than 0");
                }
                else
                {
                    this.numberOfColors = value;
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Area
{
    class Program
    {
        static void Main(string[] args)
        {
            var r = float.Parse(Console.ReadLine());
            var area = Math.PI * r * r;
            Console.WriteLine(area);
            var perimeter = 2 * Math.PI * r;
            Console.WriteLine(perimeter);

        }
    }
}


text:
/*
 * Created on May 9, 2005
 *
 */
namespace NPOI.SS.Formula.Functions
{
    using NPOI.SS.Formula.Eval;

    /// <summary>
    /// Function serves as a marker interface.
    /// </summary>
    /// @author Amol S. Deshmukh < amolweb at ya hoo dot com >
    internal interface Function
    {

        /// <summary>
        /// Evaluates the specified args.
        /// </summary>
        /// <param name="args">the evaluated function arguments.  Empty values are represented with BlankEval or MissingArgEval</param>
        /// <param name="srcRowIndex">row index of the cell containing the formula under evaluation</param>
        /// <param name="srcColumnIndex">column index of the cell containing the formula under evaluation</param>
        /// <returns></returns>
        ValueEval Evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex);

    }
}


text:
module.exports = {
  description: "",
  ns: "react-material-ui",
  type: "ReactNode",
  dependencies: {
    npm: {
      "material-ui/svg-icons/image/flash-off": require('material-ui/svg-icons/image/flash-off')
    }
  },
  name: "ImageFlashOff",
  ports: {
    input: {},
    output: {
      component: {
        title: "ImageFlashOff",
        type: "Component"
      }
    }
  }
}


text:
package athena.api.Boosting.GradientBoostedTrees;

import athena.api.AthenaMLFeatureConfiguration;
import athena.api.Marking;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.function.Function;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.mllib.feature.Normalizer;
import org.apache.spark.mllib.linalg.Vector;
import org.apache.spark.mllib.linalg.Vectors;
import org.apache.spark.mllib.regression.LabeledPoint;
import org.apache.spark.mllib.tree.GradientBoostedTrees;
import org.apache.spark.mllib.tree.configuration.BoostingStrategy;
import org.apache.spark.mllib.tree.model.GradientBoostedTreesModel;
import org.bson.BSONObject;
import org.onosproject.athena.database.AthenaFeatureField;
import scala.Tuple2;

import java.io.Serializable;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;

/**
 * Created by seunghyeon on 5/2/16.
 */
public class GradientBoostedTreesDistJob implements Serializable {
    public GradientBoostedTreesDistJob() {
    }

    public GradientBoostedTreesModel generateKMeansModel(JavaRDD<LabeledPoint> parsedData,
                                                         GradientBoostedTreesDetectionAlgorithm gradientBoostedTreesDetectionAlgorithm,
                                                         GradientBoostedTreesModelSummary gradientBoostedTreesModelSummary) {
        BoostingStrategy boostingStrategy = BoostingStrategy.defaultParams("Classification");
        boostingStrategy.setNumIterations(gradientBoostedTreesDetectionAlgorithm.getIterations());
        boostingStrategy.getTreeStrategy().setNumClasses(gradientBoostedTreesDetectionAlgorithm.getNumClasses());
        boostingStrategy.getTreeStrategy().setMaxDepth(gradientBoostedTreesDetectionAlgorithm.getMaxDepth());
        boostingStrategy.treeStrategy().setCategoricalFeaturesInfo(gradientBoostedTreesDetectionAlgorithm.getCategoricalFeaturesInfo());

        GradientBoostedTreesModel gradientBoostedTreesModel
                = GradientBoostedTrees.train(parsedData, boostingStrategy);

        gradientBoostedTreesModelSummary.setGradientBoostedTreesDetectionAlgorithm(gradientBoostedTreesDetectionAlgorithm);
        return gradientBoostedTreesModel;
    }

    public GradientBoostedTreesModel generateDecisionTreeWithPreprocessing(JavaPairRDD<Object, BSONObject> mongoRDD,
                                                                   AthenaMLFeatureConfiguration athenaMLFeatureConfiguration,
                                                                   GradientBoostedTreesDetectionAlgorithm gradientBoostedTreesDetectionAlgorithm,
                                                                   Marking marking,
                                                                   GradientBoostedTreesModelSummary gradientBoostedTreesModelSummary) {

        return generateKMeansModel(
                rddPreProcessing(mongoRDD, athenaMLFeatureConfiguration, gradientBoostedTreesModelSummary,
                        marking),
                gradientBoostedTreesDetectionAlgorithm, gradientBoostedTreesModelSummary
        );
    }

    public JavaRDD<LabeledPoint> rddPreProcessing(JavaPairRDD<Object, BSONObject> mongoRDD,
                                                  AthenaMLFeatureConfiguration athenaMLFeatureConfiguration,
                                                  GradientBoostedTreesModelSummary gradientBoostedTreesModelSummary,
                                                  Marking marking) {
        List<AthenaFeatureField> listOfTargetFeatures = athenaMLFeatureConfiguration.getListOfTargetFeatures();
        Map<AthenaFeatureField, Integer> weight = athenaMLFeatureConfiguration.getWeight();

        int numberOfTargetValue = listOfTargetFeatures.size();
        Normalizer normalizer = new Normalizer();

        JavaRDD<LabeledPoint> parsedData = mongoRDD.map(
                (Function<Tuple2<Object, BSONObject>, LabeledPoint>) t -> {

                    BSONObject feature = (BSONObject) t._2().get(AthenaFeatureField.FEATURE);
                    BSONObject idx = (BSONObject) t._2();
                    int label = marking.checkClassificationMarkingElements(idx, feature);
                    double[] values = new double[numberOfTargetValue];
                    for (int j = 0; j < numberOfTargetValue; j++) {
                        if (feature.containsField(listOfTargetFeatures.get(j).getValue())) {
                            Object obj = feature.get(listOfTargetFeatures.get(j).getValue());
                            if (obj instanceof Long) {
                                values[j] = (Long) obj;
                            } else if (obj instanceof Double) {
                                values[j] = (Double) obj;
                            } else if (obj instanceof Boolean) {
                                values[j] = (Boolean) obj ? 1 : 0;
                            } else {
                                values[j] = 0;
                            }

                            //check weight
                            if (weight.containsKey(listOfTargetFeatures.get(j))) {
                                values[j] *= weight.get(listOfTargetFeatures.get(j));
                            }
                            //check absolute
                            if (athenaMLFeatureConfiguration.isAbsolute()){
                                values[j] = Math.abs(values[j]);
                            }
                        }
                    }

                    //remove errors
                    for (int i = 0; i < numberOfTargetValue; i++) {
                        if (Double.isInfinite(values[i]) || Double.isNaN(values[i])) {
                            for (int j = 0; j < numberOfTargetValue; j++) {
                                values[j] = 0;

                            }
                            return new LabeledPoint(label, Vectors.dense(values));
                        }
                    }

                    Vector normedForVal;
                    if (athenaMLFeatureConfiguration.isNormalization()) {
                        normedForVal = normalizer.transform(Vectors.dense(values));
                    } else {
                        normedForVal = Vectors.dense(values);
                    }

                    gradientBoostedTreesModelSummary.updateSummary(idx, feature);
                    return new LabeledPoint(label, normedForVal);
                }
        );

        return parsedData;
    }

    public void validate(JavaPairRDD<Object, BSONObject> mongoRDD,
                         AthenaMLFeatureConfiguration athenaMLFeatureConfiguration,
                         GradientBoostedTreesDetectionModel gradientBoostedTreesDetectionModel,
                         GradientBoostedTreesValidationSummary gradientBoostedTreesValidationSummary) {
        List<AthenaFeatureField> listOfTargetFeatures = athenaMLFeatureConfiguration.getListOfTargetFeatures();
        Map<AthenaFeatureField, Integer> weight = athenaMLFeatureConfiguration.getWeight();
        Marking marking = gradientBoostedTreesDetectionModel.getMarking();
        GradientBoostedTreesModel model = (GradientBoostedTreesModel) gradientBoostedTreesDetectionModel.getDetectionModel();
        Normalizer normalizer = new Normalizer();

        int numberOfTargetValue = listOfTargetFeatures.size();

        mongoRDD.foreach(new VoidFunction<Tuple2<Object, BSONObject>>() {
            public void call(Tuple2<Object, BSONObject> t) throws UnknownHostException {
                long start2 = System.nanoTime(); // <-- start
                BSONObject feature = (BSONObject) t._2().get(AthenaFeatureField.FEATURE);
                BSONObject idx = (BSONObject) t._2();
                int originLabel = marking.checkClassificationMarkingElements(idx,feature);

                double[] values = new double[numberOfTargetValue];
                for (int j = 0; j < numberOfTargetValue; j++) {
                    values[j] = 0;
                    if (feature.containsField(listOfTargetFeatures.get(j).getValue())) {
                        Object obj = feature.get(listOfTargetFeatures.get(j).getValue());
                        if (obj instanceof Long) {
                            values[j] = (Long) obj;
                        } else if (obj instanceof Double) {
                            values[j] = (Double) obj;
                        } else if (obj instanceof Boolean) {
                            values[j] = (Boolean) obj ? 1 : 0;
                        } else {
                            return;
                        }

                        //check weight
                        if (weight.containsKey(listOfTargetFeatures.get(j))) {
                            values[j] *= weight.get(listOfTargetFeatures.get(j));
                        }

                        //check absolute
                        if (athenaMLFeatureConfiguration.isAbsolute()){
                            values[j] = Math.abs(values[j]);
                        }
                    }
                }

                Vector normedForVal;
                if (athenaMLFeatureConfiguration.isNormalization()) {
                    normedForVal = normalizer.transform(Vectors.dense(values));
                } else {
                    normedForVal = Vectors.dense(values);
                }

                LabeledPoint p = new LabeledPoint(originLabel,normedForVal);

                int validatedLabel = (int) model.predict(p.features());

                gradientBoostedTreesValidationSummary.updateSummary(validatedLabel,idx,feature);

                long end2 = System.nanoTime();
                long result2 = end2 - start2;
                gradientBoostedTreesValidationSummary.addTotalNanoSeconds(result2);
            }
        });
        gradientBoostedTreesValidationSummary.getAverageNanoSeconds();
        gradientBoostedTreesValidationSummary.setGradientBoostedTreesDetectionAlgorithm((GradientBoostedTreesDetectionAlgorithm) gradientBoostedTreesDetectionModel.getDetectionAlgorithm());
    }

}


text:
#include <uwsgi.h>
#include <curl/curl.h>

extern struct uwsgi_server uwsgi;

struct uwsgi_alarm_curl {
	CURL	*curl;
	struct uwsgi_thread *ut;
	int	pos;
	int	blen;
	char	*body;
	int	hlen;
	char	hdr[];
};

struct uwsgi_alarm_curl_config {
	char *url;
	char *subject;
	char *to;
};

struct uwsgi_alarm_curl_opt {
	char *name;
	CURLoption option;
	void (*func)(CURL *, CURLoption, char *, struct uwsgi_alarm_curl_config*);
};

#ifdef CURLPROTO_SMTP
static void uwsgi_alarm_curl_to(CURL *curl, CURLoption option, char *arg, struct uwsgi_alarm_curl_config *uacc) {
	uacc->to = arg;
	struct curl_slist *list = NULL;
	char *items = uwsgi_str(arg);
	char *ctx = NULL;
	char *p = strtok_r(items, ",", &ctx);
	while(p) {
		list = curl_slist_append(list, p);
		p = strtok_r(NULL, ",", &ctx);
	}
	curl_easy_setopt(curl, option, list);
	free(items);
}
#endif

static void uwsgi_alarm_curl_ssl(CURL *curl, CURLoption option, char *arg, struct uwsgi_alarm_curl_config *uacc) {
	curl_easy_setopt(curl, option, (long)CURLUSESSL_ALL);
}

static void uwsgi_alarm_curl_int(CURL *curl, CURLoption option, char *arg, struct uwsgi_alarm_curl_config *uacc) {
        curl_easy_setopt(curl, option, atoi(arg));
}

static void uwsgi_alarm_curl_set_subject(CURL *curl, CURLoption option, char *arg, struct uwsgi_alarm_curl_config *uacc) {
	uacc->subject = arg;
}

static void uwsgi_alarm_curl_url(CURL *curl, CURLoption option, char *arg, struct uwsgi_alarm_curl_config *uacc)
{
#ifndef CURLPROTO_SMTP
	if (!uwsgi_strnicmp(arg, 4, "smtp", 4)) {
		uwsgi_error("Please update libcurl to use SMTP protocol.\n");
		exit(1);
	}
#endif
	uacc->url = arg;
	curl_easy_setopt(curl, option, arg);
}

static void uwsgi_alarm_curl_ssl_insecure(CURL *curl, CURLoption option, char *arg, struct uwsgi_alarm_curl_config *uacc)
{
	curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
	curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
}

static struct uwsgi_alarm_curl_opt uaco[] = {
	{"url", CURLOPT_URL, uwsgi_alarm_curl_url},
#ifdef CURLPROTO_SMTP
	{"mail_to", CURLOPT_MAIL_RCPT, uwsgi_alarm_curl_to},
	{"mail_from", CURLOPT_MAIL_FROM, NULL},
#endif
	{"subject", 0, uwsgi_alarm_curl_set_subject},
	{"ssl", CURLOPT_USE_SSL, uwsgi_alarm_curl_ssl},
	{"ssl_insecure", 0, uwsgi_alarm_curl_ssl_insecure},
	{"auth_user", CURLOPT_USERNAME, NULL},
	{"auth_pass", CURLOPT_PASSWORD, NULL},
	{"method", CURLOPT_CUSTOMREQUEST, NULL},
	{"timeout", CURLOPT_TIMEOUT, uwsgi_alarm_curl_int},
	{"conn_timeout", CURLOPT_CONNECTTIMEOUT, uwsgi_alarm_curl_int},
	{NULL, 0, NULL},
};

static void uwsgi_alarm_curl_setopt(CURL *curl, char *opt, struct uwsgi_alarm_curl_config *uacc) {
	struct uwsgi_alarm_curl_opt *o = uaco;
	char *equal = strchr(opt,'=');
	if (!equal && !uacc->url) {
		uwsgi_alarm_curl_url(curl, CURLOPT_URL, opt, uacc);
		return;
	}
	*equal = 0;
	while(o->name) {
		if (!strcmp(o->name, opt)) {
			if (o->func) {
				o->func(curl, o->option, equal+1, uacc);
			}
			else {
				curl_easy_setopt(curl, o->option, equal+1);
			}
			break;
		}
		o++;
	}
}

static size_t uwsgi_alarm_curl_read_callback(void *ptr, size_t size, size_t nmemb, void *userp) {
	struct uwsgi_alarm_curl *uac = userp;
	size_t full_size = size * nmemb;
	int remains = full_size;

	if (uac->pos < uac->hlen) {
		if (remains > uac->hlen - uac->pos) {
			memcpy(ptr, uac->hdr + uac->pos, uac->hlen - uac->pos);
			ptr += uac->hlen - uac->pos;
			remains -= uac->hlen - uac->pos;
			uac->pos = uac->hlen;
		} else {
			memcpy(ptr, uac->hdr + uac->pos, remains);
			uac->pos += remains;
			return full_size;
		}
	}

	if (remains > uac->blen + uac->hlen - uac->pos) {
		memcpy(ptr, uac->body + uac->pos - uac->hlen, uac->blen + uac->hlen - uac->pos);
		remains -= uac->blen + uac->hlen - uac->pos;
		uac->pos = uac->blen + uac->hlen;
		return full_size - remains;
	}

	memcpy(ptr, uac->body + uac->pos - uac->hlen, remains);
	uac->pos += remains;
	return full_size;
}

static struct uwsgi_alarm_curl *uwsgi_alarm_curl_alloc(struct uwsgi_alarm_curl_config *uacc)
{
	char *addr;
	struct uwsgi_alarm_curl *uac;
	size_t required = 0;

	if (uacc->to) required += 4 + strlen(uacc->to) + 2;
	if (uacc->subject) required += 9 + strlen(uacc->subject) + 2;
	if (required)
		required += 2;	/* newline between MIME header and body */

	uac = uwsgi_malloc(sizeof(*uac) + required);
	uac->hlen = required;
	addr = uac->hdr;

	if (uacc->to) {
		memcpy(addr, "To: ", 4); addr += 4;
		memcpy(addr, uacc->to, strlen(uacc->to)); addr += strlen(uacc->to);
		*addr++ = '\r';
		*addr++ = '\n';
	}

	if (uacc->subject) {
		memcpy(addr, "Subject: ", 9); addr += 9;
		memcpy(addr, uacc->subject, strlen(uacc->subject)); addr += strlen(uacc->subject);
		*addr++ = '\r';
		*addr++ = '\n';
	}

	if (required) {
		*addr++ = '\r';
		*addr = '\n';
	}

	return uac;
}

static struct uwsgi_alarm_curl *uwsgi_alarm_curl_init_curl(struct uwsgi_alarm_instance *uai) {
	CURL *curl = curl_easy_init();
	if (!curl) {
		uwsgi_error("Failed to initialize libcurl.\n");
		exit(1);
	}

	curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, uwsgi.socket_timeout);
	curl_easy_setopt(curl, CURLOPT_TIMEOUT, uwsgi.socket_timeout);
	curl_easy_setopt(curl, CURLOPT_READFUNCTION, uwsgi_alarm_curl_read_callback);
	curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
	curl_easy_setopt(curl, CURLOPT_POST, 1L);
	struct curl_slist *expect = NULL; expect = curl_slist_append(expect, "Expect:");
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, expect);
	curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1);

	struct uwsgi_alarm_curl_config uacc;
	memset(&uacc, 0, sizeof(uacc));
	char *opts = uwsgi_str(uai->arg);

	// fill curl options
	char *ctx = NULL;
	char *p = strtok_r(opts, ";", &ctx);
	while(p) {
		uwsgi_alarm_curl_setopt(curl, p, &uacc);
		p = strtok_r(NULL, ";", &ctx);
	}

	if (!uacc.url) {
		uwsgi_error("An URL is required to trigger curl-based alarm.\n");
		exit(1);
	}

	struct uwsgi_alarm_curl *uac = uwsgi_alarm_curl_alloc(&uacc);
	curl_easy_setopt(curl, CURLOPT_READDATA, uac);
	free(opts);
	uac->curl = curl;
	uai->data_ptr = uac;

	return uac;
}

static void uwsgi_alarm_curl_call_curl(struct uwsgi_alarm_curl *uac, char *msg, int len)
{
	uac->pos = 0;
	uac->body = msg;
	uac->blen = len;
	curl_easy_setopt(uac->curl, CURLOPT_INFILESIZE, uac->hlen + uac->blen);
	CURLcode res = curl_easy_perform(uac->curl);
	if (res != CURLE_OK)
		uwsgi_log_alarm("-curl] curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}

static void uwsgi_alarm_curl_loop(struct uwsgi_thread *ut) {
	int interesting_fd;
	struct uwsgi_alarm_curl *uac = uwsgi_alarm_curl_init_curl(ut->data);
	uac->ut = ut;
	ut->buf = uwsgi_malloc(uwsgi.log_master_bufsize);
	for(;;) {
		int ret = event_queue_wait(ut->queue, -1, &interesting_fd);
		if (ret < 0) return;
		if (ret == 0) continue;
		if (interesting_fd != ut->pipe[1]) continue;
		ssize_t rlen = read(ut->pipe[1], ut->buf, uwsgi.log_master_bufsize);
		if (rlen <= 0) continue;
		uwsgi_alarm_curl_call_curl(uac, ut->buf, rlen);
	}
}

static void uwsgi_alarm_curl_init(struct uwsgi_alarm_instance *uai) {
	if (uwsgi.alarm_cheap)
		uwsgi_alarm_curl_init_curl(uai);
	else
		uwsgi_thread_new_with_data(uwsgi_alarm_curl_loop, uai);
}

// pipe the message into the thread;
static void uwsgi_alarm_curl_func(struct uwsgi_alarm_instance *uai, char *msg, size_t len) {
	struct uwsgi_alarm_curl *uac = uai->data_ptr;
	if (uwsgi.alarm_cheap)
		uwsgi_alarm_curl_call_curl(uac, msg, len);
	else {
		struct uwsgi_thread *ut = uac->ut;
		ut->rlen = write(ut->pipe[0], msg, len);
	}
}

static void uwsgi_alarm_curl_load(void) {
	uwsgi_register_alarm("curl", uwsgi_alarm_curl_init, uwsgi_alarm_curl_func);
}

struct uwsgi_plugin alarm_curl_plugin = {
	.name = "alarm_curl",
	.on_load = uwsgi_alarm_curl_load,
};


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;

namespace Azure.Management.Storage.Models
{
    public partial class ListTableServices
    {
        internal static ListTableServices DeserializeListTableServices(JsonElement element)
        {
            IReadOnlyList<TableServiceProperties> value = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("value"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        continue;
                    }
                    List<TableServiceProperties> array = new List<TableServiceProperties>();
                    foreach (var item in property.Value.EnumerateArray())
                    {
                        if (item.ValueKind == JsonValueKind.Null)
                        {
                            array.Add(null);
                        }
                        else
                        {
                            array.Add(TableServiceProperties.DeserializeTableServiceProperties(item));
                        }
                    }
                    value = array;
                    continue;
                }
            }
            return new ListTableServices(value);
        }
    }
}


text:
package model.population;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import model.solvers.fitness.Fitness;

public class Population {
	private List<Individual> individuals;
	private double totalFitness;

    public Population() {
        this.individuals = new ArrayList<Individual>();
    }

	public void evaluateMinimize(Fitness fitness){
		fitness.setCurrentPopulation(this);
		totalFitness = 0.0;
		double popMax = Double.MIN_VALUE;
		for (Individual i : individuals){
			i.evaluate(fitness);
			popMax = Math.max(i.getAbsoluteFitness(), popMax);
		}

		for (Individual i: individuals) {
			i.shiftMinimize(popMax, fitness);
			totalFitness += i.getShiftedFitness();
		}
	}

	public void evaluateMaximize(Fitness fitness){
		fitness.setCurrentPopulation(this);
		totalFitness = 0.0;
		double popMin = Double.MAX_VALUE;
		for (Individual i : individuals){
			i.evaluate(fitness);
			popMin = Math.min(i.getAbsoluteFitness(), popMin);
		}

		for (Individual i: individuals) {
			i.shiftMaximize(popMin, fitness);
			totalFitness += i.getShiftedFitness();
		}
	}

	public int getSize(){
		return individuals.size();
	}

	public List<Individual> getPopulation(){
		return individuals;
	}

	public double getTotalFitness(){
		return totalFitness;
	}

	public void addIndividual(Individual indiv){
		Individual indToAdd = new Individual(indiv.getGenome().returnCopy());
		individuals.add(indToAdd);
	}

	public void addIndividualNoCopy(Individual indiv) {
		individuals.add(indiv);
	}

    @Override
    public String toString() {
	    StringBuilder ret = new StringBuilder();
	    ret.append("Population {\n");
	    for (Individual ind : individuals) {
	        ret.append(ind.toString());
	        ret.append("\n");
        }
        ret.append("    Total Fitness=");
        ret.append(totalFitness);
        ret.append("\n");
        ret.append("}\n");
        return ret.toString();
    }

	public Population saveElite(double elitismPercent, Comparator<Individual> c) {
		Population elitism = new Population();
		int sizeElite = (int)  Math.ceil(individuals.size() * elitismPercent); //We decided to make the ceil of the percentage because if the user want a 0.1% we think is better to save an individual than none.
		Collections.sort(individuals, c);
		for(int i = 0; i < sizeElite; i++){
			elitism.addIndividual(new Individual(individuals.get(i).getGenome()));
		}

		return elitism;
	}

	public void dropWorse(double elitismPercent, Comparator<Individual> c) {
		int sizeElite = (int)  Math.ceil(individuals.size() * elitismPercent);
		Collections.sort(individuals, c);
		int loopLimit = this.getSize() - sizeElite;
		for(int i = getSize()-1; i > loopLimit-1; i--){
			individuals.remove(i);
		}
	}

	public void insertAll(Population elitism) {
		for(Individual i: elitism.individuals){
			 individuals.add(i);
		}

	}

	public Individual getBest(Comparator<Individual> comp) {
		Collections.sort(individuals, comp);
		Individual ret = new Individual(individuals.get(0));
		return ret;
	}
}


text:
"use strict";
var runtime = require("../../../runtime");
var helper = require("./helper"), compile=helper.compile;

if (typeof document !== 'undefined') { // simple trick to prevent this running by mocha from NodeJs
    describe("IT: in-browser compilation (necessary for demos and other ITs)", function () {

        var run ,  app;
        before(function(){ run= helper.before(); app = run.app; });
        after(function(){ helper.after(run)});

        it("works", function () {
            return run(compile("Hello World")).then(function () {
                expect(run.container.innerHTML).to.be.equal("Hello World");
            });
        });

        it("dependencies are resolved", function () {
            return run(compile('<t:require rt="runtime"/><t:get text="rt.promise.resolve(\'Hello World\')"><t:get text="text"/></t:get>',{
                runtime: runtime
            })).then(function () {
                expect(run.container.innerHTML).to.be.equal("Hello World");
            });
        });

    });
}


text:
package auth

import (
	"errors"
	"fmt"
)

var (
	ErrAuthFailure          = errors.New("auth: Authentication failure")
	ErrAuthProviderNotFound = errors.New("auth: Authentication provider not found")

	providers = make(map[string]Authenticator)
)

type Authenticator interface {
	Authenticate(id string, cred interface{}) error
}

func Register(name string, provider Authenticator) {
	if provider == nil {
		panic("auth: Register provide is nil")
	}

	if _, dup := providers[name]; dup {
		panic("auth: Register called twice for provider " + name)
	}

	providers[name] = provider
}

func Unregister(name string) {
	delete(providers, name)
}

type Manager struct {
	p Authenticator
}

func NewManager(providerName string) (*Manager, error) {
	p, ok := providers[providerName]
	if !ok {
		return nil, fmt.Errorf("session: unknown provider %q", providerName)
	}

	return &Manager{p: p}, nil
}

func (this *Manager) Authenticate(id string, cred interface{}) error {
	return this.p.Authenticate(id, cred)
}


text:
package org.assertj.core.api;

/**
 * Assertion methods for {@link Short}s.
 *

 * To create an instance of this class, invoke {@link Assertions#assertThat(Short)} or
 * {@link Assertions#assertThat(short)}.
 *

 *
 * @author Yvonne Wang
 * @author David DIDIER
 * @author Ansgar Konermann
 * @author Alex Ruiz
 * @author Mikhail Mazursky
 * @author Nicolas François
 */
public class ShortAssert extends AbstractShortAssert<ShortAssert> {

  public ShortAssert(Short actual) {
    super(actual, ShortAssert.class);
  }
}


text:
NXTInvaders
===========

A Space Invaders clone for the Lego Mindstorms NXT.

This game is written in the NXC language. To compile on Windows use the BricxCC
IDE avaliable at http://bricxcc.sourceforge.net/nbc/. On Linux systems install
the NBC compiler available on the same page and run make.


text:
/* AUTO-GENERATED FILE.  DO NOT MODIFY.
 *
 * This class was automatically generated by the
 * aapt tool from the resource data it found.  It
 * should not be modified by hand.
 */

package com.socrata.android.tests;

public final class Manifest {
    public static final class permission {
        public static final String C2D_MESSAGE="com.socrata.android.tests.permission.C2D_MESSAGE";
    }
}


text:
/*
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package dk.statsbiblioteket.summa.common.util;

import dk.statsbiblioteket.util.Streams;

import java.io.ByteArrayOutputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Random;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Test {@link ReaderInputStream}.
 */
public class ReaderInputStreamTest extends TestCase {
    /** Local logger. */
    private static Log log = LogFactory.getLog(ReaderInputStreamTest.class);
    /** Default encoding. */
    public static final String ENCODING = "utf-8";

    /**
     * Constructor.
     * @param name The name.
     */
    public ReaderInputStreamTest(String name) {
        super(name);
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
    }

    @Override
    public void tearDown() throws Exception {
        super.tearDown();
    }

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

    public void testBasics() throws Exception {
        assertConvert("Simple", "Hello world");
        assertConvert("Empty", "");
        assertConvert("Danish", "æøå");
        assertConvert("Long", "abcdefghijklmnopqrstuvwxyzæøåABCDEFGHIJKLMNOPQRS"
                              + "TUVWXYZÆØÅ!\"#¤%&/()=?`´1234567890 -.,;:_*'¨^½"
                              + "§<>\\");
    }

    /**
     * This unit test will fail on multi-char unicode characters as described
     * in the class documentation for {@link ReaderInputStream}. We keep it
     * enabled to ensure we don't forget about this!
     * @throws Exception always
     */
    public void testMonkey() throws Exception {
        //System.out.println("Test monkey");
        final int runs = 5000;
        final int max = 30;
        Random random = new Random(86);
        for (int run = 0; run < runs; run++) {
            int length = random.nextInt(max);
            StringWriter sw = new StringWriter(length);
            for (int i = 0; i < length; i++) {
                sw.append((char) random.nextInt(10000));
            }
            assertConvert("Monkey test #" + run, sw.toString());
        }
        //System.out.println("Test monkey end");
    }

    public void testLength() throws Exception {
        final int max = 500;
        for (int length = 0; length < max; length++) {
            StringWriter sw = new StringWriter(length);
            for (int i = 0; i < length; i++) {
                sw.append("A");
            }
            assertConvert("Test of length " + length, sw.toString());
        }
    }

    /**
     * This unit test will fail on multi-char unicode characters as described
     * in the class documentation for {@link ReaderInputStream}. We keep it
     * enabled to ensure we don't forget about this!
     * @throws Exception always
     */
    public void testAll() throws Exception {
        final int part = 30;
        final int max = 10000;
        char c = 0;
        while (c < max) {
            StringWriter sw = new StringWriter(part);
            char startPos = c;
            for (int i = 0; i < part; i++) {
                sw.append(c++);
                if (c == max) {
                    break;
                }
            }
            assertConvert("Pos " + (int) startPos, sw.toString());
        }
    }

    /**
     * Disabled (remove x from methodname)
     *
     * This unit test will fail on multi-char unicode characters as described
     * in the class documentation for {@link ReaderInputStream}. We keep it
     * enabled to ensure we don't forget about this!
     * @throws Exception always
     */
    public void xtest56300() throws Exception {
        final int high = 56300;
        final int length = 30;
        StringWriter sw = new StringWriter(length);
        for (int i = 0; i < length; i++) {
            sw.append((char) (high + i));
        }
        assertConvert("Chars at position " + high + " test", sw.toString());
    }

    private void assertConvert(String message, String input) throws Exception {
        byte[] expected = input.getBytes(ENCODING);
        Reader in = new StringReader(input);
        ReaderInputStream is = new ReaderInputStream(in, ENCODING);
        ByteArrayOutputStream os = new ByteArrayOutputStream(expected.length);
        Streams.pipe(is, os);
        byte[] actual = os.toByteArray();
        if (expected.length != actual.length) {
            StringWriter sw = new StringWriter(input.length() * 10);
            sw.append("Diff for bytes:");
            for (int i = 0; i < Math.max(expected.length, actual.length); i++) {
                sw.append(String.format(" (%s, %s)",
                        expected.length > i ? Byte.toString(expected[i]) : "NA",
                        actual.length > i ? Byte.toString(actual[i]) : "NA"));
            }
            log.info(sw.toString());
            //System.out.println(sw.toString());
            // TODO use assert

            sw = new StringWriter(100);
            sw.append("Input chars:");
            for (char c : input.toCharArray()) {
                sw.append(" ").append(Integer.toString(c));
            }
            log.info(sw.toString());
            // TODO use assert
        }
        assertEquals(message + " should result in the right number of bytes.\n"
                     + "Input was '" + input + "'",
                     expected.length, actual.length);
        for (int i = 0; i < expected.length; i++) {
            assertEquals(message + " should have the same content. The bytes at"
                         + " position " + i + " differs. "
                         + "Input was '" + input + "'",
                         expected[i], actual[i]);
        }
    }
}


text:
package org.apereo.cas.services;

import org.apereo.cas.services.util.RegisteredServiceAccessStrategyEvaluator;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;

import java.io.Serial;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * This is {@link SurrogateRegisteredServiceAccessStrategy}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
public class SurrogateRegisteredServiceAccessStrategy extends BaseSurrogateRegisteredServiceAccessStrategy {

    @Serial
    private static final long serialVersionUID = -1688944419711632962L;

    /**
     * Defines the attribute aggregation behavior when checking for required attributes.
     * Default requires that all attributes be present and match the principal's.
     */
    protected boolean requireAllAttributes = true;

    /**
     * Indicates whether matching on required attribute values
     * should be done in a case-insensitive manner.
     */
    protected boolean caseInsensitive;

    private boolean surrogateEnabled;

    private Map<String, Set<String>> surrogateRequiredAttributes = new HashMap<>(0);

    @Override
    public boolean doPrincipalAttributesAllowServiceAccess(final RegisteredServiceAccessStrategyRequest request) {
        if (isSurrogateAuthenticationSession(request)) {
            return isSurrogateEnabled() && doPrincipalAttributesAllowSurrogateServiceAccess(request);
        }
        return true;
    }

    protected boolean doPrincipalAttributesAllowSurrogateServiceAccess(final RegisteredServiceAccessStrategyRequest request) {
        return RegisteredServiceAccessStrategyEvaluator.builder()
            .caseInsensitive(this.caseInsensitive)
            .requireAllAttributes(this.requireAllAttributes)
            .requiredAttributes(this.surrogateRequiredAttributes)
            .rejectedAttributes(new LinkedHashMap<>(0))
            .build()
            .apply(request);
    }
}


text:
class sudoku_solver
{
public:
    virtual bool solve(sudoku_puzzle & puzzle) = 0;
    bool         solved(const sudoku_puzzle & puzzle);
};

#endif


text:
Bisnode CSS stylesheets

for global usage


text:
require "def_resource/controller_extension"

module DefResource
  class Engine < Rails::Engine
    config.after_initialize do
      ActionController::Base.class_eval do
        include DefResource::ControllerExtension
      end
    end
  end
end


text: Additional arguments for the JVM, such as -Xmx.


text:
function DroidScriptLayout(type, options) {
    this.className='new_DroidScriptLayout';
    this.objId=newObjId();
    this.type=type;
    this.background="";
    this.backGradient={color1:'#000000',color2:'#000000',color3:'#000000',
                x1:0,y1:0, x2:1,y2:1};
    this.children=[];
    this.padding=[0,0,0,0];
    this.options=options;
    //this.width=640;
    //this.height=480;
    _rmt.call(this, Array.from(arguments));
};

// options=repeat
DroidScriptLayout.prototype.SetBackground=function(path, options) {
    options=options.toLowerCase();
    this.background=path;
    this.options=options;
    this.backgroundRepeat = (options.indexOf('repeat') > -1) ? 'repeat' : 'no-repeat';
    //try { fs.accessSync(path); this.background=path; }
    //catch(e) {}
    _rmt.call(this, Array.from(arguments));
}
DroidScriptLayout.prototype.AddChild=function(child,order) { // > order = foreground
    _SetParent(child, {objId:this.objId});
    // 0 = back, end of list=front (drawn last)
    if(order < 0) { order=-order; }
    if(!order || order > this.children.length) { order=this.children.length; }
    this.children.splice(order, 0, {objId:child.objId});
    var args=Array.from(arguments);
    args[0]={objId:child.objId};
    _rmt.call(this, args);
}
DroidScriptLayout.prototype.SetPadding=function(left,top,right,bottom) {
    this.padding={left:left,top:top,right:right,bottom:bottom};
    _rmt.call(this, Array.from(arguments));
}
DroidScriptLayout.prototype.SetVisibility=function(mode) { // Show, Hide, Gone
    this.visibleMode=mode;
    _rmt.call(this, Array.from(arguments));
}
DroidScriptLayout.prototype.SetSize=function(width,height) {
    this.width=width;
    this.height=height;
    _rmt.call(this, Array.from(arguments));
}
// This sets 3 Background Colors for the Layout which are split at a
// Line between x1,y1 and x2,y2.
DroidScriptLayout.prototype.SetBackGradient=function(color1,color2,color3, x1,y1, x2,y2) {
    this.backGradient={color1:color1,color2:color2,color3:color3,
                x1:x1,y1:y1, x2:x2,y2:y2};
    _rmt.call(this, []);
}


text:
package com.notronix.lw.api.model;

import java.util.UUID;

public class AddImageToInventoryItemRequest
{
    private String ItemNumber;
    private UUID StockItemId;
    private Boolean IsMain;
    private String ImageUrl;

    public String getItemNumber() {
        return ItemNumber;
    }

    public void setItemNumber(String itemNumber) {
        ItemNumber = itemNumber;
    }

    public UUID getStockItemId() {
        return StockItemId;
    }

    public void setStockItemId(UUID stockItemId) {
        StockItemId = stockItemId;
    }

    public Boolean getMain() {
        return IsMain;
    }

    public void setMain(Boolean main) {
        IsMain = main;
    }

    public String getImageUrl() {
        return ImageUrl;
    }

    public void setImageUrl(String imageUrl) {
        ImageUrl = imageUrl;
    }
}


text:
"""
This module implements functions to perform various useful operations on
entries, such as grouping entries by structure.
"""

from __future__ import annotations

import collections
import csv
import datetime
import itertools
import json
import logging
import re
from typing import Iterable, List, Literal

from monty.json import MontyDecoder, MontyEncoder, MSONable
from monty.string import unicode2str

from pymatgen.analysis.phase_diagram import PDEntry
from pymatgen.analysis.structure_matcher import SpeciesComparator, StructureMatcher
from pymatgen.core.composition import Composition
from pymatgen.core.periodic_table import Element
from pymatgen.entries import Entry
from pymatgen.entries.computed_entries import ComputedEntry, ComputedStructureEntry

logger = logging.getLogger(__name__)

def _get_host(structure, species_to_remove):
    if species_to_remove:
        s = structure.copy()
        s.remove_species(species_to_remove)
        return s
    return structure

def _perform_grouping(args):
    (
        entries_json,
        hosts_json,
        ltol,
        stol,
        angle_tol,
        primitive_cell,
        scale,
        comparator,
        groups,
    ) = args

    entries = json.loads(entries_json, cls=MontyDecoder)
    hosts = json.loads(hosts_json, cls=MontyDecoder)
    unmatched = list(zip(entries, hosts))
    while len(unmatched) > 0:
        ref_host = unmatched[0][1]
        logger.info(f"Reference tid = {unmatched[0][0].entry_id}, formula = {ref_host.formula}")
        ref_formula = ref_host.composition.reduced_formula
        logger.info(f"Reference host = {ref_formula}")
        matches = [unmatched[0]]
        for i in range(1, len(unmatched)):
            test_host = unmatched[i][1]
            logger.info(f"Testing tid = {unmatched[i][0].entry_id}, formula = {test_host.formula}")
            test_formula = test_host.composition.reduced_formula
            logger.info(f"Test host = {test_formula}")
            m = StructureMatcher(
                ltol=ltol,
                stol=stol,
                angle_tol=angle_tol,
                primitive_cell=primitive_cell,
                scale=scale,
                comparator=comparator,
            )
            if m.fit(ref_host, test_host):
                logger.info("Fit found")
                matches.append(unmatched[i])
        groups.append(json.dumps([m[0] for m in matches], cls=MontyEncoder))
        unmatched = list(filter(lambda x: x not in matches, unmatched))
        logger.info(f"{len(unmatched)} unmatched remaining")

def group_entries_by_structure(
    entries,
    species_to_remove=None,
    ltol=0.2,
    stol=0.4,
    angle_tol=5,
    primitive_cell=True,
    scale=True,
    comparator=SpeciesComparator(),
    ncpus=None,
):
    """
    Given a sequence of ComputedStructureEntries, use structure fitter to group
    them by structural similarity.

    Args:
        entries: Sequence of ComputedStructureEntries.
        species_to_remove: Sometimes you want to compare a host framework
            (e.g., in Li-ion battery analysis). This allows you to specify
            species to remove before structural comparison.
        ltol (float): Fractional length tolerance. Default is 0.2.
        stol (float): Site tolerance in Angstrom. Default is 0.4 Angstrom.
        angle_tol (float): Angle tolerance in degrees. Default is 5 degrees.
        primitive_cell (bool): If true: input structures will be reduced to
            primitive cells prior to matching. Defaults to True.
        scale: Input structures are scaled to equivalent volume if true;
            For exact matching, set to False.
        comparator: A comparator object implementing an equals method that
            declares equivalency of sites. Default is SpeciesComparator,
            which implies rigid species mapping.
        ncpus: Number of cpus to use. Use of multiple cpus can greatly improve
            fitting speed. Default of None means serial processing.

    Returns:
        Sequence of sequence of entries by structural similarity. e.g,
        [[ entry1, entry2], [entry3, entry4, entry5]]
    """
    start = datetime.datetime.now()
    logger.info(f"Started at {start}")
    entries_host = [(entry, _get_host(entry.structure, species_to_remove)) for entry in entries]
    if ncpus:
        symm_entries = collections.defaultdict(list)
        for entry, host in entries_host:
            symm_entries[comparator.get_structure_hash(host)].append((entry, host))
        import multiprocessing as mp

        logging.info(f"Using {ncpus} cpus")
        manager = mp.Manager()
        groups = manager.list()
        with mp.Pool(ncpus) as p:
            # Parallel processing only supports Python primitives and not objects.
            p.map(
                _perform_grouping,
                [
                    (
                        json.dumps([e[0] for e in eh], cls=MontyEncoder),
                        json.dumps([e[1] for e in eh], cls=MontyEncoder),
                        ltol,
                        stol,
                        angle_tol,
                        primitive_cell,
                        scale,
                        comparator,
                        groups,
                    )
                    for eh in symm_entries.values()
                ],
            )
    else:
        groups = []
        hosts = [host for entry, host in entries_host]
        _perform_grouping(
            (
                json.dumps(entries, cls=MontyEncoder),
                json.dumps(hosts, cls=MontyEncoder),
                ltol,
                stol,
                angle_tol,
                primitive_cell,
                scale,
                comparator,
                groups,
            )
        )
    entry_groups = []
    for g in groups:
        entry_groups.append(json.loads(g, cls=MontyDecoder))
    logging.info(f"Finished at {datetime.datetime.now()}")
    logging.info(f"Took {datetime.datetime.now() - start}")
    return entry_groups

def group_entries_by_composition(entries, sort_by_e_per_atom=True):
    """
    Given a sequence of Entry-like objects, group them by composition and
        optionally sort by energy above hull.

    Args:
        entries (List): Sequence of Entry-like objects.
        sort_by_e_per_atom (bool): Whether to sort the grouped entries by
            energy per atom (lowest energy first). Default True.

    Returns:
        Sequence of sequence of entries by composition. e.g,
        [[ entry1, entry2], [entry3, entry4, entry5]]
    """
    entry_groups = []
    entries = sorted(entries, key=lambda e: e.composition.reduced_formula)
    for _, g in itertools.groupby(entries, key=lambda e: e.composition.reduced_formula):
        group = list(g)
        if sort_by_e_per_atom:
            group = sorted(group, key=lambda e: e.energy_per_atom)

        entry_groups.append(group)

    return entry_groups

class EntrySet(collections.abc.MutableSet, MSONable):
    """
    A convenient container for manipulating entries. Allows for generating
    subsets, dumping into files, etc.
    """

    def __init__(self, entries: Iterable[PDEntry | ComputedEntry | ComputedStructureEntry]):
        """
        Args:
            entries: All the entries.
        """
        self.entries = set(entries)

    def __contains__(self, item):
        return item in self.entries

    def __iter__(self):
        return self.entries.__iter__()

    def __len__(self):
        return len(self.entries)

    def add(self, element):
        """
        Add an entry.

        :param element: Entry
        """
        self.entries.add(element)

    def discard(self, element):
        """
        Discard an entry.

        :param element: Entry
        """
        self.entries.discard(element)

    @property
    def chemsys(self) -> set:
        """
        Returns:
            set representing the chemical system, e.g., {"Li", "Fe", "P", "O"}
        """
        chemsys = set()
        for e in self.entries:
            chemsys.update([el.symbol for el in e.composition.keys()])
        return chemsys

    @property
    def ground_states(self) -> set:
        """
        A set containing only the entries that are ground states, i.e., the lowest energy
        per atom entry at each composition.
        """
        entries = sorted(self.entries, key=lambda e: e.composition.reduced_formula)
        ground_states = set()
        for _, g in itertools.groupby(entries, key=lambda e: e.composition.reduced_formula):
            ground_states.add(min(g, key=lambda e: e.energy_per_atom))
        return ground_states

    def remove_non_ground_states(self):
        """
        Removes all non-ground state entries, i.e., only keep the lowest energy
        per atom entry at each composition.
        """
        self.entries = self.ground_states

    def is_ground_state(self, entry) -> bool:
        """
        Boolean indicating whether a given Entry is a ground state
        """
        return entry in self.ground_states

    def get_subset_in_chemsys(self, chemsys: list[str]):
        """
        Returns an EntrySet containing only the set of entries belonging to
        a particular chemical system (in this definition, it includes all sub
        systems). For example, if the entries are from the
        Li-Fe-P-O system, and chemsys=["Li", "O"], only the Li, O,
        and Li-O entries are returned.

        Args:
            chemsys: Chemical system specified as list of elements. E.g.,
                ["Li", "O"]

        Returns:
            EntrySet
        """
        chem_sys = set(chemsys)
        if not chem_sys.issubset(self.chemsys):
            raise ValueError(f"{chem_sys} is not a subset of {self.chemsys}")
        subset = set()
        for e in self.entries:
            elements = [sp.symbol for sp in e.composition.keys()]
            if chem_sys.issuperset(elements):
                subset.add(e)
        return EntrySet(subset)

    def as_dict(self) -> dict[Literal["entries"], list[Entry]]:
        """
        Returns MSONable dict.
        """
        return {"entries": list(self.entries)}

    def to_csv(self, filename: str, latexify_names: bool = False) -> None:
        """
        Exports PDEntries to a csv

        Args:
            filename: Filename to write to.
            entries: PDEntries to export.
            latexify_names: Format entry names to be LaTex compatible,
                e.g., Li_{2}O
        """

        els: set[Element] = set()
        for entry in self.entries:
            els.update(entry.composition.elements)
        elements = sorted(list(els), key=lambda a: a.X)
        with open(filename, "w") as f:
            writer = csv.writer(
                f,
                delimiter=unicode2str(","),
                quotechar=unicode2str('"'),
                quoting=csv.QUOTE_MINIMAL,
            )
            writer.writerow(["Name"] + [el.symbol for el in elements] + ["Energy"])
            for entry in self.entries:
                row: list[str] = [entry.name if not latexify_names else re.sub(r"([0-9]+)", r"_{\1}", entry.name)]
                row.extend([str(entry.composition[el]) for el in elements])
                row.append(str(entry.energy))
                writer.writerow(row)

    @classmethod
    def from_csv(cls, filename: str):
        """
        Imports PDEntries from a csv.

        Args:
            filename: Filename to import from.

        Returns:
            List of Elements, List of PDEntries
        """
        with open(filename, encoding="utf-8") as f:
            reader = csv.reader(
                f,
                delimiter=unicode2str(","),
                quotechar=unicode2str('"'),
                quoting=csv.QUOTE_MINIMAL,
            )
            entries = []
            header_read = False
            elements = []  # type: List[str]
            for row in reader:
                if not header_read:
                    elements = row[1 : (len(row) - 1)]
                    header_read = True
                else:
                    name = row[0]
                    energy = float(row[-1])
                    comp = {}
                    for ind in range(1, len(row) - 1):
                        if float(row[ind]) > 0:
                            comp[Element(elements[ind - 1])] = float(row[ind])
                    entries.append(PDEntry(Composition(comp), energy, name))
        return cls(entries)


text:
function cf = cf_SkewNormal(t,mu,sigma,lambda,coef,niid)
%cf_SkewNormal
%  Characteristic function of a linear combination (resp. convolution) of
%  independent Skew-Normal random variables.
%
%  The Skew-Normal distribution is a continuous probability distribution
%  that generalises the normal distribution to allow for non-zero skewness.
%
%  The Skew-Normal distribution was first introduced by O'Hagan and Leonard
%  in [1], for more details see works of Azzalini, e.g. [2]. Pewsey gave
%  the CF of the Skew-Normal distribution and discussed the wrapped
%  Skew-Normal distribution on the circle. The CF of the Skew-Normal
%  distribution was formally proved by Kim and Genton in [4]. For more
%  details see also [5].
%
%  In particular, if X ~ SN(mu,sigma,lambda), with real the location
%  parameter mu, the positive real scale parameter sigma, and the real
%  shape parameter lambda.
%
%  The probability density function (PDF) with the parameters mu, sigma and
%  lambda becomes
%    pdf(x)= 2/sigma * phi((x-mu)/sigma) * Phi(lambda*(x-mu)/sigma),
%  where phi denote the standard Normal (Gaussian) PDF and Phi is its CDF.
%
%  Note that the skewness of the distribution is limited to the interval
%  (-1,1). When lambda=0, the skewness vanishes, and we obtain the standard
%  Normal density, as lambda increases (in absolute value), the skewness of
%  the distribution increases, when lambda -> infty, the density converges
%  to half-normal (or folded normal) density function.
%
%  cf_SkewNormal evaluates the characteristic function cf(t) of Y =
%  sum_{i=1}^N coef_i * X_i, where X_i ~ SN(mu_i,sigma_i,lambda_i) are
%  inedependent Skew-Normal RVs with the parameters mu_i, sigma_i, and
%  lambda_i, for i  = 1,...,N.
%
%  The characteristic function of X ~ SN(mu,sigma,lambda) was defined in
%  [3] by
%   cf(t) = cf_SkewNormal(t|mu,sigma,lambda)
%    = exp(1i*t*mu - t^2*sigma^2/2) * (1 + 1i*erfi(t*sigma*delta/sqrt(2))),
%  where delta = lambda/sqrt(1+lambda^2) and erfi(z) is the imaginary
%  error function (which is related with the Faddeeva function w(z). In
%  particular, erfi(z) = -1i*(1 - exp(z^2)*w(-z)).
%
%  Based on that, we use the following representation
%   cf(t) = 2*exp(1i*t*mu - t^2*sigma^2/2) - ...
%           exp( 1i*t*mu - t^2*sigma^2*(1-delta.^2)/2 ) * ...
%           Faddeeva(-t*sigma*delta/sqrt(2));
%  Note that this expression is more suitable for practical purposesis as
%  it is numerically more stable for large t. See also erfiZX.m and
%  Faddeeva.m.
%
%  Hence, the characteristic function of Y is
%   cf(t) = Prod ( cf_SkewNormal(t | mu_i,sigma_i,lambda_i) ).
%
% SYNTAX:
%  cf = cf_SkewNormal(t,mu,sigma,lambda,coef,niid)
%
% INPUTS:
%  t     - vector or array of real values, where the CF is evaluated.
%  mu    - vector of the 'location' parameters mu in R. If empty, default
%          value is mu = 0.
%  sigma - vector of the scale parameters of the Half-Normal random
%          variables. If sigma is scalar, it is assumed that all scale
%          parameters are equal. If empty, default value is sigma = 1.
%  lambda - vector of the 'shape' parameters lambda in R. If empty, default
%          value is lambda = 0.
%  coef  - vector of the coefficients of the linear combination of the
%          Half-Normal random variables. If coef is scalar, it is assumed
%          that all coefficients are equal. If empty, default value is
%          coef = 1.
%  niid  - scalar convolution coeficient niid, such that Z = Y + ... + Y is
%          sum of niid iid random variables Y, where each Y = sum_{i=1}^N
%          coef(i) * X_i is independently and identically distributed
%          random variable. If empty, default value is niid = 1.
%
% WIKIPEDIA:
%  https://en.wikipedia.org/wiki/Skew_normal_distribution
%
% EXAMPLE 1:
% % CF of the distribution of Skew-Normal RV with mu=0, sigma=1, lambda=1
%   mu     = 0;
%   sigma  = 1;
%   lambda = 1;
%   t      = linspace(-5,5,501);
%   cf     = cf_SkewNormal(t,mu,sigma,lambda);
%   figure; plot(t,real(cf),t,imag(cf));grid on
%   title('CF of the Skew-Normal RV with mu=0, sigma=1, lambda=1')
%
% EXAMPLE 2:
% % CF of a linear combination of the Skew-Normal RVs
%   mu     = [0 0 0];
%   sigma  = [1 0.5 0.5];
%   lambda = [0 0.5 1];
%   t      = linspace(-5,5,501);
%   cf     = cf_SkewNormal(t,mu,sigma,lambda);
%   figure; plot(t,real(cf),t,imag(cf));grid on
%   title('CF of a linear combination of the Skew-Normal RVs')
%
% EXAMPLE 3:
% % PDF/CDF of a linear combination of independent Skew-Normal RVs
%   mu     = [0 0 0];
%   sigma  = [1 0.5 0.5];
%   lambda = [0 0.5 1];
%   cf     = @(t) cf_SkewNormal(t,mu,sigma,lambda);
%   clear options
%   options.N = 2^10;
%   x = linspace(5,40,201);
%   prob = [0.9 0.95 0.975 0.99];
%   result = cf2DistGP(cf,[],prob,options);
%
% EXAMPLE 4:
% % PDF/CDF combination of wrapped Skew-Normal distributions on the circle
%   mu     = [0 0 0];
%   sigma  = [1 0.5 0.5];
%   lambda = [0 0.5 1];
%   cf     = @(t) cf_SkewNormal(t,mu,sigma,lambda);
%   clear options
%   options.isCircular = true;
%   options.correctedCDF = true;
%   result = cf2DistGP(cf,[],[],options);
%   disp(result);
%   angle  = result.x;
%   radius = result.pdf;
%   figure; polarplot(angle,radius);
%   ax = gca; ax.ThetaAxisUnits = 'radians';
%   title('PDF of a Wrapped Skew-Normal Distribution on the Circle')
%
% REFERENCES:
% [1] O'Hagan, A. and Leonard, T., 1976. Bayes estimation subject to
%     uncertainty about parameter constraints. Biometrika, 63(1), 201-203.
% [2] Azzalini, A., 1985. A class of distributions which includes the
%     normal ones. Scandinavian Journal of Statistics, 171-178.
% [3] Pewsey, A., 2000. The wrapped skew-normal distribution on the circle.
%     Communications in Statistics-Theory and Methods, 29(11), 2459-2472.
% [4] Kim, H.M. and Genton, M.G., 2011. Characteristic functions of scale
%     mixtures of multivariate skew-normal distributions. Journal of
%     Multivariate Analysis, 102(7), 1105-1117.
% [5] Gupta, A.K., Nguyen, T.T. and Sanqui, J.A.T., 2004. Characterization
%     of the skew-normal distribution. Annals of the Institute of
%     Statistical Mathematics, 56(2), 351-360.
%
% SEE ALSO: cf_Normal, erfiZX

% (c) Viktor Witkovsky (witkovsky@gmail.com)
% Ver.: 07-Feb-2020 13:08:06
% Rev.: 28-Apr-2020 13:47:42

%% ALGORITHM
%  cf = cf_SkewNormal(t,mu,sigma,lambda,coef,niid)

%% CHECK THE INPUT PARAMETERS
narginchk(1, 6);
if nargin < 6, niid  = []; end
if nargin < 5, coef  = []; end
if nargin < 4, lambda = []; end
if nargin < 3, sigma = []; end
if nargin < 2, mu = []; end

if isempty(lambda)
    lambda = 0;
end

if isempty(sigma)
    sigma = 1;
end

if isempty(mu)
    mu = 0;
end

if isempty(coef)
    coef = 1;
end

%% CHECK THE INPUT PARAMETERS
[errorcode,coef,mu,sigma,lambda] = ...
    distchck(3,coef(:)',mu(:)',sigma(:)',lambda(:)');
if errorcode > 0
    error(message('InputSizeMismatch'));
end
szt = size(t);
t   = t(:);

%% CF of the linear combination of the Skew-Normal RVs
delta = lambda ./ sqrt(1+lambda.^2);
% cf =  prod(exp(1i*t*(coef.*mu) - t.^2*(coef.*sigma).^2/2) .* ...
%     (1 + 1i*erfiZX(t*(sigma.*delta)/sqrt(2))),2);

% CF based on using Faddeeva function (numerically more stable)
aux1 = 1i*t*(coef.*mu);
aux2 = (coef.*sigma).^2/2;
cf =  prod(2 * exp(aux1 - t.^2*aux2) - ...
    exp(aux1 - t.^2*(aux2.*(1-delta.^2))) .* ...
    Faddeeva(-t*(coef.*sigma.*delta)/sqrt(2)),2);

cf(t==0) = 1;
cf   = reshape(cf,szt);

if ~isempty(niid)
    if isscalar(niid)
        cf = cf .^ niid;
    else
        error('niid should be a scalar (positive integer) value');
    end
end
end