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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>org.togglz.core (Togglz 1.1.1.Final API)</title>
<meta name="date" content="2013-03-30">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package org.togglz.core

Interface Summary

Interface
Description

Feature

This interface has to be implemented by feature enums

Class Summary

Class
Description

FeatureMetaData

Represents metadata of a feature that can be specified using annotations like Label or EnabledByDefault.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2013. All Rights Reserved.


text:
#ifndef MAX_CPU_ASSOCIATIVITY_HPP
#define MAX_CPU_ASSOCIATIVITY_HPP

#include <cstdint>

namespace max
{
namespace CPU
{

	// A set can be fully associative or have N-many ways of associativity.
	// This class holds the associativity information while protecting from bad state.
	class Associativity
	{
	public:

		struct UnknownAssociativity {};
		struct FullyAssociative {};

		explicit Associativity( const UnknownAssociativity )         noexcept;
		explicit Associativity( const FullyAssociative )             noexcept;
		explicit Associativity( const uint32_t WaysOfAssociativity ) noexcept;
		Associativity()                                              noexcept = delete;
		Associativity( const Associativity & rhs )                   noexcept = default;
		Associativity( Associativity && rhs )                        noexcept = default;
		~Associativity()                                             noexcept = default;

		Associativity & operator =( const Associativity & rhs ) noexcept = default;
		Associativity & operator =( Associativity && rhs )      noexcept = default;

		bool IsUnknown()               const noexcept;
		bool IsFullyAssociative()      const noexcept;
		uint32_t WaysOfAssociativity() const noexcept;

		void SetUnknown()                                                 noexcept;
		void SetFullyAssociative()                                        noexcept;
		void SetWaysOfAssociativity( const uint32_t WaysOfAssociativity ) noexcept;

	private:

		bool     Unknown;
		bool     Fully;
		uint32_t Ways;

	};

} // namespace CPU
} // namespace max

#endif // MAX_CPU_ASSOCIATIVITY_HPP

redpajama_set_name: RedPajamaGithub


text:
package io.artsoftware.organization.web.html;

import io.artsoftware.web.html.Command;
import io.artsoftware.web.html.HtmlForward;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public final class HtmlOrgCreate implements Command {

    private final Command command;

    public HtmlOrgCreate() {
        this(
                new HtmlForward("/WEB-INF/pages/orgs/create.jsp")
        );
    }

    private HtmlOrgCreate(Command command) {
        this.command = command;
    }

    @Override
    public void act(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.command.act(req, resp);
    }
}


text:
FOUNDATION_EXPORT double Swift_BinaryVersionNumber;

//! Project version string for Swift.Binary.
FOUNDATION_EXPORT const unsigned char Swift_BinaryVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <Swift_Json/PublicHeader.h>


text:
package org.spotter.shared.result.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * {@link SpotterResult} represents the diagnosis result.
 *
 * @author Alexander Wert
 *
 */
public class SpotterResult implements Serializable {

	private static final long serialVersionUID = 6058864897164235148L;

	private final StringBuilder message = new StringBuilder();
	private final List<String> resourceFiles = new ArrayList<>();
	private final List<ProblemOccurrence> problemOccurrences = new ArrayList<>();

	private boolean detected = false;

	/**
	 *
	 * @return true if the problem (to which that result belongs) has been
	 *         detected, otherwise false
	 */
	public boolean isDetected() {
		return detected;
	}

	/**
	 * Sets whether the the problem (to which that result belongs) has been
	 * detected or not.
	 *
	 * @param detected
	 *            needs to be true if has been detected
	 */
	public void setDetected(boolean detected) {
		this.detected = detected;
	}

	/**
	 *
	 * @return the diagnosis message
	 */
	public String getMessage() {
		return message.toString();
	}

	/**
	 * Adds a message to the diagnosis text.
	 *
	 * @param msg
	 *            message to be added
	 */
	public void addMessage(String msg) {
		message.append("   # ");
		message.append(msg);
		message.append(System.getProperty("line.separator"));
	}

	/**
	 * Adds the path to an additional resource.
	 *
	 * @param pathToFile
	 *            path to file
	 */
	public void addResourceFile(String pathToFile) {
		getResourceFiles().add(pathToFile);
	}

	/**
	 * @return the resourceFiles
	 */
	public List<String> getResourceFiles() {
		return resourceFiles;
	}

	/**
	 * Adds the problem occurrence.
	 *
	 * @param problemOccurrence
	 *            occurrence to add
	 */
	public void addProblemOccurrence(ProblemOccurrence problemOccurrence) {
		getProblemOccurrences().add(problemOccurrence);
	}

	/**
	 * Returns the list of occurrences.
	 *
	 * @return the problem occurrences
	 */
	public List<ProblemOccurrence> getProblemOccurrences() {
		return problemOccurrences;
	}

}


text:
findpid:
	ps -ax | grep -i platform
.PHONY: findpid

reload:
	@echo "kill -SIGUSR1 PID"
.PHONY: reload


text:
using System;
using SharpJVM.SharpJVM.Class;
using SharpJVM.SharpJVM.Runtime.DataArea;
using SharpJVM.SharpJVM.Runtime.DataArea.Heap;
using SharpJVM.SharpJVM.Runtime.HeapConstantsPool;
using SharpJVM.SharpJVM.Runtime.Instructions.Base;
using SharpJVM.SharpJVM.Runtime.Ref;

namespace SharpJVM.SharpJVM.Runtime.Instructions.References
{
	public class New:Index16Instruction
	{
		public New()
		{
		}
		public override void Execute(Frame frame)
		{
			HeapConstantPool ConstantPool = frame.method.ConstantPool;
			ClassRef classRef = (ClassRef)ConstantPool[Index];
			JavaClass Class = classRef.ResolvedClass();
			if (ClassIniter.CheckInitClass(Class, frame))
				return;
			if (Class.AccessFlag.Interface | Class.AccessFlag.Abstract) {
				//to do
				Console.WriteLine("instantiationerror");
				return;
			}
			JavaObject ObjRef = new JavaObject(Class);
			frame.operandStack.PushRef(ObjRef);
		}
	}
}


text:
module SlackGamebot
  class Error < StandardError
  end
end


text:
package linker

import (
	"net"
	"fmt"
	"io"
	"os"
)

type Client interface{
	GetId() int32
	sendPacket(Packet)
}

type linkerClient struct {
	clientId   int32
	servRef *ServerLinker
	clientConn net.Conn
}

func (linkerClient *linkerClient) GetId() int32{
	return linkerClient.clientId
}

func (client *linkerClient) sendPacket(packet Packet) {
	largePacket, isLargePacket := packet.(LargePacket)
	headersize := 4
	if isLargePacket{
		headersize = 8
	}
	length := uint16(len(packet.GetBytes()) + headersize - 2)
	data := make([]byte, headersize)
	data[0] = uint8(length >> 8)
	data[1] = uint8(length & 0xff)
	data[2] = 0
	if isLargePacket {
		f, err := os.Stat(largePacket.GetFilePath())
		if err != nil{
			fmt.Println("large packet err ",err)
		}
		data[2] = 1
		data[3] = uint8(f.Size() >> 24)
		data[4] = uint8(f.Size() >> 16)
		data[5] = uint8(f.Size() >> 8)
		data[6] = uint8(f.Size()  & 0xff)
	}
	data[headersize - 1] = byte(packet.GetId())
	data = append(data, packet.GetBytes()...)
	client.clientConn.Write(data)
	if isLargePacket{
		f, err := os.Open(largePacket.GetFilePath())
		if err != nil {
			fmt.Println("open error", err)
		}
		size, _ := f.Stat()
		_, err = io.CopyN(client.clientConn, f, size.Size())
		if err != nil {
			fmt.Println("open error", err)
		}
		f.Close()
		client.clientConn.Write([]byte{})
	}
}


text:
import db from '../../db/mongodb';

export default db.get('following') as any; // fuck type definition


text:
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type

ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'community'}

DOCUMENTATION = '''
---
module: oneview_datacenter_facts
short_description: Retrieve facts about the OneView Data Centers
description:
    - Retrieve facts about the OneView Data Centers.
version_added: "2.5"
requirements:
    - "hpOneView >= 2.0.1"
author:
    - Alex Monteiro (@aalexmonteiro)
    - Madhav Bharadwaj (@madhav-bharadwaj)
    - Priyanka Sood (@soodpr)
    - Ricardo Galeno (@ricardogpsf)
options:
    name:
      description:
        - Data Center name.
    options:
      description:
        - "Retrieve additional facts. Options available: 'visualContent'."

extends_documentation_fragment:
    - oneview
    - oneview.factsparams
'''

EXAMPLES = '''
- name: Gather facts about all Data Centers
  oneview_datacenter_facts:
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 500
  delegate_to: localhost
- debug: var=datacenters

- name: Gather paginated, filtered and sorted facts about Data Centers
  oneview_datacenter_facts:
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 500
    params:
      start: 0
      count: 3
      sort: 'name:descending'
      filter: 'state=Unmanaged'
- debug: var=datacenters

- name: Gather facts about a Data Center by name
  oneview_datacenter_facts:
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 500
    name: "My Data Center"
  delegate_to: localhost
- debug: var=datacenters

- name: Gather facts about the Data Center Visual Content
  oneview_datacenter_facts:
    hostname: 172.16.101.48
    username: administrator
    password: my_password
    api_version: 500
    name: "My Data Center"
    options:
      - visualContent
  delegate_to: localhost
- debug: var=datacenters
- debug: var=datacenter_visual_content
'''

RETURN = '''
datacenters:
    description: Has all the OneView facts about the Data Centers.
    returned: Always, but can be null.
    type: dict

datacenter_visual_content:
    description: Has facts about the Data Center Visual Content.
    returned: When requested, but can be null.
    type: dict
'''

from ansible.module_utils.oneview import OneViewModuleBase

class DatacenterFactsModule(OneViewModuleBase):
    argument_spec = dict(
        name=dict(type='str'),
        options=dict(type='list'),
        params=dict(type='dict')
    )

    def __init__(self):
        super(DatacenterFactsModule, self).__init__(additional_arg_spec=self.argument_spec)

    def execute_module(self):

        client = self.oneview_client.datacenters
        ansible_facts = {}

        if self.module.params.get('name'):
            datacenters = client.get_by('name', self.module.params['name'])

            if self.options and 'visualContent' in self.options:
                if datacenters:
                    ansible_facts['datacenter_visual_content'] = client.get_visual_content(datacenters[0]['uri'])
                else:
                    ansible_facts['datacenter_visual_content'] = None

            ansible_facts['datacenters'] = datacenters
        else:
            ansible_facts['datacenters'] = client.get_all(**self.facts_params)

        return dict(changed=False,
                    ansible_facts=ansible_facts)

def main():
    DatacenterFactsModule().run()

if __name__ == '__main__':
    main()


text:
<?php

namespace Ems\Contracts\Assets;

use Countable;
use ArrayAccess;
use IteratorAggregate;

interface Collection extends Renderable, Countable, ArrayAccess, IteratorAggregate
{
}


text:
/**
 * @module node-opcua-address-space
 */
import { StatusCodes } from "node-opcua-status-code";
import { DataType, Variant } from "node-opcua-variant";
import { Folder, MethodFunctor, MethodFunctorCallback, Namespace, SessionContext } from "../source";

export function add_eventGeneratorObject(
  namespace: Namespace,
  parentFolder: Folder | string
) {

    const myEvtType = namespace.addEventType({
        browseName: "MyEventType",
        subtypeOf: "BaseEventType" // should be implicit
    });

    const myObject = namespace.addObject({
        browseName: "EventGeneratorObject",
        organizedBy: parentFolder
    });

    myObject.addReference({
        nodeId: myEvtType,
        referenceType: "AlwaysGeneratesEvent"
    });

    const method = namespace.addMethod(myObject, {
        browseName: "EventGeneratorMethod",
        inputArguments: [
            {
                dataType: DataType.String,
                description: { text: "Event Message" },
                name: "message"
            },
            {
                dataType: DataType.UInt32,
                description: { text: "Event Severity" },
                name: "severity"
            }
        ],
        outputArguments: []
    });

    method.bindMethod((
      inputArguments: Variant[],
      context: SessionContext,
      callback: MethodFunctorCallback) => {

        // xx console.log("In Event Generator Method");
        // xx console.log(this.toString());
        // xx console.log(context.object.toString());

        // xx console.log("inputArguments ", inputArguments[0].toString());

        const message = inputArguments[0].value || "Hello from Event Generator Object";
        const severity = inputArguments[1].value || 0;

        const myEventType = namespace.addressSpace.findEventType("MyEventType", namespace.index);
        context.object.raiseEvent(myEventType, {
            message: {
                dataType: DataType.LocalizedText,
                value: { text: message }
            },
            severity: {
                dataType: DataType.UInt32,
                value: severity
            }

        });
        // console.log(require("util").inspect(context).toString());
        const callMethodResult = {
            outputArguments: [],
            statusCode: StatusCodes.Good
        };
        callback(null, callMethodResult);
    });

}


text:
<!DOCTYPE html>

    {% include head.html %}

    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.11.0/styles/default.min.css">

                    <button type="button" class="navbar-toggle collapsed my-color" data-toggle="collapse"
                            data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                        Toggle navigation

                    </button>
                    Stephanie

Home

Documentation

Github

                        {%if page.currentpage == "resources" %}
                            Resources
                        {% else %}
                            Resources
                        {% endif %}
                        {%if page.currentpage == "More Modules" %}
                            More Modules
                        {% else %}
                            More Modules
                        {% endif %}
                        {%if page.currentpage == "football" %}
                            Football
                        {% else %}
                            Football
                        {% endif %}
                        {%if page.currentpage == "news" %}
                            News
                        {% else %}
                            News
                        {% endif %}
                        {%if page.currentpage == "algorithm" %}
                            Algorithm
                        {% else %}
                            Algorithm
                        {% endif %}
                        {%if page.currentpage == "algorithm-api" %}
                            Algorithm API
                        {% else %}
                            Algorithm API
                        {% endif %}
                        {%if page.currentpage == "api-reference" %}
                            API Reference
                        {% else %}
                            API Reference
                        {% endif %}
                        {%if page.currentpage == "credits" %}
                            Credits
                        {% else %}
                            Credits
                        {% endif %}
                        {%if page.currentpage == "support" %}
                            Support
                        {% else %}
                            Support
                        {% endif %}
                            Documentation
                        {%if page.currentpage == "blog" %}
                            dont click.
                        {% else %}
                            dont click.
                        {% endif %}

                    {{ content }}

        {% include footer.html %}
        {% include js.html %}


text:
package org.onosproject.bgpio.types;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import com.google.common.testing.EqualsTester;

/**
 * Test for destination port number flow specification component.
 */
public class BgpFsDestinationPortNumTest {
    List<BgpFsOperatorValue> operatorValue1 = new ArrayList<>();
    List<BgpFsOperatorValue> operatorValue2 = new ArrayList<>();

    @Test
    public void testEquality() {
        operatorValue1.add(new BgpFsOperatorValue((byte) 1, new byte[100]));
        operatorValue1.add(new BgpFsOperatorValue((byte) 1, new byte[100]));
        operatorValue2.add(new BgpFsOperatorValue((byte) 2, new byte[100]));
        operatorValue2.add(new BgpFsOperatorValue((byte) 1, new byte[100]));

        BgpFsDestinationPortNum tlv1 = new BgpFsDestinationPortNum(operatorValue1);
        BgpFsDestinationPortNum sameAsTlv1 = new BgpFsDestinationPortNum(operatorValue1);
        BgpFsDestinationPortNum tlv2 = new BgpFsDestinationPortNum(operatorValue2);

        new EqualsTester()
        .addEqualityGroup(tlv1, sameAsTlv1)
        .addEqualityGroup(tlv2)
        .testEquals();
    }
}


text:
<!-- bootstrap & fontawesome -->
<link rel="stylesheet"
	href="${contextPath}/admin/assets/css/bootstrap.css" />
<link rel="stylesheet"
	href="${contextPath}/admin/assets/css/font-awesome.css" />

	<!-- page specific plugin BEGAIN -->
		${pageCss}
	<!-- page specific plugin END -->
<!-- text fonts -->
<link rel="stylesheet"
	href="${contextPath}/admin/assets/css/ace-fonts.css" />

<!-- ace styles -->
<link rel="stylesheet" href="${contextPath}/admin/assets/css/ace.css"
	class="ace-main-stylesheet" id="main-ace-style" />

<!--[if lte IE 9]>
			<link rel="stylesheet" href="${contextPath}/admin/assets/css/ace-part2.css" class="ace-main-stylesheet" />
		<![endif]-->

<!--[if lte IE 9]>
		  <link rel="stylesheet" href="${contextPath}/admin/assets/css/ace-ie.css" />
		<![endif]-->

<!-- inline styles related to this page -->

<!-- ace settings handler -->
<script src="${contextPath}/admin/assets/js/ace-extra.js"></script>

<!-- HTML5shiv and Respond.js for IE8 to support HTML5 elements and media queries -->

<!--[if lte IE 8]>
		<script src="${contextPath}/admin/assets/js/html5shiv.js"></script>
		<script src="${contextPath}/admin/assets/js/respond.js"></script>
		<![endif]-->


text:
package com.example.wangyonghua.androidlearndemos;

import android.app.Application;
import android.test.ApplicationTestCase;

/**
 * Testing Fundamentals
 */
public class ApplicationTest extends ApplicationTestCase<Application> {
    public ApplicationTest() {
        super(Application.class);
    }
}


text:
#include <qpid/dispatch/atomic.h>
#include <qpid/dispatch/amqp.h>
#include <qpid/dispatch/protocol_adaptor.h>
#include <qpid/dispatch/threading.h>
#include <qpid/dispatch/timer.h>

#include <proton/connection_driver.h>

#include <libwebsockets.h>

#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <inttypes.h>

#include "http.h"
#include "server_private.h"
#include "config.h"

static const char *CIPHER_LIST = "ALL:aNULL:!eNULL:@STRENGTH"; /* Default */
static const char *IGNORED = "ignore-this-log-message";

/* Log for LWS messages. For dispatch server messages use qd_http_server_t::log */
static qd_log_source_t* http_log;

static qd_log_level_t qd_level(int lll) {
    switch (lll) {
    case LLL_ERR: return QD_LOG_ERROR;
    case LLL_WARN: return QD_LOG_WARNING;
    /* LWS is noisy compared to dispatch on the informative levels, downgrade */
    case LLL_NOTICE: return QD_LOG_DEBUG;
    default: return QD_LOG_TRACE; /* Everything else to trace  */
    }
}

static void logger(int lll, const char *line)  {
    if (strstr(line, IGNORED)) return;
    size_t  len = strlen(line);
    while (len > 1 && isspace(line[len-1])) { /* Strip trailing newline */
        --len;
    }
    qd_log(http_log, qd_level(lll), "%.*s", (int)len, line);
}

static void log_init() {
    http_log = qd_log_source("HTTP");
    int levels = 0;
    for (int i = 0; i < LLL_COUNT; ++i) {
        int lll = 1<<i;
        levels |= qd_log_enabled(http_log, qd_level(lll)) ? lll : 0;
    }
    lws_set_log_level(levels, logger);
}

/* Intermediate write buffer: LWS needs extra header space on write.  */
typedef struct buffer_t {
    char *start;
    size_t size, cap;
} buffer_t;

/* Ensure size bytes in buffer, make buf empty if alloc fails */
static void buffer_set_size(buffer_t *buf, size_t size) {
    if (size > buf->cap) {
        buf->cap = (size > buf->cap * 2) ? size : buf->cap * 2;
        buf->start = realloc(buf->start, buf->cap);
    }
    if (buf->start) {
        buf->size = size;
    } else {
        buf->size = buf->cap = 0;
    }
}

/* AMQPWS connection: set as lws user data and qd_conn->context */
typedef struct connection_t {
    pn_connection_driver_t driver;
    qd_connection_t* qd_conn;
    buffer_t wbuf;   /* LWS requires allocated header space at start of buffer */
    struct lws *wsi;
} connection_t;

typedef struct stats_request_state_t {
    bool callback_completed;
    bool wsi_deleted;
    qdr_global_stats_t stats;
    qd_http_server_t *server;
    struct lws *wsi;
} stats_request_state_t;

typedef struct stats_t {
    size_t current;
    bool headers_sent;
    stats_request_state_t *context;
} stats_t;

/* Navigating from WSI pointer to qd objects */
static qd_http_server_t *wsi_server(struct lws *wsi);
static qd_lws_listener_t *wsi_listener(struct lws *wsi);
static qd_log_source_t *wsi_log(struct lws *wsi);

/* Declare LWS callbacks and protocol list */
static int callback_http(struct lws *wsi, enum lws_callback_reasons reason,
                         void *user, void *in, size_t len);
static int callback_amqpws(struct lws *wsi, enum lws_callback_reasons reason,
                           void *user, void *in, size_t len);
static int callback_metrics(struct lws *wsi, enum lws_callback_reasons reason,
                               void *user, void *in, size_t len);
static int callback_healthz(struct lws *wsi, enum lws_callback_reasons reason,
                               void *user, void *in, size_t len);

static struct lws_protocols protocols[] = {
    /* HTTP only protocol comes first */
    {
        "http-only",
        callback_http,
        0,
    },
    /* "amqp" is the official oasis AMQP over WebSocket protocol name */
    {
        "amqp",
        callback_amqpws,
        sizeof(connection_t),
    },
    /* "binary" is an alias for "amqp", for compatibility with clients designed
     * to work with a WebSocket proxy
     */
    {
        "binary",
        callback_amqpws,
        sizeof(connection_t),
    },
    {
        "http",
        callback_metrics,
        sizeof(stats_t),
    },
    {
        "healthz",
        callback_healthz,
        sizeof(stats_t),
    },
    { NULL, NULL, 0, 0 } /* terminator */
};

static inline int unexpected_close(struct lws *wsi, const char *msg) {
    lws_close_reason(wsi, LWS_CLOSE_STATUS_UNEXPECTED_CONDITION,
                     (unsigned char*)msg, strlen(msg));
    char peer[64];
    lws_get_peer_simple(wsi, peer, sizeof(peer));
    qd_log(wsi_log(wsi), QD_LOG_ERROR, "Error on HTTP connection from %s: %s", peer, msg);
    return -1;
}

static int handle_events(connection_t* c) {
    if (!c->qd_conn) {
        return unexpected_close(c->wsi, "not-established");
    }
    pn_event_t *e;
    while ((e = pn_connection_driver_next_event(&c->driver))) {
        if (c->qd_conn && e) {
            if (!qd_connection_handle(c->qd_conn, e)) {
                c->qd_conn = 0;  // connection closed
            }
        }
    }
    if (pn_connection_driver_write_buffer(&c->driver).size) {
        lws_callback_on_writable(c->wsi);
    }
    if (pn_connection_driver_write_closed(&c->driver)) {
        lws_close_reason(c->wsi, LWS_CLOSE_STATUS_NORMAL, NULL, 0);
        return -1;
    }
    return 0;
}

/* The server has a bounded, thread-safe queue for external work */
typedef struct work_t {
    enum { W_NONE, W_LISTEN, W_CLOSE, W_WAKE, W_STOP, W_HANDLE_STATS } type;
    void *value;
} work_t;

#define WORK_MAX 8              /* Just decouple threads, not a big buffer */

typedef struct work_queue_t {
    sys_mutex_t *lock;
    sys_cond_t *cond;
    work_t work[WORK_MAX];
    size_t head, len;          /* Ring buffer */
} work_queue_t;

/* HTTP Server runs in a single thread, communication from other threads via work_queue */
struct qd_http_server_t {
    qd_server_t *server;
    qdr_core_t *core;
    sys_thread_t *thread;
    work_queue_t work;
    qd_log_source_t *log;
    struct lws_context *context;
    qd_timestamp_t now;         /* Cache current time in thread_run */
    qd_timestamp_t next_tick;   /* Next requested tick service */
};

static void work_queue_destroy(work_queue_t *wq) {
    if (wq->lock) sys_mutex_free(wq->lock);
    if (wq->cond) sys_cond_free(wq->cond);
}

static void work_queue_init(work_queue_t *wq) {
    wq->lock = sys_mutex();
    wq->cond = sys_cond();
}

 /* Block till there is space */
static void work_push(qd_http_server_t *hs, work_t w) {
    work_queue_t *wq = &hs->work;
    sys_mutex_lock(wq->lock);
    while (wq->len == WORK_MAX) {
        lws_cancel_service(hs->context); /* Wake up the run thread to clear space */
        sys_cond_wait(wq->cond, wq->lock);
    }
    wq->work[(wq->head + wq->len) % WORK_MAX] = w;
    ++wq->len;
    sys_mutex_unlock(wq->lock);
    lws_cancel_service(hs->context); /* Wake up the run thread to handle my work */
}

/* Non-blocking, return { W_NONE, NULL } if empty */
static work_t work_pop(qd_http_server_t *hs) {
    work_t w = { W_NONE, NULL };
    work_queue_t *wq = &hs->work;
    sys_mutex_lock(wq->lock);
    if (wq->len > 0) {
        w = wq->work[wq->head];
        wq->head = (wq->head + 1) % WORK_MAX;
        --wq->len;
        sys_cond_signal(wq->cond);
    }
    sys_mutex_unlock(wq->lock);
    return w;
}

/* Each qd_lws_listener_t is associated with an lws_vhost */
struct qd_lws_listener_t {
    qd_listener_t *listener;
    qd_http_server_t *server;
    struct lws_vhost *vhost;
    struct lws_http_mount mount;
    struct lws_http_mount metrics;
    struct lws_http_mount healthz;
};

void qd_lws_listener_free(qd_lws_listener_t *hl) {
    if (!hl) return;
    if (hl->listener) {
        hl->listener->http = NULL;
        qd_listener_decref(hl->listener);
    }
    free(hl);
}

static qd_lws_listener_t *qd_lws_listener(qd_http_server_t *hs, qd_listener_t *li) {
    qd_lws_listener_t *hl = calloc(1, sizeof(*hl));
    if (hl) {
        hl->server = hs;
        hl->listener = li;
        li->http = hl;
        sys_atomic_inc(&li->ref_count); /* Keep it around till qd_http_server_free() */
    } else {
        qd_log(hs->log, QD_LOG_CRITICAL, "No memory for HTTP listen on %s",
               li->config.host_port);
    }
    return hl;
}

/* Linked list: first entry on each line should point to next, last line should be the
 * octet-stream default.
 */
static const struct lws_protocol_vhost_options mime_types[] = {
    { &mime_types[1], NULL, ".json", "application/json" },
    { &mime_types[2], NULL, ".woff2", "font/woff2" },
    { NULL, NULL, "*", "application/octet-stream" }
};

static void listener_start(qd_lws_listener_t *hl, qd_http_server_t *hs) {
    log_init();                 /* Update log flags at each listener */

    qd_server_config_t *config = &hl->listener->config;

    int port = qd_port_int(config->port);
    if (port < 0) {
        qd_log(hs->log, QD_LOG_ERROR, "HTTP listener %s has invalid port %s",
               config->host_port, config->port);
        goto error;
    }
    struct lws_http_mount *m = &hl->mount;
    m->mountpoint = "/";    /* URL mount point */
    m->mountpoint_len = strlen(m->mountpoint); /* length of the mountpoint */
    m->origin = (config->http_root_dir && *config->http_root_dir) ? /* File system root */
        config->http_root_dir : QPID_CONSOLE_STAND_ALONE_INSTALL_DIR;
    m->def = "index.html";  /* Default file name */
    m->origin_protocol = LWSMPRO_FILE; /* mount type is a directory in a filesystem */
    m->extra_mimetypes = mime_types;
    struct lws_http_mount *tail = m;
    if (config->metrics) {
        struct lws_http_mount *metrics = &hl->metrics;
        tail->mount_next = metrics;
        tail = metrics;
        metrics->mountpoint = "/metrics";
        metrics->mountpoint_len = strlen(metrics->mountpoint);
        metrics->origin_protocol = LWSMPRO_CALLBACK;
        metrics->protocol = "http";
        metrics->origin = IGNORED;
    }
    if (config->healthz) {
        struct lws_http_mount *healthz = &hl->healthz;
        tail->mount_next = healthz;
        healthz->mountpoint = "/healthz";
        healthz->mountpoint_len = strlen(healthz->mountpoint);
        healthz->origin_protocol = LWSMPRO_CALLBACK;
        healthz->protocol = "healthz";
        healthz->origin = IGNORED;
    }

    struct lws_context_creation_info info = {0};
    info.mounts = m;
    info.port = port;
    info.protocols = protocols;
    info.keepalive_timeout = 1;
    info.ssl_cipher_list = CIPHER_LIST;
    info.options |= LWS_SERVER_OPTION_VALIDATE_UTF8;
    if (config->ssl_profile) {
        info.ssl_cert_filepath = config->ssl_certificate_file;
        info.ssl_private_key_filepath = config->ssl_private_key_file;
        info.ssl_private_key_password = config->ssl_password;
        info.ssl_ca_filepath = config->ssl_trusted_certificate_db;
        info.ssl_cipher_list = config->ssl_ciphers;

        info.options |=
            LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT |
#if LWS_LIBRARY_VERSION_MAJOR > 3 || (LWS_LIBRARY_VERSION_MAJOR == 3 && LWS_LIBRARY_VERSION_MINOR >= 2)
            (config->ssl_required ? 0 : LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT | LWS_SERVER_OPTION_ALLOW_HTTP_ON_HTTPS_LISTENER) |
#else
            (config->ssl_required ? 0 : LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT) |
#endif
            ((config->requireAuthentication && info.ssl_ca_filepath) ? LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT : 0);
    }
    info.vhost_name = hl->listener->config.host_port;
    hl->vhost = lws_create_vhost(hs->context, &info);
    if (hl->vhost) {
        /* Store hl pointer in vhost */
        void *vp = lws_protocol_vh_priv_zalloc(hl->vhost, &protocols[0], sizeof(hl));
        memcpy(vp, &hl, sizeof(hl));
        qd_log(hs->log, QD_LOG_NOTICE, "Listening for HTTP on %s", config->host_port);
        return;
    } else {
        qd_log(hs->log, QD_LOG_NOTICE, "Error listening for HTTP on %s", config->host_port);
        goto error;
    }
    return;

  error:
    if (hl->listener->exit_on_error) {
        qd_log(hs->log, QD_LOG_CRITICAL, "Shutting down, required listener failed %s",
               config->host_port);
        exit(1);
    }
    qd_lws_listener_free(hl);
}

static void listener_close(qd_lws_listener_t *hl, qd_http_server_t *hs) {
    qd_server_config_t *config = &hl->listener->config;
    qd_log(hs->log, QD_LOG_NOTICE, "Stopped listening for HTTP on %s", config->host_port);
    lws_vhost_destroy(hl->vhost);
}

/*
 * LWS callback for un-promoted HTTP connections.
 * Note main HTTP file serving is handled by the "mount" struct below.
 */
static int callback_http(struct lws *wsi, enum lws_callback_reasons reason,
                         void *user, void *in, size_t len)
{
    switch (reason) {
    case LWS_CALLBACK_PROTOCOL_DESTROY:
        qd_lws_listener_free(wsi_listener(wsi));
        break;
      default:
        break;
    }
    /* Do default HTTP handling for all the cases we don't care about. */
    return lws_callback_http_dummy(wsi, reason, user, in, len);
}

/* Wake up a connection managed by the http server thread */
static void connection_wake(qd_connection_t *qd_conn)
{
    connection_t *c = qd_conn->context;
    if (c && qd_conn->listener->http) {
        qd_http_server_t *hs = qd_conn->listener->http->server;
        work_t w = { W_WAKE, c };
        work_push(hs, w);
    }
}

/**
 * Called on router worker thread
 */
static void handle_stats_results(void *context)
{
    stats_request_state_t* state = (stats_request_state_t*) context;
    if (state->wsi_deleted) {
        free(state);
    } else {
        qd_http_server_t *hs = state->server;
        if (hs) {
            work_t w = { W_HANDLE_STATS, state };
            work_push(hs, w);
        }
    }
}

/**
 * Called on http thread
 */
static void handle_stats_result_HT(stats_request_state_t* state)
{
    if (state->wsi_deleted) {
        free(state);
    } else {
        state->callback_completed = true;
        lws_callback_on_writable(state->wsi);
    }
}

typedef int (*int_metric) (qdr_global_stats_t *stats);
typedef struct metric_definition {
    const char* name;
    const char* type;
    int_metric value;
} metric_definition;

typedef struct allocator_metric_definition {
    const char* name;
    qd_alloc_stats_t *(*fn)(void);
} allocator_metric_definition;

static int stats_get_connections(qdr_global_stats_t *stats) { return stats->connections; }
static int stats_get_links(qdr_global_stats_t *stats) { return stats->links; }
static int stats_get_addrs(qdr_global_stats_t *stats) { return stats->addrs; }
static int stats_get_routers(qdr_global_stats_t *stats) { return stats->routers; }
static int stats_get_link_routes(qdr_global_stats_t *stats) { return stats->link_routes; }
static int stats_get_auto_links(qdr_global_stats_t *stats) { return stats->auto_links; }
static int stats_get_presettled_deliveries(qdr_global_stats_t *stats) { return stats->presettled_deliveries; }
static int stats_get_dropped_presettled_deliveries(qdr_global_stats_t *stats) { return stats->dropped_presettled_deliveries; }
static int stats_get_accepted_deliveries(qdr_global_stats_t *stats) { return stats->accepted_deliveries; }
static int stats_get_released_deliveries(qdr_global_stats_t *stats) { return stats->released_deliveries; }
static int stats_get_rejected_deliveries(qdr_global_stats_t *stats) { return stats->rejected_deliveries; }
static int stats_get_modified_deliveries(qdr_global_stats_t *stats) { return stats->modified_deliveries; }
static int stats_get_deliveries_ingress(qdr_global_stats_t *stats) { return stats->deliveries_ingress; }
static int stats_get_deliveries_egress(qdr_global_stats_t *stats) { return stats->deliveries_egress; }
static int stats_get_deliveries_transit(qdr_global_stats_t *stats) { return stats->deliveries_transit; }
static int stats_get_deliveries_ingress_route_container(qdr_global_stats_t *stats) { return stats->deliveries_ingress_route_container; }
static int stats_get_deliveries_egress_route_container(qdr_global_stats_t *stats) { return stats->deliveries_egress_route_container; }
static int stats_get_deliveries_delayed_1sec(qdr_global_stats_t *stats) { return stats->deliveries_delayed_1sec; }
static int stats_get_deliveries_delayed_10sec(qdr_global_stats_t *stats) { return stats->deliveries_delayed_10sec; }
static int stats_get_deliveries_stuck(qdr_global_stats_t *stats) { return stats->deliveries_stuck; }
static int stats_get_links_blocked(qdr_global_stats_t *stats) { return stats->links_blocked; }
static int stats_get_deliveries_redirected_to_fallback(qdr_global_stats_t *stats) { return stats->deliveries_redirected_to_fallback; }

qd_alloc_stats_t *alloc_stats_qd_bitmask_t(void);
qd_alloc_stats_t *alloc_stats_qd_buffer_t(void);
qd_alloc_stats_t *alloc_stats_qd_composed_field_t(void);
qd_alloc_stats_t *alloc_stats_qd_composite_t(void);
qd_alloc_stats_t *alloc_stats_qd_connection_t(void);
qd_alloc_stats_t *alloc_stats_qd_hash_handle_t(void);
qd_alloc_stats_t *alloc_stats_qd_hash_item_t(void);
qd_alloc_stats_t *alloc_stats_qd_iterator_t(void);
qd_alloc_stats_t *alloc_stats_qd_link_ref_t(void);
qd_alloc_stats_t *alloc_stats_qd_link_t(void);
qd_alloc_stats_t *alloc_stats_qd_listener_t(void);
qd_alloc_stats_t *alloc_stats_qd_log_entry_t(void);
qd_alloc_stats_t *alloc_stats_qd_management_context_t(void);
qd_alloc_stats_t *alloc_stats_qd_message_content_t(void);
qd_alloc_stats_t *alloc_stats_qd_message_t(void);
qd_alloc_stats_t *alloc_stats_qd_node_t(void);
qd_alloc_stats_t *alloc_stats_qd_parse_node_t(void);
qd_alloc_stats_t *alloc_stats_qd_parsed_field_t(void);
qd_alloc_stats_t *alloc_stats_qd_timer_t(void);
qd_alloc_stats_t *alloc_stats_qdr_action_t(void);
qd_alloc_stats_t *alloc_stats_qdr_address_config_t(void);
qd_alloc_stats_t *alloc_stats_qdr_address_t(void);
qd_alloc_stats_t *alloc_stats_qdr_connection_info_t(void);
qd_alloc_stats_t *alloc_stats_qdr_connection_t(void);
qd_alloc_stats_t *alloc_stats_qdr_connection_work_t(void);
qd_alloc_stats_t *alloc_stats_qdr_core_timer_t(void);
qd_alloc_stats_t *alloc_stats_qdr_delivery_cleanup_t(void);
qd_alloc_stats_t *alloc_stats_qdr_delivery_ref_t(void);
qd_alloc_stats_t *alloc_stats_qdr_delivery_t(void);
qd_alloc_stats_t *alloc_stats_qdr_field_t(void);
qd_alloc_stats_t *alloc_stats_qdr_general_work_t(void);
qd_alloc_stats_t *alloc_stats_qdr_link_ref_t(void);
qd_alloc_stats_t *alloc_stats_qdr_link_t(void);
qd_alloc_stats_t *alloc_stats_qdr_link_work_t(void);
qd_alloc_stats_t *alloc_stats_qdr_query_t(void);
qd_alloc_stats_t *alloc_stats_qdr_terminus_t(void);

static struct metric_definition metrics[] = {
    {"qdr_connections_total", "gauge", stats_get_connections},
    {"qdr_links_total", "gauge", stats_get_links},
    {"qdr_addresses_total", "gauge", stats_get_addrs},
    {"qdr_routers_total", "gauge", stats_get_routers},
    {"qdr_link_routes_total", "gauge", stats_get_link_routes},
    {"qdr_auto_links_total", "gauge", stats_get_auto_links},
    {"qdr_presettled_deliveries_total", "counter", stats_get_presettled_deliveries},
    {"qdr_dropped_presettled_deliveries_total", "counter", stats_get_dropped_presettled_deliveries},
    {"qdr_accepted_deliveries_total", "counter", stats_get_accepted_deliveries},
    {"qdr_released_deliveries_total", "counter", stats_get_released_deliveries},
    {"qdr_rejected_deliveries_total", "counter", stats_get_rejected_deliveries},
    {"qdr_modified_deliveries_total", "counter", stats_get_modified_deliveries},
    {"qdr_deliveries_ingress_total", "counter", stats_get_deliveries_ingress},
    {"qdr_deliveries_egress_total", "counter", stats_get_deliveries_egress},
    {"qdr_deliveries_transit_total", "counter", stats_get_deliveries_transit},
    {"qdr_deliveries_ingress_route_container_total", "counter", stats_get_deliveries_ingress_route_container},
    {"qdr_deliveries_egress_route_container_total", "counter", stats_get_deliveries_egress_route_container},
    {"qdr_deliveries_delayed_1sec_total", "counter", stats_get_deliveries_delayed_1sec},
    {"qdr_deliveries_delayed_10sec_total", "counter", stats_get_deliveries_delayed_10sec},
    {"qdr_deliveries_stuck_total", "gauge", stats_get_deliveries_stuck},
    {"qdr_links_blocked_total", "gauge", stats_get_links_blocked},
    {"qdr_deliveries_redirected_to_fallback_total", "counter", stats_get_deliveries_redirected_to_fallback}
};
static size_t metrics_length = sizeof(metrics)/sizeof(metrics[0]);

static struct allocator_metric_definition allocator_metrics[] = {
        {"qdr_allocator_qd_bitmask_t", alloc_stats_qd_bitmask_t},
        {"qdr_allocator_qd_buffer_t", alloc_stats_qd_buffer_t},
        {"qdr_allocator_qd_composed_field_t", alloc_stats_qd_composed_field_t},
        {"qdr_allocator_qd_composite_t", alloc_stats_qd_composite_t},
        {"qdr_allocator_qd_connection_t", alloc_stats_qd_connection_t},
        {"qdr_allocator_qd_hash_handle_t", alloc_stats_qd_hash_handle_t},
        {"qdr_allocator_qd_hash_item_t", alloc_stats_qd_hash_item_t},
        {"qdr_allocator_qd_iterator_t", alloc_stats_qd_iterator_t},
        {"qdr_allocator_qd_link_ref_t", alloc_stats_qd_link_ref_t},
        {"qdr_allocator_qd_link_t", alloc_stats_qd_link_t},
        {"qdr_allocator_qd_listener_t", alloc_stats_qd_listener_t},
        {"qdr_allocator_qd_log_entry_t", alloc_stats_qd_log_entry_t},
        {"qdr_allocator_qd_management_context_t", alloc_stats_qd_management_context_t},
        {"qdr_allocator_qd_message_content_t", alloc_stats_qd_message_content_t},
        {"qdr_allocator_qd_message_t", alloc_stats_qd_message_t},
        {"qdr_allocator_qd_node_t", alloc_stats_qd_node_t},
        {"qdr_allocator_qd_parse_node_t", alloc_stats_qd_parse_node_t},
        {"qdr_allocator_qd_parsed_field_t", alloc_stats_qd_parsed_field_t},
        {"qdr_allocator_qd_timer_t", alloc_stats_qd_timer_t},
        {"qdr_allocator_qdr_action_t", alloc_stats_qdr_action_t},
        {"qdr_allocator_qdr_address_config_t", alloc_stats_qdr_address_config_t},
        {"qdr_allocator_qdr_address_t", alloc_stats_qdr_address_t},
        {"qdr_allocator_qdr_connection_info_t", alloc_stats_qdr_connection_info_t},
        {"qdr_allocator_qdr_connection_t", alloc_stats_qdr_connection_t},
        {"qdr_allocator_qdr_connection_work_t", alloc_stats_qdr_connection_work_t},
        {"qdr_allocator_qdr_core_timer_t", alloc_stats_qdr_core_timer_t},
        {"qdr_allocator_qdr_delivery_cleanup_t", alloc_stats_qdr_delivery_cleanup_t},
        {"qdr_allocator_qdr_delivery_ref_t", alloc_stats_qdr_delivery_ref_t},
        {"qdr_allocator_qdr_delivery_t", alloc_stats_qdr_delivery_t},
        {"qdr_allocator_qdr_field_t", alloc_stats_qdr_field_t},
        {"qdr_allocator_qdr_general_work_t", alloc_stats_qdr_general_work_t},
        {"qdr_allocator_qdr_link_ref_t", alloc_stats_qdr_link_ref_t},
        {"qdr_allocator_qdr_link_t", alloc_stats_qdr_link_t},
        {"qdr_allocator_qdr_link_work_t", alloc_stats_qdr_link_work_t},
        {"qdr_allocator_qdr_query_t", alloc_stats_qdr_query_t},
        {"qdr_allocator_qdr_terminus_t", alloc_stats_qdr_terminus_t}
};
static size_t allocator_metrics_length = sizeof(allocator_metrics)/sizeof(allocator_metrics[0]);

#define ALLOC_DATA(S, F) ((allocator_field) {#F, (S!=NULL? S->F: 0)})

typedef struct allocator_field {
    const char* name;
    uint64_t value;
} allocator_field;

static bool write_stats(uint8_t **position, const uint8_t * const end, const char* name, const char* type, int value)
{
    //11 chars + type + 2*name + 20 chars for int
    // average metric name size is 30 bytes
    // average metric type size is 8 bytes
    // current number of metrics is 22
    // total metric buffer size = 22 * (11 + 8 + 2*30 + 20) = 2178
    size_t length = 11 + strlen(type) + strlen(name)*2 + 20;
    if (end - *position >= length) {
        *position += lws_snprintf((char*) *position, end - *position, "# TYPE %s %s\n", name, type);
        *position += lws_snprintf((char*) *position, end - *position, "%s %i\n", name, value);
        return true;
    } else {
        return false;
    }
}

static bool write_allocator_stats(uint8_t **position, const uint8_t * const end, const char* name, allocator_field field)
{
    // 30 chars (static) + 2*name + 2*field.name + 20 for int
    // average allocator metric name size is 54 bytes (name:field.name)
    // current number of metrics is 180
    // total allocator buffer size = 180 * (30 + 2*54 + 20) = 28440
    size_t length = 30 + strlen(name)*2 + strlen(field.name)*2 + 20;
    if (end - *position >= length) {
        *position += lws_snprintf((char*) *position, end - *position, "# TYPE %s:%s_bytes gauge\n", name, field.name);
        *position += lws_snprintf((char*) *position, end - *position, "%s:%s_bytes %"PRIu64"\n", name, field.name, field.value);
        return true;
    } else {
        return false;
    }
}

static bool write_metric(uint8_t **position, const uint8_t * const end, metric_definition* definition, qdr_global_stats_t* stats)
{
    return write_stats(position, end, definition->name, definition->type, definition->value(stats));
}

static bool write_allocator_metric(uint8_t **position, const uint8_t * const end, allocator_metric_definition* definition)
{
    qd_alloc_stats_t *allocator_stats = definition->fn();
    if (!write_allocator_stats(position, end, definition->name, ALLOC_DATA(allocator_stats, total_alloc_from_heap))) return false;
    if (!write_allocator_stats(position, end, definition->name, ALLOC_DATA(allocator_stats, total_free_to_heap))) return false;
    if (!write_allocator_stats(position, end, definition->name, ALLOC_DATA(allocator_stats, held_by_threads))) return false;
    if (!write_allocator_stats(position, end, definition->name, ALLOC_DATA(allocator_stats, batches_rebalanced_to_threads))) return false;
    if (!write_allocator_stats(position, end, definition->name, ALLOC_DATA(allocator_stats, batches_rebalanced_to_global))) return false;
    return true;
}

static int add_header_by_name(struct lws *wsi, const char* name, const char* value, uint8_t** position, uint8_t* end)
{
    return lws_add_http_header_by_name(wsi, (unsigned char*) name, (unsigned char*) value, strlen(value), position, end);
}

static int callback_metrics(struct lws *wsi, enum lws_callback_reasons reason,
                               void *user, void *in, size_t len)
{
    qd_http_server_t *hs = wsi_server(wsi);
    stats_t *stats = (stats_t*) user;
    // rationale for buffer size is explained at write_stats and write_allocator_stats
    uint8_t buffer[LWS_PRE + 30618];
    uint8_t *start = &buffer[LWS_PRE], *position = start, *end = &buffer[sizeof(buffer) - LWS_PRE - 1];

    switch (reason) {

    case LWS_CALLBACK_HTTP: {
        stats->context = NEW(stats_request_state_t);
        ZERO(stats->context);
        stats->context->wsi = wsi;
        stats->context->server = hs;
        //request stats from core thread
        qdr_request_global_stats(hs->core, &stats->context->stats, handle_stats_results, (void*) stats->context);
        return 0;
    }

    case LWS_CALLBACK_HTTP_WRITEABLE: {
        //encode stats into buffer
        if (!stats->headers_sent) {
            if (lws_add_http_header_status(wsi, HTTP_STATUS_OK, &position, end)
                || add_header_by_name(wsi, "content-type:", "text/plain", &position, end)
                || add_header_by_name(wsi, "connection:", "close", &position, end))
                return 1;
            if (lws_finalize_http_header(wsi, &position, end))
                return 1;
            stats->headers_sent = true;
        }

        while (stats->current < metrics_length) {
            if (write_metric(&position, end, &metrics[stats->current], &stats->context->stats)) {
                stats->current++;
                qd_log(hs->log, QD_LOG_DEBUG, "wrote metric %lu of %lu", stats->current, metrics_length);
            } else {
                qd_log(hs->log, QD_LOG_WARNING, "insufficient space in buffer");
                break;
            }
        }

        int alloc_cur = 0;
        while (alloc_cur < allocator_metrics_length) {
            if (write_allocator_metric(&position, end, &allocator_metrics[alloc_cur])) {
                qd_log(hs->log, QD_LOG_DEBUG, "wrote allocator metric %lu of %lu", alloc_cur, allocator_metrics_length);
                alloc_cur++;
            } else {
                qd_log(hs->log, QD_LOG_WARNING, "insufficient space in buffer");
                break;
            }
        }
        int n = (stats->current < metrics_length) || (alloc_cur < allocator_metrics_length) ? LWS_WRITE_HTTP : LWS_WRITE_HTTP_FINAL;

        //write buffer
        size_t available = position - start;
        if (lws_write(wsi, (unsigned char*) start, available, n) != available)
            return 1;
        if (n == LWS_WRITE_HTTP_FINAL) {
            if (lws_http_transaction_completed(wsi)) return -1;
        } else {
            lws_callback_on_writable(wsi);
        }
        return 0;
    }

    case LWS_CALLBACK_CLOSED: {
        stats->context->wsi_deleted = true;
        if (stats->context->callback_completed) {
            free(stats->context);
        }
    }

    default:
        return 0;
    }
}

static int callback_healthz(struct lws *wsi, enum lws_callback_reasons reason,
                               void *user, void *in, size_t len)
{
    qd_http_server_t *hs = wsi_server(wsi);
    stats_t *stats = (stats_t*) user;
    uint8_t buffer[LWS_PRE + 2048];
    uint8_t *start = &buffer[LWS_PRE], *position = start, *end = &buffer[sizeof(buffer) - LWS_PRE - 1];

    switch (reason) {

    case LWS_CALLBACK_HTTP: {
        stats->context = NEW(stats_request_state_t);
        ZERO(stats->context);
        stats->context->wsi = wsi;
        stats->context->server = hs;
        //make dummy request for stats (pass in null ptr); this still exercises the
        //path through core thread and back through callback on io thread which is
        //a reasonable initial liveness check
        qdr_request_global_stats(hs->core, 0, handle_stats_results, (void*) stats->context);
        return 0;
    }

    case LWS_CALLBACK_HTTP_WRITEABLE: {
        //encode stats into buffer
        if (!stats->headers_sent) {
            if (lws_add_http_header_status(wsi, HTTP_STATUS_OK, &position, end)
                || add_header_by_name(wsi, "content-type:", "text/plain", &position, end)
                || lws_add_http_header_content_length(wsi, 3, &position, end))
                return 1;
            if (lws_finalize_http_header(wsi, &position, end))
                return 1;
            stats->headers_sent = true;
        }
        position += lws_snprintf((char*) position, end - position, "OK\n");

        int n = LWS_WRITE_HTTP_FINAL;
        //write buffer
        size_t available = position - start;
	if (lws_write(wsi, (unsigned char*) start, available, n) != available)
            return 1;
        else if (lws_http_transaction_completed(wsi))
            return -1;
        else return 0;
    }

    case LWS_CALLBACK_CLOSED: {
        stats->context->wsi_deleted = true;
        if (stats->context->callback_completed) {
            free(stats->context);
        }
    }

    default:
        return 0;
    }
}

/* Callbacks for promoted AMQP over WS connections. */
static int callback_amqpws(struct lws *wsi, enum lws_callback_reasons reason,
                           void *user, void *in, size_t len)
{
    qd_http_server_t *hs = wsi_server(wsi);
    connection_t *c = (connection_t*)user;

    switch (reason) {

    case LWS_CALLBACK_ESTABLISHED: {
        /* Upgrade accepted HTTP connection to AMQPWS */
        memset(c, 0, sizeof(*c));
        c->wsi = wsi;
        qd_lws_listener_t *hl = wsi_listener(wsi);
        if (hl == NULL || !hl->listener->config.websockets) {
            return unexpected_close(c->wsi, "cannot-upgrade");
        }
        c->qd_conn = qd_server_connection(hs->server, &hl->listener->config);
        if (c->qd_conn == NULL) {
            return unexpected_close(c->wsi, "out-of-memory");
        }
        c->qd_conn->context = c;
        c->qd_conn->wake = connection_wake;
        c->qd_conn->listener = hl->listener;
        lws_get_peer_simple(wsi, c->qd_conn->rhost, sizeof(c->qd_conn->rhost));
        int err = pn_connection_driver_init(&c->driver, c->qd_conn->pn_conn, NULL);
        if (err) {
            return unexpected_close(c->wsi, pn_code(err));
        }
        strncpy(c->qd_conn->rhost_port, c->qd_conn->rhost, sizeof(c->qd_conn->rhost_port));
        qd_log(hs->log, QD_LOG_DEBUG,
               "[%"PRIu64"] upgraded HTTP connection from %s to AMQPWS",
               qd_connection_connection_id(c->qd_conn), qd_connection_name(c->qd_conn));
        return handle_events(c);
    }

    case LWS_CALLBACK_SERVER_WRITEABLE: {
        if (handle_events(c)) return -1;
        pn_bytes_t dbuf = pn_connection_driver_write_buffer(&c->driver);
        if (dbuf.size) {
            /* lws_write() demands LWS_PRE bytes of free space before the data,
             * so we must copy from the driver's buffer to larger temporary wbuf
             */
            buffer_set_size(&c->wbuf, LWS_PRE + dbuf.size);
            if (c->wbuf.start == NULL) {
                return unexpected_close(c->wsi, "out-of-memory");
            }
            unsigned char* buf = (unsigned char*)c->wbuf.start + LWS_PRE;
            memcpy(buf, dbuf.start, dbuf.size);
            ssize_t wrote = lws_write(wsi, buf, dbuf.size, LWS_WRITE_BINARY);
            if (wrote < 0) {
                pn_connection_driver_write_close(&c->driver);
                return unexpected_close(c->wsi, "write-error");
            } else {
                pn_connection_driver_write_done(&c->driver, wrote);
            }
        }
        return handle_events(c);
    }

    case LWS_CALLBACK_RECEIVE: {
        while (len > 0) {
            if (handle_events(c)) return -1;
            pn_rwbytes_t dbuf = pn_connection_driver_read_buffer(&c->driver);
            if (dbuf.size == 0) {
                return unexpected_close(c->wsi, "unexpected-data");
            }
            size_t copy = (len < dbuf.size) ? len : dbuf.size;
            memcpy(dbuf.start, in, copy);
            pn_connection_driver_read_done(&c->driver, copy);
            len -= copy;
            in = (char*)in + copy;
        }
        return handle_events(c);
    }

    case LWS_CALLBACK_USER: {
        pn_timestamp_t next_tick = pn_transport_tick(c->driver.transport, hs->now);
        if (next_tick && next_tick > hs->now && next_tick < hs->next_tick) {
            hs->next_tick = next_tick;
        }
        return handle_events(c);
    }

    case LWS_CALLBACK_WS_PEER_INITIATED_CLOSE: {
        pn_connection_driver_read_close(&c->driver);
        return handle_events(c);
    }

    case LWS_CALLBACK_CLOSED: {
        if (c->driver.transport) {
            pn_connection_driver_close(&c->driver);
            handle_events(c);
        }
        pn_connection_driver_destroy(&c->driver);
        free(c->wbuf.start);
        return -1;
    }

    default:
        return 0;
    }
}

#define DEFAULT_TICK 1000

static void* http_thread_run(void* v) {
    qd_http_server_t *hs = v;
    qd_log(hs->log, QD_LOG_INFO, "HTTP server thread running");
    int result = 0;
    while(result >= 0) {
        /* Send a USER event to run transport ticks, may decrease hs->next_tick. */
        hs->now = qd_timer_now();
        hs->next_tick = hs->now + DEFAULT_TICK;
        lws_callback_all_protocol(hs->context, &protocols[1], LWS_CALLBACK_USER);
        lws_callback_all_protocol(hs->context, &protocols[2], LWS_CALLBACK_USER);
        pn_millis_t timeout = (hs->next_tick > hs->now) ? hs->next_tick - hs->now : 1;
        result = lws_service(hs->context, timeout);

        /* Process any work items on the queue */
        for (work_t w = work_pop(hs); w.type != W_NONE; w = work_pop(hs)) {
            switch (w.type) {
            case W_NONE:
                break;
            case W_STOP:
                result = -1;
                break;
            case W_LISTEN:
                listener_start((qd_lws_listener_t*)w.value, hs);
                break;
            case W_CLOSE:
                listener_close((qd_lws_listener_t*)w.value, hs);
                break;
            case W_HANDLE_STATS:
                handle_stats_result_HT((stats_request_state_t*) w.value);
                break;
            case W_WAKE: {
                connection_t *c = w.value;
                pn_collector_put(c->driver.collector, PN_OBJECT, c->driver.connection,
                                 PN_CONNECTION_WAKE);
                handle_events(c);
                break;
            }
            }
        }
    }
    qd_log(hs->log, QD_LOG_INFO, "HTTP server thread exit");
    return NULL;
}

void qd_http_server_stop(qd_http_server_t *hs) {
    if (!hs) return;
    if (hs->thread) {
        /* Thread safe, stop via work queue then clean up */
        work_t work = { W_STOP, NULL };
        work_push(hs, work);
        sys_thread_join(hs->thread);
        sys_thread_free(hs->thread);
        hs->thread = NULL;
    }
}

void qd_http_server_free(qd_http_server_t *hs) {
    if (!hs) return;
    qd_http_server_stop(hs);
    work_queue_destroy(&hs->work);
    if (hs->context) lws_context_destroy(hs->context);
    free(hs);
}

qd_http_server_t *qd_http_server(qd_server_t *s, qd_log_source_t *log) {
    log_init();
    qd_http_server_t *hs = calloc(1, sizeof(*hs));
    if (hs) {
        work_queue_init(&hs->work);
        struct lws_context_creation_info info = {0};
        info.gid = info.uid = -1;
        info.user = hs;
        info.server_string = QD_CONNECTION_PROPERTY_PRODUCT_VALUE;
        info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS |
            LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME |
            LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
        info.max_http_header_pool = 32;
        info.timeout_secs = 1;

        hs->context = lws_create_context(&info);
        hs->server = s;
        hs->log = log;              /* For messages from this file */
        hs->core = 0; // not yet available
        if (!hs->context) {
            qd_log(hs->log, QD_LOG_CRITICAL, "No memory starting HTTP server");
            qd_http_server_free(hs);
            hs = NULL;
        }
    }
    return hs;
}

/* Thread safe calls that put items on work queue */

qd_lws_listener_t *qd_http_server_listen(qd_http_server_t *hs, qd_listener_t *li)
{
    hs->core = qd_dispatch_router_core(qd_server_dispatch(hs->server));
    sys_mutex_lock(hs->work.lock);
    if (!hs->thread) {
        hs->thread = sys_thread(http_thread_run, hs);
    }
    bool ok = hs->thread;
    sys_mutex_unlock(hs->work.lock);
    if (!ok) return NULL;

    qd_lws_listener_t *hl = qd_lws_listener(hs, li);
    if (hl) {
        work_t w = { W_LISTEN, hl };
        work_push(hs, w);
    }
    return hl;
}

void qd_lws_listener_close(qd_lws_listener_t *hl)
{
    work_t w = { W_CLOSE, hl };
    work_push(hl->server, w);
}

static qd_http_server_t *wsi_server(struct lws *wsi) {
    return (qd_http_server_t*)lws_context_user(lws_get_context(wsi));
}

static qd_lws_listener_t *wsi_listener(struct lws *wsi) {
    qd_lws_listener_t *hl = NULL;
    struct lws_vhost *vhost = lws_get_vhost(wsi);
    if (vhost) {                /* Get qd_lws_listener from vhost data */
        void *vp = lws_protocol_vh_priv_get(vhost, &protocols[0]);
        memcpy(&hl, vp, sizeof(hl));
    }
    return hl;
}

static qd_log_source_t *wsi_log(struct lws *wsi) {
    return wsi_server(wsi)->log;
}


text:
import imp

class UnityClass(dict):
	def __init__(self, version=None, *args, **kwargs):
		super(UnityClass, self).__init__(*args, **kwargs)

		self.versions = set()
		self.load("common")

		if version:
			self.load(version)

	def load(self, version):
		definitions = imp.load_source(version, "ClassDefinition/%s.py" % version)
		self.versions.add(definitions.version)
		self.update(definitions.classes)

	def reload(self):
		versions = list(self.versions)
		self.clear()
		self.versions.clear()
		for version in versions:
			self.load(version)


text: API utitilies to be used in a koco project


text:
<md-content class="Page-Container Footer iOS-hack" layout-align="center center">

    © 2016 CEA Jalisco

</md-content>


text:
package nexus.diff.ops

import nexus.diff._
import nexus.diff.exception._
import nexus.diff.ops.mixin._
import nexus._
import nexus.typelevel.Remove.Aux
import nexus.typelevel._

object Sum {

  object All extends PolyOp1 {
    implicit def sumAllF[T[_], R, A](implicit T: IsRealTensorK[T, R]): P[T[A], R] =
      new P[T[A], R] {
        def name = "Sum"
        def tag = Tag.real[R]
        def forward(x: T[A]) = T.sum(x)
        def backward(dy: R, y: R, x: T[A]) = ???
      }
  }

  object Along extends ParameterizedPolyOp1 with RealAxisReductionOpMixin {
    def name = "SumAlong"
    def forwardR[T[_], R, U, I <: Dim, V](x: T[U], dim: I)(implicit T: IsRealTensorK[T, R], rx: Remove.Aux[U, I, V]): T[V] = ???
    def backwardR[T[_], R, U, I <: Dim, V](dy: T[V], y: T[V], x: T[U])(implicit T: IsRealTensorK[T, R], rx: Remove.Aux[U, I, V]) = ???
  }

}

object ProdAlong extends ParameterizedPolyOp1 {

}

object Mean {

  object Along extends ParameterizedPolyOp1 with RealAxisReductionOpMixin {
    def name = "MeanAlong"
    def forwardR[T[_], R, U, I <: Dim, V](x: T[U], dim: I)(implicit T: IsRealTensorK[T, R], rx: Aux[U, I, V]) = ???
    def backwardR[T[_], R, U, I <: Dim, V](dy: T[V], y: T[V], x: T[U])(implicit T: IsRealTensorK[T, R], rx: Aux[U, I, V]) = ???
  }

}

object ArgMaxAlong extends ParameterizedPolyOp1 {

  implicit def argmaxAlongF[TR[_], R, TZ[_], Z, a, u <: Dim, b]
  (implicit TR: IsRealTensorK[TR, R], TZ: IsIntTensorK[TZ, Z], r: Remove.Aux[a, u, b]) = (u: u) =>
    new P[TR[a], TZ[b]] {
      def name = s"ArgMaxAlong[${typeName(u)}"
      def tag = Tag.tensor[TZ, Z, b] // TODO: intTensor
      override def differentiable = false
      def forward(x: TR[a]) = ???
      def backward(dy: TZ[b], y: TZ[b], x: TR[a]) = throw new OperatorNotDifferentiableException(this, 1)
    }

}

object ArgMinAlong extends ParameterizedPolyOp1

object MaxAlong extends ParameterizedPolyOp1

object MinAlong extends ParameterizedPolyOp1


text:
require 'rails_helper'

RSpec.describe Book, :type => :model do

  it 'detects when the book has reviews' do
    @book = FactoryGirl.create(:book)
    @review = FactoryGirl.create(:review, book: @book)
    expect(@book.has_reviews?).to eq(true)
  end

  it 'detects when the book does not have reviews' do
  	@book = FactoryGirl.create(:book)
  	expect(@book.has_reviews?).to eq(false)
  end

end


text:
package com.androidstarterkit.injection.model;

import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;
import java.util.List;

public class Snippet {
  @SerializedName("element")
  private List<String> elements;

  @SerializedName("lines")
  private List<String> codelines;

  public Snippet(List<String> elements, String codeline) {
    this.elements = elements;

    if (codelines == null) {
      codelines = new ArrayList<>();
    }
    codelines.add(codeline);
  }

  public Snippet(List<String> elements, List<String> codelines) {
    this.elements = elements;
    this.codelines = codelines;
  }

  public List<String> getElements() {
    if (elements == null) {
      elements = new ArrayList<>();
    }
    return elements;
  }

  public void setElements(List<String> elements) {
    this.elements = elements;
  }

  public List<String> getCodelines() {
    return codelines;
  }

  public void setCodelines(List<String> codelines) {
    this.codelines = codelines;
  }

  public boolean hasElement() {
    return elements != null;
  }

  @Override
  public String toString() {
    return "CodeBlock{" +
        "elements=" + (elements != null ? elements.toString() : "" ) +
        ", codelines=" + codelines.toString() +
        '}';
  }
}


text:
var express = require('express');
var router = express.Router();

router.get('/webapp3/api/add', function(req, res, next) {

    try {
        var a = ("a" in req.query) ? parseInt(req.query.a) : 0;
        var b = ("b" in req.query) ? parseInt(req.query.b) : 0;

        if (String(a) != req.query.a) throw "something"
        if (String(b) != req.query.b) throw "something"

        res.setHeader('content-type', 'application/json');

        res.send(JSON.stringify({
            "apiversion": "1.0",
            "status": "OK",
            "result": a + b,
            "flag": "YOU_CAN_PEEK_HTTP_RESPONSE" }));

    } catch(e) {
        res.send(JSON.stringify({
            "apiversion": "1.0",
            "status": "Fail",
            "result": "HINT: press F12 key to see http response...",
            "flag": "YOU_CAN_PEEK_HTTP_RESPONSE" }));
    }
});

router.get('/:problemId', function(req, res, next) {
    var model = require('../../model');

    // 渡されるproblem_idの問題を読み込み
    var Problem = model.Problem;
    Problem.findOne({ problem_id: req.params.problemId }, function(err, problem) {
        try {
            if (problem == null) throw "Problem not found.";
            res.render('problem_public', { problem: problem });
        }
        catch (e) {
            console.log(e);
            res.status(503).send(e);
        }
    });
});

router.post('/webapp1', function(req, res, next) {
    var username = req.body.username;
    var password = req.body.password;
    var md5sum = require('crypto').createHash('md5');
    md5sum.update(username + password);
    var digest = md5sum.digest('hex');
    if (digest == 'f12070c20cf77e9103b88f8cc3ac8f80') {
        res.render('problem/webapp1');
    } else {
        res.send('Invalid username or password.');
    }
});

router.post('/webapp2', function(req, res, next) {

    var pg = require('pg');
    var pg_uri = process.env.POSTGRES_URI || ""
    if (!pg_uri) throw new Error('There is no postgresql uri')
    var client = new pg.Client(process.env.POSTGRES_URI);
    client.connect(function(err) {
        if (err) {
            return res.send('could not connect to pgsql', err);
        }

        var user = ("username" in req.body) ? req.body.username : "";
        var pass = ("password" in req.body) ? req.body.password : "";
        var sql = "select username from userdb where username = '" + user + "' and password = md5('" + pass + "');";

        // SELECT以外のコマンドをエラー扱い
        // INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER, CREATE, CONNECT, TEMPORARY, EXECUTE, and USAGE.
        if ( sql.match(/insert/i)
          || sql.match(/update/i)
          || sql.match(/delete/i)
          || sql.match(/truncate/i)
          || sql.match(/references/i)
          || sql.match(/trigger/i)
          || sql.match(/create/i)
          || sql.match(/connect/i)
          || sql.match(/temporary/i)
          || sql.match(/execute/i)
          || sql.match(/usage/i)
          || sql.match(/alter/i)
          || sql.match(/revoke/i)
          || sql.match(/grant/i)
        ){
            return res.send('Invalid query.');
        }

        client.query(sql, function(err, result) {
            client.end();

            if (err) return res.send(err);
            if (result.rows.length == 0) return res.send('Invalid username or password.');

            var outputString = result;
            var username = user;
            res.render('problem/webapp2', { output: outputString, username } );
        });
    });

});

module.exports = router;


text:
using namespace foundation;
using namespace std;

namespace appleseed {
namespace shared {

SuperLogger::SuperLogger()
  : m_log_target(nullptr)
{
    set_log_target(create_open_file_log_target(stderr));
}

SuperLogger::~SuperLogger()
{
    delete m_log_target;
}

ILogTarget& SuperLogger::get_log_target() const
{
    return *m_log_target;
}

void SuperLogger::set_log_target(ILogTarget* log_target)
{
    if (m_log_target)
    {
        remove_target(m_log_target);
        delete m_log_target;
    }

    m_log_target = log_target;
    add_target(m_log_target);
}

void SuperLogger::enable_message_coloring()
{
#ifndef _WIN32
    const int StdErrFileDesc = 2;
    if (!isatty(StdErrFileDesc))
        return;
#endif

    set_log_target(create_console_log_target(stderr));
}

void SuperLogger::set_verbosity_level_from_string(const char* level_name, const bool warn_if_invalid)
{
    const LogMessage::Category level = LogMessage::get_category_value(level_name);

    if (level < LogMessage::NumMessageCategories)
        set_verbosity_level(level);
    else if (warn_if_invalid)
        LOG_ERROR(*this, "invalid message verbosity level \"%s\".", level_name);
}

void SuperLogger::configure_from_settings(const Dictionary& settings)
{
    if (settings.strings().exist("message_coloring"))
    {
        const char* value = settings.get("message_coloring");
        try
        {
            if (from_string<bool>(value))
                enable_message_coloring();
        }
        catch (const ExceptionStringConversionError&)
        {
            LOG_ERROR(*this, "invalid value \"%s\" for parameter \"message_coloring\".", value);
        }
    }

    if (settings.strings().exist("message_verbosity"))
        set_verbosity_level_from_string(settings.get("message_verbosity"));
}

}   // namespace shared
}   // namespace appleseed


text: export { Cda20 as default } from "../../";


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var router_1 = require('@angular/router');
var msn_login_1 = require('../../../../services/msn.login');
var modallogin_1 = require('../../../../shared/components/login/modallogin');
var msn_service_1 = require('../../../../services/msn.service');
var UserVerifyComponent = (function () {
    function UserVerifyComponent(msnService, loginService, router, route) {
        this.msnService = msnService;
        this.loginService = loginService;
        this.router = router;
        this.route = route;
        this.serviceinfoChange = new core_1.EventEmitter();
        this.postUserRequest = new core_1.EventEmitter();
        this.isOTPVerifyPhase = false;
        this.isOTPVerifyDone = false;
        this.isLoggedInUser = false;
        this.isMobileVerified = false;
        this.initialLoad();
    }
    UserVerifyComponent.prototype.ngOnInit = function () {
    };
    UserVerifyComponent.prototype.initialLoad = function () {
        var _this = this;
        var currentUser = JSON.parse(localStorage.getItem('currentUser'));
        this.isLoggedInUser = false;
        if (currentUser)
            this.loginService.loginUserInfo(currentUser).subscribe(function (user) {
                if (user.HasRegistered) {
                    _this.isLoggedInUser = true;
                    _this.user = user;
                    _this.serviceinfo.userid = user.ID;
                    if (user.Phone != "" && user.Phone != null)
                        _this.isMobileVerified = true;
                    console.log(user);
                }
            });
    };
    //titleChange(value) {
    //    this.serviceinfoChange.emit(this.serviceinfo);
    //}
    //descriptionChange(value) {
    //    this.serviceinfoChange.emit(this.serviceinfo);
    //}
    UserVerifyComponent.prototype.sendOTPClicked = function () {
        this.isOTPVerifyPhase = true;
        //logic for sending OTP message
    };
    UserVerifyComponent.prototype.afterVerifyOTPClick = function () {
        this.isOTPVerifyDone = true;
        this.isOTPVerifyPhase = false;
        this.postUserRequest.emit(this.serviceinfo);
    };
    UserVerifyComponent.prototype.confirmRequest = function () {
        this.postUserRequest.emit(this.serviceinfo);
    };
    UserVerifyComponent.prototype.loginOrSignupclick = function () {
        this.myLoginModal.open();
        //this.initialLoad();
    };
    __decorate([
        core_1.ViewChild('modallogin'),
        __metadata('design:type', modallogin_1.ModalLoginComponent)
    ], UserVerifyComponent.prototype, "myLoginModal", void 0);
    __decorate([
        core_1.Input(),
        __metadata('design:type', Object)
    ], UserVerifyComponent.prototype, "serviceinfo", void 0);
    __decorate([
        core_1.Output(),
        __metadata('design:type', core_1.EventEmitter)
    ], UserVerifyComponent.prototype, "serviceinfoChange", void 0);
    __decorate([
        core_1.Output(),
        __metadata('design:type', core_1.EventEmitter)
    ], UserVerifyComponent.prototype, "postUserRequest", void 0);
    UserVerifyComponent = __decorate([
        core_1.Component({
            selector: 'userverify',
            templateUrl: 'app/core/userview/postservice/userverify/userverify.html',
            styleUrls: ['app/core/userview/postservice/userverify/userverify.css'],
            providers: [msn_service_1.MSNService, msn_login_1.LoginService],
            directives: []
        }),
        __metadata('design:paramtypes', [msn_service_1.MSNService, msn_login_1.LoginService, router_1.Router, router_1.ActivatedRoute])
    ], UserVerifyComponent);
    return UserVerifyComponent;
}());
exports.UserVerifyComponent = UserVerifyComponent;
//# sourceMappingURL=userverify.js.map


text:
(function(app) {
    'use strict';
    app.filter('encodeURIComponent', [function() {
        return window.encodeURIComponent;
    }]);

    app.filter('limitChars', [function() {
        return function(chars, limit){
            return chars.substring(0, limit) + '...';
        };
    }]);

    app.filter('toFixed', [function() {
        return function(nums){
            return (+nums).toFixed(2);
        };
    }]);

    app.filter('getColorCode', ['CONSTANT_COLORS', 'utility', function(CONSTANT_COLORS, utility) {
    	return function(colorName){
    		return utility.getColorCode(colorName).hex;
    	};
    }]);
})(angular.module("Meanapp"));

/*

db.products.update({
    "size.text": "SELECT Size"
}, {
 $set: {
   "size.$.text": ""
 }
}, {multi:true});

db.products.find({
    "size.text": "SELECT Size"
})

*/


text:
from __future__ import absolute_import
import os

# import the settings here to preload the ENV settings
from . import settings as proj_settings

from django.conf import settings

from celery import Celery

try:
    # if available, initialize the newrelic environment
    import newrelic.agent

    config_file = os.environ.get('NEW_RELIC_CONFIG_FILE')
    environment = os.environ.get('NEW_RELIC_ENVIRONMENT')

    newrelic.agent.initialize(config_file, environment)
except ImportError:
    pass

# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
os.environ.setdefault('DJANGO_SETTINGS_MODULE', '{{ project_name }}.settings.development')

app = Celery('{{ project_name }}')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)


text:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace OnlineShop.Entities
{
    public class BestProduct
    {
        [Key, ForeignKey("Product")]
        public int Id { get; set; }

        virtual public Product Product { get; set; }

    }
}


text:
// Copyright 2019 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/certificate_provider/test_certificate_provider_extension.h"

#include <cstdint>
#include <utility>
#include <vector>

#include "base/containers/span.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/numerics/safe_conversions.h"
#include "base/path_service.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_restrictions.h"
#include "base/values.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/api/certificate_provider.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "crypto/rsa_private_key.h"
#include "extensions/browser/api/test/test_api.h"
#include "extensions/browser/event_router.h"
#include "extensions/browser/notification_types.h"
#include "extensions/common/api/test.h"
#include "net/cert/asn1_util.h"
#include "net/cert/x509_certificate.h"
#include "net/cert/x509_util.h"
#include "net/test/cert_test_util.h"
#include "net/test/test_data_directory.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/boringssl/src/include/openssl/rsa.h"
#include "third_party/boringssl/src/include/openssl/ssl.h"

namespace ash {

namespace {

constexpr char kExtensionId[] = "ecmhnokcdiianioonpgakiooenfnonid";
// Paths relative to |chrome::DIR_TEST_DATA|:
constexpr base::FilePath::CharType kExtensionPath[] =
    FILE_PATH_LITERAL("extensions/test_certificate_provider/extension/");
constexpr base::FilePath::CharType kExtensionPemPath[] =
    FILE_PATH_LITERAL("extensions/test_certificate_provider/extension.pem");

// List of algorithms that the extension claims to support for the returned
// certificates.
constexpr extensions::api::certificate_provider::Algorithm
    kSupportedAlgorithms[] = {extensions::api::certificate_provider::Algorithm::
                                  ALGORITHM_RSASSA_PKCS1_V1_5_SHA256,
                              extensions::api::certificate_provider::Algorithm::
                                  ALGORITHM_RSASSA_PKCS1_V1_5_SHA1};

base::Value ConvertBytesToValue(base::span<const uint8_t> bytes) {
  base::Value value(base::Value::Type::LIST);
  for (auto byte : bytes)
    value.Append(byte);
  return value;
}

std::vector<uint8_t> ExtractBytesFromValue(const base::Value& value) {
  std::vector<uint8_t> bytes;
  for (const base::Value& item_value : value.GetList())
    bytes.push_back(base::checked_cast<uint8_t>(item_value.GetInt()));
  return bytes;
}

base::span<const uint8_t> GetCertDer(const net::X509Certificate& certificate) {
  return base::as_bytes(base::make_span(
      net::x509_util::CryptoBufferAsStringPiece(certificate.cert_buffer())));
}

base::Value MakeClientCertificateInfoValue(
    const net::X509Certificate& certificate) {
  base::Value cert_info_value(base::Value::Type::DICTIONARY);
  base::Value certificate_chain(base::Value::Type::LIST);
  certificate_chain.Append(ConvertBytesToValue(GetCertDer(certificate)));
  cert_info_value.SetKey("certificateChain", std::move(certificate_chain));
  base::Value supported_algorithms_value(base::Value::Type::LIST);
  for (auto supported_algorithm : kSupportedAlgorithms) {
    supported_algorithms_value.Append(
        extensions::api::certificate_provider::ToString(supported_algorithm));
  }
  cert_info_value.SetKey("supportedAlgorithms",
                         std::move(supported_algorithms_value));
  return cert_info_value;
}

std::string ConvertValueToJson(const base::Value& value) {
  std::string json;
  CHECK(base::JSONWriter::Write(value, &json));
  return json;
}

base::Value ParseJsonToValue(const std::string& json) {
  absl::optional<base::Value> value = base::JSONReader::Read(json);
  CHECK(value);
  return std::move(*value);
}

bool RsaSignRawData(crypto::RSAPrivateKey* key,
                    uint16_t openssl_signature_algorithm,
                    const std::vector<uint8_t>& input,
                    std::vector<uint8_t>* signature) {
  const EVP_MD* const digest_algorithm =
      SSL_get_signature_algorithm_digest(openssl_signature_algorithm);
  bssl::ScopedEVP_MD_CTX ctx;
  EVP_PKEY_CTX* pkey_ctx = nullptr;
  if (!EVP_DigestSignInit(ctx.get(), &pkey_ctx, digest_algorithm,
                          /*ENGINE* e=*/nullptr, key->key()))
    return false;
  if (SSL_is_signature_algorithm_rsa_pss(openssl_signature_algorithm)) {
    // For RSA-PSS, configure the special padding and set the salt length to be
    // equal to the hash size.
    if (!EVP_PKEY_CTX_set_rsa_padding(pkey_ctx, RSA_PKCS1_PSS_PADDING) ||
        !EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx, /*salt_len=*/-1)) {
      return false;
    }
  }
  size_t sig_len = 0;
  // Determine the signature length for the buffer.
  if (!EVP_DigestSign(ctx.get(), /*out_sig=*/nullptr, &sig_len, input.data(),
                      input.size()))
    return false;
  signature->resize(sig_len);
  return EVP_DigestSign(ctx.get(), signature->data(), &sig_len, input.data(),
                        input.size()) != 0;
}

void SendReplyToJs(ExtensionTestMessageListener* message_listener,
                   const base::Value& response) {
  message_listener->Reply(ConvertValueToJson(response));
  message_listener->Reset();
}

std::unique_ptr<crypto::RSAPrivateKey> LoadPrivateKeyFromFile(
    const base::FilePath& path) {
  std::string key_pk8;
  {
    base::ScopedAllowBlockingForTesting allow_io;
    EXPECT_TRUE(base::ReadFileToString(path, &key_pk8));
  }
  return crypto::RSAPrivateKey::CreateFromPrivateKeyInfo(
      base::as_bytes(base::make_span(key_pk8)));
}

}  // namespace

// static
extensions::ExtensionId TestCertificateProviderExtension::extension_id() {
  return kExtensionId;
}

// static
base::FilePath TestCertificateProviderExtension::GetExtensionSourcePath() {
  return base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
      .Append(kExtensionPath);
}

// static
base::FilePath TestCertificateProviderExtension::GetExtensionPemPath() {
  return base::PathService::CheckedGet(chrome::DIR_TEST_DATA)
      .Append(kExtensionPemPath);
}

// static
scoped_refptr<net::X509Certificate>
TestCertificateProviderExtension::GetCertificate() {
  return net::ImportCertFromFile(net::GetTestCertsDirectory(), "client_1.pem");
}

// static
std::string TestCertificateProviderExtension::GetCertificateSpki() {
  const scoped_refptr<net::X509Certificate> certificate = GetCertificate();
  base::StringPiece spki_bytes;
  if (!net::asn1::ExtractSPKIFromDERCert(
          net::x509_util::CryptoBufferAsStringPiece(certificate->cert_buffer()),
          &spki_bytes)) {
    return {};
  }
  return std::string(spki_bytes);
}

TestCertificateProviderExtension::TestCertificateProviderExtension(
    content::BrowserContext* browser_context)
    : browser_context_(browser_context),
      certificate_(GetCertificate()),
      private_key_(LoadPrivateKeyFromFile(net::GetTestCertsDirectory().Append(
          FILE_PATH_LITERAL("client_1.pk8")))),
      message_listener_(ReplyBehavior::kWillReply) {
  DCHECK(browser_context_);
  CHECK(certificate_);
  CHECK(private_key_);
  // Ignore messages targeted to other extensions or browser contexts.
  message_listener_.set_extension_id(kExtensionId);
  message_listener_.set_browser_context(browser_context);
  message_listener_.SetOnRepeatedlySatisfied(
      base::BindRepeating(&TestCertificateProviderExtension::HandleMessage,
                          base::Unretained(this)));
}

TestCertificateProviderExtension::~TestCertificateProviderExtension() = default;

void TestCertificateProviderExtension::TriggerSetCertificates() {
  base::Value message_data(base::Value::Type::DICTIONARY);
  message_data.SetStringKey("name", "setCertificates");
  base::Value cert_info_values(base::Value::Type::LIST);
  if (should_provide_certificates_)
    cert_info_values.Append(MakeClientCertificateInfoValue(*certificate_));
  message_data.SetKey("certificateInfoList", std::move(cert_info_values));

  base::Value::List message;
  message.Append(std::move(message_data));
  auto event = std::make_unique<extensions::Event>(
      extensions::events::FOR_TEST,
      extensions::api::test::OnMessage::kEventName, std::move(message),
      browser_context_);
  extensions::EventRouter::Get(browser_context_)
      ->DispatchEventToExtension(extension_id(), std::move(event));
}

void TestCertificateProviderExtension::HandleMessage(
    const std::string& message) {
  // Handle the request and reply to it (possibly, asynchronously).
  base::Value message_value = ParseJsonToValue(message);
  CHECK(message_value.is_list());
  base::Value::List& message_list = message_value.GetList();
  CHECK(message_list.size());
  CHECK(message_list[0].is_string());
  const std::string& request_type = message_list[0].GetString();
  ReplyToJsCallback send_reply_to_js_callback =
      base::BindOnce(&SendReplyToJs, &message_listener_);
  if (request_type == "getCertificates") {
    CHECK_EQ(message_list.size(), 1U);
    HandleCertificatesRequest(std::move(send_reply_to_js_callback));
  } else if (request_type == "onSignatureRequested") {
    CHECK_EQ(message_list.size(), 4U);
    HandleSignatureRequest(
        /*sign_request=*/message_list[1],
        /*pin_status=*/message_list[2],
        /*pin=*/message_list[3], std::move(send_reply_to_js_callback));
  } else {
    LOG(FATAL) << "Unexpected JS message type: " << request_type;
  }
}

void TestCertificateProviderExtension::HandleCertificatesRequest(
    ReplyToJsCallback callback) {
  ++certificate_request_count_;
  base::Value cert_info_values(base::Value::Type::LIST);
  if (should_provide_certificates_)
    cert_info_values.Append(MakeClientCertificateInfoValue(*certificate_));
  std::move(callback).Run(cert_info_values);
}

void TestCertificateProviderExtension::HandleSignatureRequest(
    const base::Value& sign_request,
    const base::Value& pin_status,
    const base::Value& pin,
    ReplyToJsCallback callback) {
  CHECK_EQ(*sign_request.FindKey("certificate"),
           ConvertBytesToValue(GetCertDer(*certificate_)));
  const std::string pin_status_string = pin_status.GetString();
  const std::string pin_string = pin.GetString();

  const int sign_request_id = sign_request.FindKey("signRequestId")->GetInt();
  const std::vector<uint8_t> input =
      ExtractBytesFromValue(*sign_request.FindKey("input"));

  const extensions::api::certificate_provider::Algorithm algorithm =
      extensions::api::certificate_provider::ParseAlgorithm(
          sign_request.FindKey("algorithm")->GetString());
  int openssl_signature_algorithm = 0;
  if (algorithm == extensions::api::certificate_provider::Algorithm::
                       ALGORITHM_RSASSA_PKCS1_V1_5_SHA256) {
    openssl_signature_algorithm = SSL_SIGN_RSA_PKCS1_SHA256;
  } else if (algorithm == extensions::api::certificate_provider::Algorithm::
                              ALGORITHM_RSASSA_PKCS1_V1_5_SHA1) {
    openssl_signature_algorithm = SSL_SIGN_RSA_PKCS1_SHA1;
  } else {
    LOG(FATAL) << "Unexpected signature request algorithm: " << algorithm;
  }

  if (should_fail_sign_digest_requests_) {
    // Simulate a failure.
    std::move(callback).Run(/*response=*/base::Value());
    return;
  }

  base::Value response(base::Value::Type::DICTIONARY);
  if (required_pin_.has_value()) {
    if (pin_status_string == "not_requested") {
      // The PIN is required but not specified yet, so request it via the JS
      // side before generating the signature.
      base::Value pin_request_parameters(base::Value::Type::DICTIONARY);
      pin_request_parameters.SetIntKey("signRequestId", sign_request_id);
      if (remaining_pin_attempts_ == 0) {
        pin_request_parameters.SetStringKey("errorType",
                                            "MAX_ATTEMPTS_EXCEEDED");
      }
      response.SetKey("requestPin", std::move(pin_request_parameters));
      std::move(callback).Run(response);
      return;
    }
    if (remaining_pin_attempts_ == 0) {
      // The error about the lockout is already displayed, so fail immediately.
      std::move(callback).Run(/*response=*/base::Value());
      return;
    }
    if (pin_status_string == "canceled" ||
        base::StartsWith(pin_status_string,
                         "failed:", base::CompareCase::SENSITIVE)) {
      // The PIN request failed.
      LOG(WARNING) << "PIN request failed: " << pin_status_string;
      // Respond with a failure.
      std::move(callback).Run(/*response=*/base::Value());
      return;
    }
    DCHECK_EQ(pin_status_string, "ok");
    if (pin_string != *required_pin_) {
      // The entered PIN is wrong, so decrement the remaining attempt count, and
      // update the PIN dialog with displaying an error.
      if (remaining_pin_attempts_ > 0)
        --remaining_pin_attempts_;
      base::Value pin_request_parameters(base::Value::Type::DICTIONARY);
      pin_request_parameters.SetIntKey("signRequestId", sign_request_id);
      pin_request_parameters.SetStringKey(
          "errorType", remaining_pin_attempts_ == 0 ? "MAX_ATTEMPTS_EXCEEDED"
                                                    : "INVALID_PIN");
      if (remaining_pin_attempts_ > 0) {
        pin_request_parameters.SetIntKey("attemptsLeft",
                                         remaining_pin_attempts_);
      }
      response.SetKey("requestPin", std::move(pin_request_parameters));
      std::move(callback).Run(response);
      return;
    }
    // The entered PIN is correct. Stop the PIN request and proceed to
    // generating the signature.
    base::Value stop_pin_request_parameters(base::Value::Type::DICTIONARY);
    stop_pin_request_parameters.SetIntKey("signRequestId", sign_request_id);
    response.SetKey("stopPinRequest", std::move(stop_pin_request_parameters));
  }
  // Generate and return a valid signature.
  std::vector<uint8_t> signature;
  CHECK(RsaSignRawData(private_key_.get(), openssl_signature_algorithm, input,
                       &signature));
  response.SetKey("signature", ConvertBytesToValue(signature));
  std::move(callback).Run(response);
}

}  // namespace ash


text:
using namespace shepherd;

void common::IOUtil::CleanUp(){

}


text:
"""Mathematical formulas relevant to plasma physics."""

__all__ = ["Fermi_integral", "rot_a_to_b"]

import numbers
import numpy as np

from mpmath import polylog
from typing import Union

def Fermi_integral(
    x: Union[float, int, complex, np.ndarray], j: Union[float, int, complex, np.ndarray]
) -> Union[float, complex, np.ndarray]:
    r"""
    Calculate the complete Fermi-Dirac integral.

    Parameters
    ----------
    x : `float`, `int`, `complex`, or `~numpy.ndarray`
        Argument of the Fermi-Dirac integral function.

    j : `float`, `int`, `complex`, or `~numpy.ndarray`
        Order/index of the Fermi-Dirac integral function.

    Returns
    -------
    integral : `float`, `complex`, or `~numpy.ndarray`
        Complete Fermi-Dirac integral for given argument and order.

    Raises
    ------
    `TypeError`
        If the argument is invalid.

    `~astropy.units.UnitsError`
        If the argument is a `~astropy.units.Quantity` but is not
        dimensionless.

    `ValueError`
        If the argument is not entirely finite.

    Notes
    -----
    The `complete Fermi-Dirac integral
    <https://en.wikipedia.org/wiki/Complete_Fermi-Dirac_integral>`_ is
    defined as:

    .. math::
        F_j (x) = \frac{1}{Γ(j+1)} \int_0^∞ \frac{t^j}{\exp{(t-x)} + 1} dt

    for :math:`j > 0`.

    This is equivalent to the following `polylogarithm
    <https://en.wikipedia.org/wiki/Polylogarithm>`_ function:

    .. math::
        F_j (x) = -Li_{j+1}\left(-e^{x}\right)

    Warnings
    --------
    At present this function is limited to relatively small arguments
    due to limitations in ``mpmath.polylog``.

    Examples
    --------
    >>> Fermi_integral(0, 0)
    (0.6931471805599453-0j)
    >>> Fermi_integral(1, 0)
    (1.3132616875182228-0j)
    >>> Fermi_integral(1, 1)
    (1.8062860704447743-0j)
    """
    if isinstance(x, (numbers.Integral, numbers.Real, numbers.Complex)):
        arg = -np.exp(x)
        return -1 * complex(polylog(j + 1, arg))
    elif isinstance(x, np.ndarray):
        integral_arr = np.zeros_like(x, dtype="complex")
        for idx, val in enumerate(x):
            integral_arr[idx] = -1 * complex(polylog(j + 1, -np.exp(val)))
        return integral_arr
    else:
        raise TypeError(f"Improper type {type(x)} given for argument x.")

def rot_a_to_b(a: np.ndarray, b: np.ndarray) -> np.ndarray:
    r"""
    Calculates the 3D rotation matrix that will rotate vector ``a`` to be aligned
    with vector ``b``. The rotation matrix is calculated as follows. Let

    .. math::
        \vec v = \vec a \times \vec b

    and let :math:`\theta` be the angle between :math:`\vec a`
    and :math:`\vec b` such that the projection of :math:`\vec a` along
    :math:`\vec b` is

    .. math::
        c = \vec a \cdot \vec b \cos\theta

    Then the rotation matrix :math:`R` is

    .. math::
        R = I + v_x + v_x^2 \frac{1}{1 + c}

    where :math:`I` is the identity matrix and :math:`v_x` is the
    skew-symmetric cross-product matrix of :math:`v` defined as

    .. math::
        v_x = \begin{bmatrix}
                0 & -v_3 & v_2 \\
                v_3 & 0 & -v_1 \\
                -v_2 & v_1 & 0
            \end{bmatrix}

    Note that this algorithm fails when :math:`1+c=0`, which occurs when :math:`a` and
    :math:`b` are anti-parallel. However, since the correct rotation matrix
    in this case is simply :math:`R=-I`, this function just handles this
    special case explicitly.

    This algorithm is based on
    `this discussion
    <https://math.stackexchange.com/questions/180418/calculate-rotation-matrix-to-align-vector-a-to-vector-b-in-3d/476311#476311>`_
    on StackExchange.

    Parameters
    ----------
    a : `~numpy.ndarray`, shape (3,)
        Vector to be rotated.  Should be a 1D, 3-element unit vector.  If ``a``
        is not normalize, then it will be normalized.

    b : `~numpy.ndarray`, shape (3,)
        Vector representing the desired orientation after rotation.  Should be
        a 1D, 3-element unit vector.  If ``b`` is not normalized, then it will
        be.

    Returns
    -------
    R : `~numpy.ndarray`, shape (3,3)
        The rotation matrix that will rotate vector ``a`` onto vector ``b``.
    """

    # Normalize and validate both vectors

    a = np.squeeze(a)
    if a.shape != (3,):
        raise ValueError(
            f"Argument 'a' must have shape (3,) but input has shape {a.shape}."
        )
    a = a / np.linalg.norm(a)

    b = np.squeeze(b)
    if b.shape != (3,):
        raise ValueError(
            f"Argument 'b' must have shape (3,) but input has shape {b.shape}."
        )
    b = b / np.linalg.norm(b)

    # Manually handle the case where a and b point in opposite directions
    if np.dot(a, b) == -1:
        return -np.identity(3)

    axb = np.cross(a, b)
    c = np.dot(a, b)
    vskew = np.array(
        [[0, -axb[2], axb[1]], [axb[2], 0, -axb[0]], [-axb[1], axb[0], 0]]
    ).T  # Transpose to get right orientation

    return np.identity(3) + vskew + np.dot(vskew, vskew) / (1 + c)


text:
package org.jboss.weld.tests.proxy.weld1052;

import javax.enterprise.context.RequestScoped;

@RequestScoped
public final class Foo implements FooInterface {

}