text:
#include "libavutil/crc.h"
#include "libavutil/opt.h"
#include "libavutil/random_seed.h"
#include "libavcodec/xiph.h"
#include "libavcodec/bytestream.h"
#include "libavcodec/flac.h"
#include "avformat.h"
#include "avio_internal.h"
#include "internal.h"
#include "vorbiscomment.h"

#define MAX_PAGE_SIZE 65025

typedef struct {
    int64_t granule;
    int stream_index;
    uint8_t flags;
    uint8_t segments_count;
    uint8_t segments[255];
    uint8_t data[MAX_PAGE_SIZE];
    uint16_t size;
} OGGPage;

typedef struct {
    unsigned page_counter;
    uint8_t *header[3];
    int header_len[3];
    /** for theora granule */
    int kfgshift;
    int64_t last_kf_pts;
    int vrev;
    int eos;
    unsigned page_count; ///< number of page buffered
    OGGPage page; ///< current page
    unsigned serial_num; ///< serial number
    int64_t last_granule; ///< last packet granule
} OGGStreamContext;

typedef struct OGGPageList {
    OGGPage page;
    struct OGGPageList *next;
} OGGPageList;

typedef struct {
    const AVClass *class;
    OGGPageList *page_list;
    int pref_size; ///< preferred page size (0 => fill all segments)
} OGGContext;

static const AVOption options[] = {
    { "oggpagesize", "Set preferred Ogg page size.",
      offsetof(OGGContext, pref_size), FF_OPT_TYPE_INT, 0, 0, MAX_PAGE_SIZE, AV_OPT_FLAG_ENCODING_PARAM},
    { NULL },
};

static const AVClass ogg_muxer_class = {
    "Ogg muxer",
    av_default_item_name,
    options,
    LIBAVUTIL_VERSION_INT,
};

static void ogg_update_checksum(AVFormatContext *s, AVIOContext *pb, int64_t crc_offset)
{
    int64_t pos = avio_tell(pb);
    uint32_t checksum = ffio_get_checksum(pb);
    avio_seek(pb, crc_offset, SEEK_SET);
    avio_wb32(pb, checksum);
    avio_seek(pb, pos, SEEK_SET);
}

static int ogg_write_page(AVFormatContext *s, OGGPage *page, int extra_flags)
{
    OGGStreamContext *oggstream = s->streams[page->stream_index]->priv_data;
    AVIOContext *pb;
    int64_t crc_offset;
    int ret, size;
    uint8_t *buf;

    ret = avio_open_dyn_buf(&pb);
    if (ret < 0)
        return ret;
    ffio_init_checksum(pb, ff_crc04C11DB7_update, 0);
    ffio_wfourcc(pb, "OggS");
    avio_w8(pb, 0);
    avio_w8(pb, page->flags | extra_flags);
    avio_wl64(pb, page->granule);
    avio_wl32(pb, oggstream->serial_num);
    avio_wl32(pb, oggstream->page_counter++);
    crc_offset = avio_tell(pb);
    avio_wl32(pb, 0); // crc
    avio_w8(pb, page->segments_count);
    avio_write(pb, page->segments, page->segments_count);
    avio_write(pb, page->data, page->size);

    ogg_update_checksum(s, pb, crc_offset);
    avio_flush(pb);

    size = avio_close_dyn_buf(pb, &buf);
    if (size < 0)
        return size;

    avio_write(s->pb, buf, size);
    avio_flush(s->pb);
    av_free(buf);
    oggstream->page_count--;
    return 0;
}

static int64_t ogg_granule_to_timestamp(OGGStreamContext *oggstream, int64_t granule)
{
    if (oggstream->kfgshift)
        return (granule>>oggstream->kfgshift) +
            (granule & ((1<<oggstream->kfgshift)-1));
    else
        return granule;
}

static int ogg_compare_granule(AVFormatContext *s, OGGPage *next, OGGPage *page)
{
    AVStream *st2 = s->streams[next->stream_index];
    AVStream *st  = s->streams[page->stream_index];
    int64_t next_granule, cur_granule;

    if (next->granule == -1 || page->granule == -1)
        return 0;

    next_granule = av_rescale_q(ogg_granule_to_timestamp(st2->priv_data, next->granule),
                                st2->time_base, AV_TIME_BASE_Q);
    cur_granule  = av_rescale_q(ogg_granule_to_timestamp(st->priv_data, page->granule),
                                st ->time_base, AV_TIME_BASE_Q);
    return next_granule > cur_granule;
}

static int ogg_reset_cur_page(OGGStreamContext *oggstream)
{
    oggstream->page.granule = -1;
    oggstream->page.flags = 0;
    oggstream->page.segments_count = 0;
    oggstream->page.size = 0;
    return 0;
}

static int ogg_buffer_page(AVFormatContext *s, OGGStreamContext *oggstream)
{
    OGGContext *ogg = s->priv_data;
    OGGPageList **p = &ogg->page_list;
    OGGPageList *l = av_mallocz(sizeof(*l));

    if (!l)
        return AVERROR(ENOMEM);
    l->page = oggstream->page;

    oggstream->page_count++;
    ogg_reset_cur_page(oggstream);

    while (*p) {
        if (ogg_compare_granule(s, &(*p)->page, &l->page))
            break;
        p = &(*p)->next;
    }
    l->next = *p;
    *p = l;

    return 0;
}

static int ogg_buffer_data(AVFormatContext *s, AVStream *st,
                           uint8_t *data, unsigned size, int64_t granule)
{
    OGGStreamContext *oggstream = st->priv_data;
    OGGContext *ogg = s->priv_data;
    int total_segments = size / 255 + 1;
    uint8_t *p = data;
    int i, segments, len, flush = 0;

    // Handles VFR by flushing page because this frame needs to have a timestamp
    if (st->codec->codec_id == CODEC_ID_THEORA &&
        ogg_granule_to_timestamp(oggstream, granule) >
        ogg_granule_to_timestamp(oggstream, oggstream->last_granule) + 1) {
        if (oggstream->page.granule != -1)
            ogg_buffer_page(s, oggstream);
        flush = 1;
    }

    for (i = 0; i < total_segments; ) {
        OGGPage *page = &oggstream->page;

        segments = FFMIN(total_segments - i, 255 - page->segments_count);

        if (i && !page->segments_count)
            page->flags |= 1; // continued packet

        memset(page->segments+page->segments_count, 255, segments - 1);
        page->segments_count += segments - 1;

        len = FFMIN(size, segments*255);
        page->segments[page->segments_count++] = len - (segments-1)*255;
        memcpy(page->data+page->size, p, len);
        p += len;
        size -= len;
        i += segments;
        page->size += len;

        if (i == total_segments)
            page->granule = granule;

        if(page->segments_count == 255 ||
           (ogg->pref_size > 0 && page->size >= ogg->pref_size)) {
           ogg_buffer_page(s, oggstream);
        }
    }

    if (flush && oggstream->page.granule != -1)
        ogg_buffer_page(s, oggstream);

    return 0;
}

static uint8_t *ogg_write_vorbiscomment(int offset, int bitexact,
                                        int *header_len, AVDictionary **m, int framing_bit)
{
    const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;
    int size;
    uint8_t *p, *p0;
    unsigned int count;

    ff_metadata_conv(m, ff_vorbiscomment_metadata_conv, NULL);

    size = offset + ff_vorbiscomment_length(*m, vendor, &count) + framing_bit;
    p = av_mallocz(size);
    if (!p)
        return NULL;
    p0 = p;

    p += offset;
    ff_vorbiscomment_write(&p, m, vendor, count);
    if (framing_bit)
        bytestream_put_byte(&p, 1);

    *header_len = size;
    return p0;
}

static int ogg_build_flac_headers(AVCodecContext *avctx,
                                  OGGStreamContext *oggstream, int bitexact,
                                  AVDictionary **m)
{
    enum FLACExtradataFormat format;
    uint8_t *streaminfo;
    uint8_t *p;

    if (!ff_flac_is_extradata_valid(avctx, &format, &streaminfo))
        return -1;

    // first packet: STREAMINFO
    oggstream->header_len[0] = 51;
    oggstream->header[0] = av_mallocz(51); // per ogg flac specs
    p = oggstream->header[0];
    if (!p)
        return AVERROR(ENOMEM);
    bytestream_put_byte(&p, 0x7F);
    bytestream_put_buffer(&p, "FLAC", 4);
    bytestream_put_byte(&p, 1); // major version
    bytestream_put_byte(&p, 0); // minor version
    bytestream_put_be16(&p, 1); // headers packets without this one
    bytestream_put_buffer(&p, "fLaC", 4);
    bytestream_put_byte(&p, 0x00); // streaminfo
    bytestream_put_be24(&p, 34);
    bytestream_put_buffer(&p, streaminfo, FLAC_STREAMINFO_SIZE);

    // second packet: VorbisComment
    p = ogg_write_vorbiscomment(4, bitexact, &oggstream->header_len[1], m, 0);
    if (!p)
        return AVERROR(ENOMEM);
    oggstream->header[1] = p;
    bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment
    bytestream_put_be24(&p, oggstream->header_len[1] - 4);

    return 0;
}

#define SPEEX_HEADER_SIZE 80

static int ogg_build_speex_headers(AVCodecContext *avctx,
                                   OGGStreamContext *oggstream, int bitexact,
                                   AVDictionary **m)
{
    uint8_t *p;

    if (avctx->extradata_size < SPEEX_HEADER_SIZE)
        return -1;

    // first packet: Speex header
    p = av_mallocz(SPEEX_HEADER_SIZE);
    if (!p)
        return AVERROR(ENOMEM);
    oggstream->header[0] = p;
    oggstream->header_len[0] = SPEEX_HEADER_SIZE;
    bytestream_put_buffer(&p, avctx->extradata, SPEEX_HEADER_SIZE);
    AV_WL32(&oggstream->header[0][68], 0);  // set extra_headers to 0

    // second packet: VorbisComment
    p = ogg_write_vorbiscomment(0, bitexact, &oggstream->header_len[1], m, 0);
    if (!p)
        return AVERROR(ENOMEM);
    oggstream->header[1] = p;

    return 0;
}

static int ogg_write_header(AVFormatContext *s)
{
    OGGStreamContext *oggstream;
    int i, j;

    for (i = 0; i < s->nb_streams; i++) {
        AVStream *st = s->streams[i];
        unsigned serial_num = i;

        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
            av_set_pts_info(st, 64, 1, st->codec->sample_rate);
        else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)
            av_set_pts_info(st, 64, st->codec->time_base.num, st->codec->time_base.den);
        if (st->codec->codec_id != CODEC_ID_VORBIS &&
            st->codec->codec_id != CODEC_ID_THEORA &&
            st->codec->codec_id != CODEC_ID_SPEEX  &&
            st->codec->codec_id != CODEC_ID_FLAC) {
            av_log(s, AV_LOG_ERROR, "Unsupported codec id in stream %d\n", i);
            return -1;
        }

        if (!st->codec->extradata || !st->codec->extradata_size) {
            av_log(s, AV_LOG_ERROR, "No extradata present\n");
            return -1;
        }
        oggstream = av_mallocz(sizeof(*oggstream));
        oggstream->page.stream_index = i;

        if (!(st->codec->flags & CODEC_FLAG_BITEXACT))
            do {
                serial_num = av_get_random_seed();
                for (j = 0; j < i; j++) {
                    OGGStreamContext *sc = s->streams[j]->priv_data;
                    if (serial_num == sc->serial_num)
                        break;
                }
            } while (j < i);
        oggstream->serial_num = serial_num;

        st->priv_data = oggstream;
        if (st->codec->codec_id == CODEC_ID_FLAC) {
            int err = ogg_build_flac_headers(st->codec, oggstream,
                                             st->codec->flags & CODEC_FLAG_BITEXACT,
                                             &s->metadata);
            if (err) {
                av_log(s, AV_LOG_ERROR, "Error writing FLAC headers\n");
                av_freep(&st->priv_data);
                return err;
            }
        } else if (st->codec->codec_id == CODEC_ID_SPEEX) {
            int err = ogg_build_speex_headers(st->codec, oggstream,
                                              st->codec->flags & CODEC_FLAG_BITEXACT,
                                              &s->metadata);
            if (err) {
                av_log(s, AV_LOG_ERROR, "Error writing Speex headers\n");
                av_freep(&st->priv_data);
                return err;
            }
        } else {
            uint8_t *p;
            const char *cstr = st->codec->codec_id == CODEC_ID_VORBIS ? "vorbis" : "theora";
            int header_type = st->codec->codec_id == CODEC_ID_VORBIS ? 3 : 0x81;
            int framing_bit = st->codec->codec_id == CODEC_ID_VORBIS ? 1 : 0;

            if (ff_split_xiph_headers(st->codec->extradata, st->codec->extradata_size,
                                      st->codec->codec_id == CODEC_ID_VORBIS ? 30 : 42,
                                      oggstream->header, oggstream->header_len) < 0) {
                av_log(s, AV_LOG_ERROR, "Extradata corrupted\n");
                av_freep(&st->priv_data);
                return -1;
            }

            p = ogg_write_vorbiscomment(7, st->codec->flags & CODEC_FLAG_BITEXACT,
                                        &oggstream->header_len[1], &s->metadata,
                                        framing_bit);
            if (!p)
                return AVERROR(ENOMEM);

            oggstream->header[1] = p;
            bytestream_put_byte(&p, header_type);
            bytestream_put_buffer(&p, cstr, 6);

            if (st->codec->codec_id == CODEC_ID_THEORA) {
                /** KFGSHIFT is the width of the less significant section of the granule position
                    The less significant section is the frame count since the last keyframe */
                oggstream->kfgshift = ((oggstream->header[0][40]&3)<<3)|(oggstream->header[0][41]>>5);
                oggstream->vrev = oggstream->header[0][9];
                av_log(s, AV_LOG_DEBUG, "theora kfgshift %d, vrev %d\n",
                       oggstream->kfgshift, oggstream->vrev);
            }
        }
    }

    for (j = 0; j < s->nb_streams; j++) {
        OGGStreamContext *oggstream = s->streams[j]->priv_data;
        ogg_buffer_data(s, s->streams[j], oggstream->header[0],
                        oggstream->header_len[0], 0);
        oggstream->page.flags |= 2; // bos
        ogg_buffer_page(s, oggstream);
    }
    for (j = 0; j < s->nb_streams; j++) {
        AVStream *st = s->streams[j];
        OGGStreamContext *oggstream = st->priv_data;
        for (i = 1; i < 3; i++) {
            if (oggstream && oggstream->header_len[i])
                ogg_buffer_data(s, st, oggstream->header[i],
                                oggstream->header_len[i], 0);
        }
        ogg_buffer_page(s, oggstream);
    }
    return 0;
}

static void ogg_write_pages(AVFormatContext *s, int flush)
{
    OGGContext *ogg = s->priv_data;
    OGGPageList *next, *p;

    if (!ogg->page_list)
        return;

    for (p = ogg->page_list; p; ) {
        OGGStreamContext *oggstream =
            s->streams[p->page.stream_index]->priv_data;
        if (oggstream->page_count < 2 && !flush)
            break;
        ogg_write_page(s, &p->page,
                       flush && oggstream->page_count == 1 ? 4 : 0); // eos
        next = p->next;
        av_freep(&p);
        p = next;
    }
    ogg->page_list = p;
}

static int ogg_write_packet(AVFormatContext *s, AVPacket *pkt)
{
    AVStream *st = s->streams[pkt->stream_index];
    OGGStreamContext *oggstream = st->priv_data;
    int ret;
    int64_t granule;

    if (st->codec->codec_id == CODEC_ID_THEORA) {
        int64_t pts = oggstream->vrev < 1 ? pkt->pts : pkt->pts + pkt->duration;
        int pframe_count;
        if (pkt->flags & AV_PKT_FLAG_KEY)
            oggstream->last_kf_pts = pts;
        pframe_count = pts - oggstream->last_kf_pts;
        // prevent frame count from overflow if key frame flag is not set
        if (pframe_count >= (1<<oggstream->kfgshift)) {
            oggstream->last_kf_pts += pframe_count;
            pframe_count = 0;
        }
        granule = (oggstream->last_kf_pts<<oggstream->kfgshift) | pframe_count;
    } else
        granule = pkt->pts + pkt->duration;

    ret = ogg_buffer_data(s, st, pkt->data, pkt->size, granule);
    if (ret < 0)
        return ret;

    ogg_write_pages(s, 0);

    oggstream->last_granule = granule;

    return 0;
}

static int ogg_write_trailer(AVFormatContext *s)
{
    int i;

    /* flush current page */
    for (i = 0; i < s->nb_streams; i++)
        ogg_buffer_page(s, s->streams[i]->priv_data);

    ogg_write_pages(s, 1);

    for (i = 0; i < s->nb_streams; i++) {
        AVStream *st = s->streams[i];
        OGGStreamContext *oggstream = st->priv_data;
        if (st->codec->codec_id == CODEC_ID_FLAC ||
            st->codec->codec_id == CODEC_ID_SPEEX) {
            av_free(oggstream->header[0]);
            av_free(oggstream->header[1]);
        }
        av_freep(&st->priv_data);
    }
    return 0;
}

AVOutputFormat ff_ogg_muxer = {
    "ogg",
    NULL_IF_CONFIG_SMALL("Ogg"),
    "application/ogg",
    "ogg,ogv,spx",
    sizeof(OGGContext),
    CODEC_ID_FLAC,
    CODEC_ID_THEORA,
    ogg_write_header,
    ogg_write_packet,
    ogg_write_trailer,
    .priv_class = &ogg_muxer_class,
};


text:
"use strict";

// This is an `every` implementation that works for all iterables
module.exports = function every(obj, fn) {
    var pass = true;

    try {
        obj.forEach(function () {
            if (!fn.apply(this, arguments)) {
                // Throwing an error is the only way to break `forEach`
                throw new Error();
            }
        });
    } catch (e) {
        pass = false;
    }

    return pass;
};

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.9.1"/>
<title>ovs all: /home/vladn/git/ovs/include/windows/windefs.h Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

ovs all

Main Page

Related Pages

Namespaces

Data Structures

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

File List

Globals

windefs.h

Go to the documentation of this file.

    1

   16

   17 #ifndef WINDEFS_H

   18 #define WINDEFS_H 1

   19

   20 #include <Winsock2.h>

   21 #include <In6addr.h>

   22 #include <WS2tcpip.h>

   23 #include <windows.h>

   24 #include <BaseTsd.h>

   25 #include <io.h>

   26 #include <inttypes.h>

   27

   28 #pragma comment(lib, "advapi32")

   29

   30 #define inline __inline

   31 #define __func__ __FUNCTION__

   32 #define ssize_t SSIZE_T

   33 #define u_int8_t uint8_t

   34 #define u_int16_t uint16_t

   35 #define u_int32_t uint32_t

   36 #define u_int64_t uint64_t

   37

   38 typedef int pid_t;

   39

   40 char *strsep(char **stringp, const char *delim);

   41

   42 #define srandom srand

   43 #define random rand

   44

   45 #endif /* windefs.h */

strsep

char * strsep(char **stringp, const char *delim)

Definition: strsep.c:46

pid_t

int pid_t

Definition: windefs.h:38

ovs

include

windows

windefs.h

Generated on Wed Sep 9 2015 19:07:23 for ovs all by

     1.8.9.1


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

    <style name="tab_menu_item">
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_weight">1</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:background">@drawable/tab_menu_bg</item>
        <item name="android:button">@null</item>
        <item name="android:gravity">center</item>
        <item name="android:paddingTop">3dp</item>
        <item name="android:textColor">@drawable/tab_menu_text</item>
        <item name="android:textSize">18sp</item>
    </style>

</resources>


text:
"""
Python 2.4 bytecode scanner/deparser

This massages tokenized 2.7 bytecode to make it more amenable for
grammar parsing.
"""

import uncompyle6.scanners.scanner25 as scan

# bytecode verification, verify(), uses JUMP_OPs from here
from xdis.opcodes import opcode_24
JUMP_OPs = opcode_24.JUMP_OPs

# We base this off of 2.5 instead of the other way around
# because we cleaned things up this way.
# The history is that 2.7 support is the cleanest,
# then from that we got 2.6 and so on.
class Scanner24(scan.Scanner25):
    def __init__(self, show_asm=False):
        scan.Scanner25.__init__(self, show_asm)
        # These are the only differences in initialization between
        # 2.4, 2.5 and 2.6
        self.opc = opcode_24
        self.opname = opcode_24.opname
        self.version = 2.4
        self.genexpr_name = '<generator expression>'
        return


text:
from dash import Dash, Input, Output, State, dcc, html

import time
from multiprocessing import Value

from tests.integration.long_callback.utils import get_long_callback_manager

long_callback_manager = get_long_callback_manager()
handle = long_callback_manager.handle

app = Dash(__name__, long_callback_manager=long_callback_manager)
app._cache_key = Value("i", 0)

# Control return value of cache_by function using multiprocessing value
def cache_fn():
    return app._cache_key.value

long_callback_manager.cache_by = [cache_fn]

app.layout = html.Div(
    [
        dcc.Input(id="input1", value="AAA"),
        html.Button(id="run-button1", children="Run"),
        html.Div(id="status1", children="Finished"),
        html.Div(id="result1", children="No results"),
        html.Hr(),
        dcc.Input(id="input2", value="aaa"),
        html.Button(id="run-button2", children="Run"),
        html.Div(id="status2", children="Finished"),
        html.Div(id="result2", children="No results"),
    ]
)

@app.long_callback(
    Output("result1", "children"),
    [Input("run-button1", "n_clicks"), State("input1", "value")],
    progress=Output("status1", "children"),
    progress_default="Finished",
    interval=500,
    cache_args_to_ignore=[0],
)
def update_output1(set_progress, _n_clicks, value):
    for i in range(4):
        set_progress(f"Progress {i}/4")
        time.sleep(2)
    return f"Result for '{value}'"

@app.long_callback(
    Output("result2", "children"),
    dict(button=Input("run-button2", "n_clicks"), value=State("input2", "value")),
    progress=Output("status2", "children"),
    progress_default="Finished",
    interval=500,
    cache_args_to_ignore=["button"],
    prevent_initial_call=True,
)
def update_output2(set_progress, button, value):
    for i in range(4):
        set_progress(f"Progress {i}/4")
        time.sleep(2)
    return f"Result for '{value}'"

if __name__ == "__main__":
    app.run_server(debug=True)


text:
'''
Standalone simple graph structure with the means to compute a longest shortest path.
'''
from misc import pop_next_destination

class Vertex:
    '''
    Vertex

    This class holds all relevant information about a vertex.
    '''

    def __init__(self, name):
        self.name = name
        self.edges_in = []
        self.edges_out = []

    def __str__(self):
        return "Vert({})".format(self.name)

    def __repr__(self):
        return self.__str__()

    def __lt__(self, other):
        return self.name < other.name

    def __gt__(self, other):
        return self.name > other.name

    def __ge__(self, other):
        return self.name >= other.name

    def __le__(self, other):
        return self.name <= other.name

    def add_incoming_edge(self, edge):
        '''
        Add an incoming edge.
        '''
        self.edges_in.append(edge)

    def add_outgoing_edge(self, edge):
        '''
        Add an outgoing adge.
        '''
        self.edges_out.append(edge)

    def get_incoming_edges(self):
        '''
        Return list of incoming edges.
        '''
        return self.edges_in

    def get_outgoing_edges(self):
        '''
        Return list of outgoing edges.
        '''
        return self.edges_out

    def get_name(self):
        '''
        Return name of Vertex
        '''
        return self.name

class Edge:
    '''
    Edge

    This class holds all relevant information about an edge.
    '''

    # source and target are Vertices, w is int
    def __init__(self, source, target, w):
        self.weight = w
        self.source = source
        self.target = target

    def register(self):
        '''
        Register edge to source and target vertices.
        '''
        self.source.add_outgoing_edge(self)
        self.target.add_incoming_edge(self)

    def __str__(self):
        return "Edge[{} => {}, {}]".format(self.source, self.target, self.weight)

    def __repr__(self):
        return self.__str__()

    def get_source(self):
        '''
        Return source of edge.
        '''
        return self.source

    def get_target(self):
        '''
        Return target of edge.
        '''
        return self.target

    def get_weight(self):
        '''
        Return weight of edge.
        '''
        return self.weight

class Graph:
    '''
    Graph

    This class holds all relevant information about a graph.
    '''

    def __init__(self, filename, directed=False):
        self.vertices = []
        self.edges = []
        self.n_vertices = 0
        self.n_edges = 0
        self.init_from_file(filename, directed)

    def __str__(self):
        return "Graph\nVertices: {}\nEdges: {}".format(
            self.vertices, "\n".join(map(lambda e: "\t"+e.__str__(), self.edges)))

    def __repr__(self):
        return self.__str__()

    def reset(self):
        '''
        Reset all information: vertices, edges, n_vertices, n_edges.
        '''
        self.vertices = []
        self.edges = []
        self.n_vertices = 0
        self.n_edges = 0

    def add_edge(self, vert1, vert2, weight):
        '''
        Add an edge to graph.

        Args:
            vert1 (int): source vertex
            vert2 (int): destination vertex
            weight (int): weight of edge.
        '''
        edge = Edge(vert1, vert2, weight)
        edge.register()
        self.edges.append(edge)
        self.n_edges = self.n_edges + 1

    def add_vertex(self, vert):
        '''
        Add a vertex to graph.

        Args:
            vert (int): Vertex name.
        '''
        self.vertices.append(Vertex(vert))
        self.n_vertices = self.n_vertices + 1

    def init_from_file(self, filename, directed=False):
        '''
        Read in a file containing a graph.
        First line contains two numbers: number of vertices, number of edges.
        Then the (weighted) edges are specified linewise: source target weight.

        Args:
            filename (string): name of file
            directed (boolean): default False for undirected graph, True for directed graph.
        '''
        self.reset()

        with open(filename, "r") as infile:
            # assume first line has number of vertices and number of edges
            line = infile.readline()
            info = line.split(" ")

            n_vert = int(info[0])
            #n_edges = int(info[1])

            # assume file contains vertices in range 1 .. n_vertices
            for i in range(n_vert):
                self.add_vertex(i+1)

            # assume file contains lines describing edges in form "vertex1 vertex2 weight"
            for i, line in enumerate(infile):
                info = line.split(" ")

                vert1 = self.vertices[int(info[0])-1]
                vert2 = self.vertices[int(info[1])-1]
                # assume w positive
                weight = int(info[2])

                self.add_edge(vert1, vert2, weight)
                if not directed:
                    self.add_edge(vert2, vert1, weight)

    def get_vertex_by_name(self, vertex):
        '''
        Return the name associated to the vertex.

        Args:
            vertex (string): the name of the vertex.

        Return:
            int: index of vertex with name vertex
        '''
        for vert in self.vertices:
            if vert.get_name() == vertex:
                return vert

    def get_min_unvisited(self, visited, distance):
        '''
        Return an unvisited vertex with current shortest distance amongst all unvisited vertices.

        Args:
            visited (array): an index-based array containing whether or not a vertex has been visited.
            distance (array): an index-based array containing the current shortest distances to a vertex.

        Return:
            int: index of nearest unvisited vertex.
        '''
        mind = -1
        minv = None
        for vert in self.vertices:
            if distance[vert] != -1 and not visited[vert] and (distance[vert] < mind or mind == -1):
                mind = distance[vert]
                minv = vert
        return minv

    def calculate_distances_to(self, vert):
        '''
        Calculate shortest distances to a vertex.

        Args:
            vert (int): Vertex to which the lengths of the shortest paths should be calculated.

        Return:
            array: containing shortest distance to each vertex.
        '''
        distance = {}
        visited = {}
        for vertex in self.vertices:
            distance[vertex] = -1
            visited[vertex] = False
        distance[vert] = 0
        to_visit = set()

        to_visit.add(vert)
        n_next = len(to_visit)
        while n_next != 0:
            curr = pop_next_destination(to_visit, distance)
            visited[curr] = True
            edges = curr.get_incoming_edges()
            for edge in edges:
                neighbor = edge.get_source()
                if not visited[neighbor]:
                    # update distances
                    newdist = distance[curr] + edge.get_weight()
                    if distance[neighbor] == -1 or newdist < distance[neighbor]:
                        distance[neighbor] = newdist
                    to_visit.add(neighbor)
            n_next = len(to_visit)
        return distance

    def get_longest_shortest_to(self, vert):
        '''
        Return the length and start vertex of a shortest path to vert.
        If more than one path hast shortest length, the one with the smallest index is returned.

        Args:
            vert (int): vertex to which a shortest path is being searched.

        Return:
            (int, int): pair of vertex and distance.
        '''
        vert = self.get_vertex_by_name(vert)
        distances = self.calculate_distances_to(vert)
        max_dist = 0
        max_vert = vert
        for vertex in sorted(self.vertices):
            dist = distances[vertex]
            if dist > max_dist:
                max_dist = dist
                max_vert = vertex
        return (max_vert.get_name(), max_dist)


text:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** @author  John Miller
 *  @version 1.3
 *  @date    Sun Sep 22 18:45:44 EDT 2013
 *  @see     LICENSE (MIT style license file).
 */

package scalation.analytics.classifier

import scalation.linalgebra.{MatriD, MatrixD, VectoD, VectorD, VectoI, VectorI}

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `KNN_Classifier` class is used to classify a new vector 'z' into one of
 *  'k' classes.  It works by finding its 'knn' nearest neighbors.  These neighbors
 *  essentially vote according to their classification.  The class with most
 *  votes is selected as the classification of 'z'.  Using a distance metric,
 *  the 'knn' vectors nearest to 'z' are found in the training data, which is
 *  stored row-wise in the data matrix 'x'.  The corresponding classifications
 *  are given in the vector 'y', such that the classification for vector 'x(i)'
 *  is given by 'y(i)'.
 *  @param x    the vectors/points of classified data stored as rows of a matrix
 *  @param y    the classification of each vector in x
 *  @param fn   the names for all features/variables
 *  @param k    the number of classes
 *  @param cn   the names for all classes
 *  @param knn  the number of nearest neighbors to consider
 */
class KNN_Classifier (x: MatriD, y: VectoI, fn: Array [String], k: Int, cn: Array [String], knn: Int = 3)
      extends ClassifierReal (x, y, fn, k, cn)
{
    private val DEBUG      = true                                        // debug flag
    private val MAX_DOUBLE = Double.PositiveInfinity                     // infinity
    private val topK       = Array.ofDim [Tuple2 [Int, Double]] (knn)    // top-knn nearest points (in reserve order)
    private val count      = new VectorI (k)                             // how many nearest neighbors in each class.

    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Compute a distance metric between vectors/points u and v.
     *  @param u  the first vector/point
     *  @param v  the second vector/point
     */
    def distance (u: VectoD, v: VectoD): Double =
    {
        (u - v).normSq       // squared Euclidean norm used for efficiency, may use other norms
    } // distance

    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Find the 'knn' nearest neighbors (top-'knn') to vector 'z' and store in
     *  the 'topK' array.
     *  @param z  the vector to be classified
     */
    def kNearest (z: VectoD)
    {
        var dk = MAX_DOUBLE
        for (i <- 0 until x.dim1) {
            val di = distance (z, x(i))                   // compute distance to z
            if (di < dk) dk = replace (i, di)             // if closer, adjust top-knn
        } // for
        if (DEBUG) println ("topK = " + topK.deep)
    } // kNearest

    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Training involves resetting the data structures before each classification.
     *  It uses lazy training, so most of it is done during classification.
     *  @param testStart  starting index of test region (inclusive) used in cross-validation.
     *  @param testEnd    ending index of test region (exclusive) used in cross-validation.
     */
    def train (testStart: Int, testEnd: Int)    // FIX - use these parameters
    {
        for (i <- 0 until knn) topK(i)  = (-1, MAX_DOUBLE)   // initialize top-knn
        for (j <- 0 until k) count(j) = 0                    // initialize counters
    } // train

    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Given a new point/vector 'z', determine which class it belongs to (i.e.,
     *  the class getting the most votes from its 'knn' nearest neighbors.
     *  Return the best class, its name and its votes
     *  @param z  the vector to classify
     */
    def classify (z: VectoD): (Int, String, Double) =
    {
        kNearest (z)                                         // set top-knn to knn nearest
        for (i <- 0 until knn) count(y(topK(i)._1)) += 1     // tally per class
        println ("count = " + count)
        val best = count.argmax ()                           // class with maximal count
        (best, cn(best), count(best))                        // return the best class, its name and its votes
    } // classify

    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Remove the most distant neighbor and add new neighbor 'i'.  Maintain the
     *  'topK' nearest neighbors in sorted order farthest to nearest.
     */
    private def replace (i: Int, di: Double): Double =
    {
        var j = 0
        while (j < knn-1 && di < topK(j)._2) { topK(j) = topK(j+1); j += 1 }
        topK(j) = (i, di)
        topK(0)._2                      // the distance of the new farthest neighbor
    } // replace

    //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Reset or re-initialize the frequency tables and the probability tables.
     */
    def reset ()
    {
        // FIX: to be implemented
    } // reset

} // KNN_Classifier class

//:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `KNN_ClassifierTest` object is used to test the `KNN_Classifier` class.
 */
object KNN_ClassifierTest extends App
{
    val x = new MatrixD ((6, 2), 1.0, 2.0,      // data/feature matrix
                                 2.0, 1.0,
                                 5.0, 4.0,
                                 4.0, 5.0,
                                 9.0, 8.0,
                                 8.0, 9.0)
    val y  = VectorI (0, 0, 0, 1, 1, 1)         // classification for each vector in x
    val fn = Array ("x1", "x2")                 // feature/variable names
    val cn = Array ("No", "Yes")                // class names

    println ("----------------------------------------------------")
    println ("x = " + x)
    println ("y = " + y)
    val cl = new KNN_Classifier (x, y, fn, 2, cn)

    cl.train ()
    val z1 = VectorD (10.0, 10.0)
    println ("----------------------------------------------------")
    println ("z1 = " + z1)
    println ("class = " + cl.classify (z1))

    cl.train ()
    val z2 = VectorD ( 3.0,  3.0)
    println ("----------------------------------------------------")
    println ("z2 = " + z2)
    println ("class = " + cl.classify (z2))

} // KNN_ClassifierTest object


text:
package worker

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"
	nethttp "net/http"
	"runtime"
	"strings"
	"time"

	"github.com/containerd/containerd/content"
	"github.com/containerd/containerd/images"
	"github.com/containerd/containerd/platforms"
	"github.com/containerd/containerd/rootfs"
	"github.com/docker/docker/distribution"
	distmetadata "github.com/docker/docker/distribution/metadata"
	"github.com/docker/docker/distribution/xfer"
	"github.com/docker/docker/image"
	"github.com/docker/docker/layer"
	pkgprogress "github.com/docker/docker/pkg/progress"
	"github.com/moby/buildkit/cache"
	"github.com/moby/buildkit/cache/metadata"
	"github.com/moby/buildkit/client"
	"github.com/moby/buildkit/executor"
	"github.com/moby/buildkit/exporter"
	localexporter "github.com/moby/buildkit/exporter/local"
	tarexporter "github.com/moby/buildkit/exporter/tar"
	"github.com/moby/buildkit/frontend"
	gw "github.com/moby/buildkit/frontend/gateway/client"
	"github.com/moby/buildkit/session"
	"github.com/moby/buildkit/snapshot"
	"github.com/moby/buildkit/solver"
	"github.com/moby/buildkit/solver/llbsolver/ops"
	"github.com/moby/buildkit/solver/pb"
	"github.com/moby/buildkit/source"
	"github.com/moby/buildkit/source/git"
	"github.com/moby/buildkit/source/http"
	"github.com/moby/buildkit/source/local"
	"github.com/moby/buildkit/util/contentutil"
	"github.com/moby/buildkit/util/progress"
	digest "github.com/opencontainers/go-digest"
	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	bolt "go.etcd.io/bbolt"
)

const labelCreatedAt = "buildkit/createdat"

// LayerAccess provides access to a moby layer from a snapshot
type LayerAccess interface {
	GetDiffIDs(ctx context.Context, key string) ([]layer.DiffID, error)
	EnsureLayer(ctx context.Context, key string) ([]layer.DiffID, error)
}

// Opt defines a structure for creating a worker.
type Opt struct {
	ID                string
	Labels            map[string]string
	GCPolicy          []client.PruneInfo
	MetadataStore     *metadata.Store
	Executor          executor.Executor
	Snapshotter       snapshot.Snapshotter
	ContentStore      content.Store
	CacheManager      cache.Manager
	ImageSource       source.Source
	DownloadManager   distribution.RootFSDownloadManager
	V2MetadataService distmetadata.V2MetadataService
	Transport         nethttp.RoundTripper
	Exporter          exporter.Exporter
	Layers            LayerAccess
	Platforms         []ocispec.Platform
}

// Worker is a local worker instance with dedicated snapshotter, cache, and so on.
// TODO: s/Worker/OpWorker/g ?
type Worker struct {
	Opt
	SourceManager *source.Manager
}

// NewWorker instantiates a local worker
func NewWorker(opt Opt) (*Worker, error) {
	sm, err := source.NewManager()
	if err != nil {
		return nil, err
	}

	cm := opt.CacheManager
	sm.Register(opt.ImageSource)

	gs, err := git.NewSource(git.Opt{
		CacheAccessor: cm,
		MetadataStore: opt.MetadataStore,
	})
	if err == nil {
		sm.Register(gs)
	} else {
		logrus.Warnf("Could not register builder git source: %s", err)
	}

	hs, err := http.NewSource(http.Opt{
		CacheAccessor: cm,
		MetadataStore: opt.MetadataStore,
		Transport:     opt.Transport,
	})
	if err == nil {
		sm.Register(hs)
	} else {
		logrus.Warnf("Could not register builder http source: %s", err)
	}

	ss, err := local.NewSource(local.Opt{
		CacheAccessor: cm,
		MetadataStore: opt.MetadataStore,
	})
	if err == nil {
		sm.Register(ss)
	} else {
		logrus.Warnf("Could not register builder local source: %s", err)
	}

	return &Worker{
		Opt:           opt,
		SourceManager: sm,
	}, nil
}

// ID returns worker ID
func (w *Worker) ID() string {
	return w.Opt.ID
}

// Labels returns map of all worker labels
func (w *Worker) Labels() map[string]string {
	return w.Opt.Labels
}

// Platforms returns one or more platforms supported by the image.
func (w *Worker) Platforms() []ocispec.Platform {
	if len(w.Opt.Platforms) == 0 {
		return []ocispec.Platform{platforms.DefaultSpec()}
	}
	return w.Opt.Platforms
}

// GCPolicy returns automatic GC Policy
func (w *Worker) GCPolicy() []client.PruneInfo {
	return w.Opt.GCPolicy
}

// LoadRef loads a reference by ID
func (w *Worker) LoadRef(id string, hidden bool) (cache.ImmutableRef, error) {
	var opts []cache.RefOption
	if hidden {
		opts = append(opts, cache.NoUpdateLastUsed)
	}
	return w.CacheManager.Get(context.TODO(), id, opts...)
}

// ResolveOp converts a LLB vertex into a LLB operation
func (w *Worker) ResolveOp(v solver.Vertex, s frontend.FrontendLLBBridge, sm *session.Manager) (solver.Op, error) {
	if baseOp, ok := v.Sys().(*pb.Op); ok {
		switch op := baseOp.Op.(type) {
		case *pb.Op_Source:
			return ops.NewSourceOp(v, op, baseOp.Platform, w.SourceManager, sm, w)
		case *pb.Op_Exec:
			return ops.NewExecOp(v, op, baseOp.Platform, w.CacheManager, sm, w.MetadataStore, w.Executor, w)
		case *pb.Op_File:
			return ops.NewFileOp(v, op, w.CacheManager, w.MetadataStore, w)
		case *pb.Op_Build:
			return ops.NewBuildOp(v, op, s, w)
		}
	}
	return nil, errors.Errorf("could not resolve %v", v)
}

// ResolveImageConfig returns image config for an image
func (w *Worker) ResolveImageConfig(ctx context.Context, ref string, opt gw.ResolveImageConfigOpt, sm *session.Manager) (digest.Digest, []byte, error) {
	// ImageSource is typically source/containerimage
	resolveImageConfig, ok := w.ImageSource.(resolveImageConfig)
	if !ok {
		return "", nil, errors.Errorf("worker %q does not implement ResolveImageConfig", w.ID())
	}
	return resolveImageConfig.ResolveImageConfig(ctx, ref, opt, sm)
}

// Exec executes a process directly on a worker
func (w *Worker) Exec(ctx context.Context, meta executor.Meta, rootFS cache.ImmutableRef, stdin io.ReadCloser, stdout, stderr io.WriteCloser) error {
	active, err := w.CacheManager.New(ctx, rootFS)
	if err != nil {
		return err
	}
	defer active.Release(context.TODO())
	return w.Executor.Exec(ctx, meta, active, nil, stdin, stdout, stderr)
}

// DiskUsage returns disk usage report
func (w *Worker) DiskUsage(ctx context.Context, opt client.DiskUsageInfo) ([]*client.UsageInfo, error) {
	return w.CacheManager.DiskUsage(ctx, opt)
}

// Prune deletes reclaimable build cache
func (w *Worker) Prune(ctx context.Context, ch chan client.UsageInfo, info ...client.PruneInfo) error {
	return w.CacheManager.Prune(ctx, ch, info...)
}

// Exporter returns exporter by name
func (w *Worker) Exporter(name string, sm *session.Manager) (exporter.Exporter, error) {
	switch name {
	case "moby":
		return w.Opt.Exporter, nil
	case client.ExporterLocal:
		return localexporter.New(localexporter.Opt{
			SessionManager: sm,
		})
	case client.ExporterTar:
		return tarexporter.New(tarexporter.Opt{
			SessionManager: sm,
		})
	default:
		return nil, errors.Errorf("exporter %q could not be found", name)
	}
}

// GetRemote returns a remote snapshot reference for a local one
func (w *Worker) GetRemote(ctx context.Context, ref cache.ImmutableRef, createIfNeeded bool) (*solver.Remote, error) {
	var diffIDs []layer.DiffID
	var err error
	if !createIfNeeded {
		diffIDs, err = w.Layers.GetDiffIDs(ctx, ref.ID())
		if err != nil {
			return nil, err
		}
	} else {
		if err := ref.Finalize(ctx, true); err != nil {
			return nil, err
		}
		diffIDs, err = w.Layers.EnsureLayer(ctx, ref.ID())
		if err != nil {
			return nil, err
		}
	}

	descriptors := make([]ocispec.Descriptor, len(diffIDs))
	for i, dgst := range diffIDs {
		descriptors[i] = ocispec.Descriptor{
			MediaType: images.MediaTypeDockerSchema2Layer,
			Digest:    digest.Digest(dgst),
			Size:      -1,
		}
	}

	return &solver.Remote{
		Descriptors: descriptors,
		Provider:    &emptyProvider{},
	}, nil
}

// PruneCacheMounts removes the current cache snapshots for specified IDs
func (w *Worker) PruneCacheMounts(ctx context.Context, ids []string) error {
	mu := ops.CacheMountsLocker()
	mu.Lock()
	defer mu.Unlock()

	for _, id := range ids {
		id = "cache-dir:" + id
		sis, err := w.MetadataStore.Search(id)
		if err != nil {
			return err
		}
		for _, si := range sis {
			for _, k := range si.Indexes() {
				if k == id || strings.HasPrefix(k, id+":") {
					if siCached := w.CacheManager.Metadata(si.ID()); siCached != nil {
						si = siCached
					}
					if err := cache.CachePolicyDefault(si); err != nil {
						return err
					}
					si.Queue(func(b *bolt.Bucket) error {
						return si.SetValue(b, k, nil)
					})
					if err := si.Commit(); err != nil {
						return err
					}
					// if ref is unused try to clean it up right away by releasing it
					if mref, err := w.CacheManager.GetMutable(ctx, si.ID()); err == nil {
						go mref.Release(context.TODO())
					}
					break
				}
			}
		}
	}

	ops.ClearActiveCacheMounts()
	return nil
}

// FromRemote converts a remote snapshot reference to a local one
func (w *Worker) FromRemote(ctx context.Context, remote *solver.Remote) (cache.ImmutableRef, error) {
	rootfs, err := getLayers(ctx, remote.Descriptors)
	if err != nil {
		return nil, err
	}

	layers := make([]xfer.DownloadDescriptor, 0, len(rootfs))

	for _, l := range rootfs {
		// ongoing.add(desc)
		layers = append(layers, &layerDescriptor{
			desc:     l.Blob,
			diffID:   layer.DiffID(l.Diff.Digest),
			provider: remote.Provider,
			w:        w,
			pctx:     ctx,
		})
	}

	defer func() {
		for _, l := range rootfs {
			w.ContentStore.Delete(context.TODO(), l.Blob.Digest)
		}
	}()

	r := image.NewRootFS()
	rootFS, release, err := w.DownloadManager.Download(ctx, *r, runtime.GOOS, layers, &discardProgress{})
	if err != nil {
		return nil, err
	}
	defer release()

	if len(rootFS.DiffIDs) != len(layers) {
		return nil, errors.Errorf("invalid layer count mismatch %d vs %d", len(rootFS.DiffIDs), len(layers))
	}

	for i := range rootFS.DiffIDs {
		tm := time.Now()
		if tmstr, ok := remote.Descriptors[i].Annotations[labelCreatedAt]; ok {
			if err := (&tm).UnmarshalText([]byte(tmstr)); err != nil {
				return nil, err
			}
		}
		descr := fmt.Sprintf("imported %s", remote.Descriptors[i].Digest)
		if v, ok := remote.Descriptors[i].Annotations["buildkit/description"]; ok {
			descr = v
		}
		ref, err := w.CacheManager.GetFromSnapshotter(ctx, string(layer.CreateChainID(rootFS.DiffIDs[:i+1])), cache.WithDescription(descr), cache.WithCreationTime(tm))
		if err != nil {
			return nil, err
		}
		if i == len(remote.Descriptors)-1 {
			return ref, nil
		}
		defer ref.Release(context.TODO())
	}

	return nil, errors.Errorf("unreachable")
}

type discardProgress struct{}

func (*discardProgress) WriteProgress(_ pkgprogress.Progress) error {
	return nil
}

// Fetch(ctx context.Context, desc ocispec.Descriptor) (io.ReadCloser, error)
type layerDescriptor struct {
	provider content.Provider
	desc     ocispec.Descriptor
	diffID   layer.DiffID
	// ref      ctdreference.Spec
	w    *Worker
	pctx context.Context
}

func (ld *layerDescriptor) Key() string {
	return "v2:" + ld.desc.Digest.String()
}

func (ld *layerDescriptor) ID() string {
	return ld.desc.Digest.String()
}

func (ld *layerDescriptor) DiffID() (layer.DiffID, error) {
	return ld.diffID, nil
}

func (ld *layerDescriptor) Download(ctx context.Context, progressOutput pkgprogress.Output) (io.ReadCloser, int64, error) {
	done := oneOffProgress(ld.pctx, fmt.Sprintf("pulling %s", ld.desc.Digest))
	if err := contentutil.Copy(ctx, ld.w.ContentStore, ld.provider, ld.desc); err != nil {
		return nil, 0, done(err)
	}
	done(nil)

	ra, err := ld.w.ContentStore.ReaderAt(ctx, ld.desc)
	if err != nil {
		return nil, 0, err
	}

	return ioutil.NopCloser(content.NewReader(ra)), ld.desc.Size, nil
}

func (ld *layerDescriptor) Close() {
	// ld.is.ContentStore.Delete(context.TODO(), ld.desc.Digest)
}

func (ld *layerDescriptor) Registered(diffID layer.DiffID) {
	// Cache mapping from this layer's DiffID to the blobsum
	ld.w.V2MetadataService.Add(diffID, distmetadata.V2Metadata{Digest: ld.desc.Digest})
}

func getLayers(ctx context.Context, descs []ocispec.Descriptor) ([]rootfs.Layer, error) {
	layers := make([]rootfs.Layer, len(descs))
	for i, desc := range descs {
		diffIDStr := desc.Annotations["containerd.io/uncompressed"]
		if diffIDStr == "" {
			return nil, errors.Errorf("%s missing uncompressed digest", desc.Digest)
		}
		diffID, err := digest.Parse(diffIDStr)
		if err != nil {
			return nil, err
		}
		layers[i].Diff = ocispec.Descriptor{
			MediaType: ocispec.MediaTypeImageLayer,
			Digest:    diffID,
		}
		layers[i].Blob = ocispec.Descriptor{
			MediaType: desc.MediaType,
			Digest:    desc.Digest,
			Size:      desc.Size,
		}
	}
	return layers, nil
}

func oneOffProgress(ctx context.Context, id string) func(err error) error {
	pw, _, _ := progress.FromContext(ctx)
	now := time.Now()
	st := progress.Status{
		Started: &now,
	}
	pw.Write(id, st)
	return func(err error) error {
		// TODO: set error on status
		now := time.Now()
		st.Completed = &now
		pw.Write(id, st)
		pw.Close()
		return err
	}
}

type resolveImageConfig interface {
	ResolveImageConfig(ctx context.Context, ref string, opt gw.ResolveImageConfigOpt, sm *session.Manager) (digest.Digest, []byte, error)
}

type emptyProvider struct {
}

func (p *emptyProvider) ReaderAt(ctx context.Context, dec ocispec.Descriptor) (content.ReaderAt, error) {
	return nil, errors.Errorf("ReaderAt not implemented for empty provider")
}


text:
from django.conf import settings
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^', include('authactions.urls', namespace='auth')),
    url(r'^', include('blog.urls', namespace='blog')),
    url(r'^', include('profile.urls', namespace='profile')),
)

if settings.DEBUG:
    urlpatterns += patterns('django.contrib.staticfiles.views',
                            url(r'^static/(?P<path>.*)$', 'serve'),)


text:
package bgames.stack;

import bgames.World;
import bgames.thing.ThingTrie;

public class OutsideWorld {
  private final World world;
  private ThingTrie things;

  public OutsideWorld(World world) {
    this.world = world;
    this.things = world.getThings();
  }

  public World getWorld() {
    return world;
  }
  public ThingTrie getThings() {
    return things;
  }
  public void setThings(ThingTrie things) {
    this.things = things;
  }
}


text:
<!DOCTYPE html>

  <title>KillCheck</title>

KillCheck

<?php
require_once(__DIR__ . "/../resources/classes/util.php");
require_once(__DIR__ . "/../resources/classes/cache.php");
require_once(__DIR__ . "/../resources/classes/universe.php");

if (
  isset($_GET["alliance"])
  && isset($_GET["blues"])
){
  $cfg = (object)[
    'alliance' => $_GET["alliance"],
    'blues' => explode(PHP_EOL, $_GET['blues'])
  ];
  $killCheck = new KillCheck($cfg);
  ?>

<?=strval($killCheck->getLossCount())?> of your last 1000 losses have been to listed entities.

<?=strval($killCheck->getKillCount())?> of your last 1000 kills have been of listed entities.

  <?php
  foreach ($killCheck->getBlues() as $name => $blue) {
    echo ('
'.$name.' ('.$blue->type.')
');
    if (count($blue->killmails)>0){
      ?>

            Victim
            Attackers
            Location
            Timestamp

        <?php
          foreach ($blue->killmails as $killmailIndex => $killmail) {
            ?>

              <?=outputPlayer($killmail->victim)?>
              <?php
                $attackerStr = [];
                foreach ($killmail->attackers as $attackerIndex => $attacker) {
                  array_push($attackerStr, outputPlayer($attacker));
                }
                echo (implode('
', $attackerStr));
              ?>
              <?=$killmail->system?>
              <a href="https://zkillboard.com/kill/<?=$killmail->killID?>/" target="_blank">
                <?=$killmail->killTime?>

            <?php
          }
        ?>

      <?php
    }
  }
}
else {
 ?>
  <form action="" method="get" enctype="multipart/form-data">

Check to see if you've been in fights with would-be-blues (or actual blues) in your last 1000 kills and last 1000 losses.

Your Alliance:
<input type="text" name="alliance"/>

Line separated blues list:
<textarea name= "blues"></textarea>

    <input type="submit" value="Submit">
  </form>
<?php
}

function outputPlayer($player){
  return $player->player . ' (' . $player->corp . ') ['. $player->alliance .']';
}

class KillCheck {
  public function __construct($cfg){
    $this->killIDs = [];
    $this->lossIDs = [];
    $this->util = new Util();
    $this->universe = new Universe();
    $this->cache = new FileCache('killcheck/'.urlencode($cfg->alliance).'.json');
    $data = $this->cache->get();

    if (isset($data->alliance->name) && $data->alliance->name == $cfg->alliance){
      $this->alliance  = $data->alliance;
    }
    else {
      $this->alliance = $this->getEntityByName($cfg->alliance);
    }

    $this->losses = $this->getKills($this->alliance, 'losses', 5);
    $this->kills = $this->getKills($this->alliance, 'kills', 5);

    $this->blues = (object)[];
    $this->nulls = [];
    foreach ($cfg->blues as $index => $name) {
      $name = trim($name);
      if (isset($data->blues->$name->id)){
        $this->blues->$name = $data->blues->$name;
      }
      else {
        $entity = $this->getEntityByName($name);
        if (is_null($entity)){
          array_push($this->nulls, $name);
          continue;
        }
        else {
          $this->blues->$name = $entity;
        }
      }
      $this->blues->$name->killmails = [];
      $this->blues->$name->killmails = $this->searchKillMails($this->blues->$name);
    };

    $this->cache->set((object)[
      'alliance' => $this->alliance,
      'blues' => $this->blues,
      'nulls' => $this->nulls
    ]);
  }

  public function getKillCount(){
    return count($this->killIDs);
  }

  public function getLossCount(){
    return count($this->lossIDs);
  }

  public function getAlliance(){
    return $this->alliance;
  }

  public function getBlues(){
    return $this->blues;
  }

  private function getKills($entity, $type, $pages){
    $kills = [];
    for ($i=1; $i <= $pages; $i++) {
      $kills = array_merge($kills, $this->getKillsPage($entity, $type, $i));
    }
    return $kills;
  }

  private function getKillsPage($entity, $type, $page){
    $kills =  $this->util->requestAndRetry(
      'https://zkillboard.com/api/'.$type.'/'. $entity->type .'ID/'.$entity->id
        .'/page/'.strval($page).'/',
      (object)[]
    );
    return $kills;
  }

  private function searchKillMails($entity){
    $killmails = [];

    $prop = $entity->type .'ID';
    foreach ($this->losses as $lossIndex => $kill) {
      foreach ($kill->attackers as $index => $attacker) {
        if ($attacker->$prop == $entity->id) {
          array_push($killmails, $this->shortKill($kill));
          $this->lossIDs[$kill->killID] = true;
          break;
        }
      }
    }
    foreach ($this->kills as $killIndex => $kill) {
      if ($kill->victim->$prop == $entity->id) {
        array_push($killmails, $this->shortKill($kill));
        $this->killIDs[$kill->killID] = true;
      }
    }
    return $killmails;
  }

  private function shortKill($kill){

     $shortkill = (object)[
      'killID' => $kill->killID,
      'killTime' => $kill->killTime,
      'system' => $this->universe->getSystemById($kill->solarSystemID)->name,
      'value' => $kill->zkb->totalValue,
      'victim' => (object)[
        'player' => $kill->victim->characterName,
        'corp' => $kill->victim->corporationName,
        'alliance' => $kill->victim->allianceName,
      ],
      'attackers' => []
    ];

    foreach ($kill->attackers as $index => $attacker) {
      array_push($shortkill->attackers, (object)[
        'player' => $attacker->characterName,
        'corp' => $attacker->corporationName,
        'alliance' => $attacker->allianceName,
      ]);
    }

    return $shortkill;
  }

  private function getEntityByName($name){
    $id = null;
    $response = $this->util->requestAndRetry(
      'https://esi.tech.ccp.is/latest/search/?categories=alliance&datasource=tranquility&language=en-us&strict=false&search=' . urlencode($name),
      (object)[]
    );
    if (isset($response->alliance)){
      return (object)[
        'id' => $response->alliance[0],
        'type' => 'alliance'
      ];
    }

    $response = $this->util->requestAndRetry(
      'https://esi.tech.ccp.is/latest/search/?categories=corporation&datasource=tranquility&language=en-us&strict=false&search=' . urlencode($name),
      (object)[]
    );
    if (isset($response->corporation)){
      return (object)[
        'id' => $response->corporation[0],
        'type' => 'corporation'
      ];
    }

    $response = $this->util->requestAndRetry(
      'https://esi.tech.ccp.is/latest/search/?categories=character&datasource=tranquility&language=en-us&strict=false&search=' . urlencode($name),
      (object)[]
    );
    if (isset($response->character)){
      return (object)[
        'id' => $response->character[0],
        'type' => 'character'
      ];
    }

    return null;
  }

}
?>


text:
import os
from tools.td_tools import Teradata
from tools import JsonConf

root_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
conf = JsonConf().get_json_conf(path= root_path + '/conf.json')
conf_td = conf['teradata']

tera = Teradata(host=conf_td['jackal_host'], user_name=conf_td['username'], password=conf_td['password'])
df = tera.query(query_string='''select * from pp_oap_sing_jyang2_t.test;''')
print(df)


text:
namespace Cradle.Editor.ThirdParty.FullSerializer {
    /// <summary>
    /// Controls how the reflected converter handles member serialization.
    /// </summary>
    public enum fsMemberSerialization {
        /// <summary>
        /// Only members with [SerializeField] or [fsProperty] attributes are serialized.
        /// </summary>
        OptIn,

        /// <summary>
        /// Only members with [NotSerialized] or [fsIgnore] will not be serialized.
        /// </summary>
        OptOut,

        /// <summary>
        /// The default member serialization behavior is applied.
        /// </summary>
        Default
    }
}


text:
pref("extensions.spamness.header", "x-spam-status");
pref("extensions.spamness.display.column", 0);
pref("extensions.spamness.display.messageScore", true);
pref("extensions.spamness.display.messageRules", false);
pref("extensions.spamness.version", "0.6");
pref("extensions.spamness.isDefaultColumn", true);
pref("extensions.spamness.installationGreeting", true);
pref("extensions.spamness.openRuleLinkLocally", true);


text:
/* $Id$ */

#include "zend.h"
#include "zend_globals.h"
#include "zend_variables.h"
#include "zend_API.h"
#include "zend_objects_API.h"

#define ZEND_DEBUG_OBJECTS 0

ZEND_API void zend_objects_store_init(zend_objects_store *objects, zend_uint init_size)
{
	objects->object_buckets = (zend_object_store_bucket *) emalloc(init_size * sizeof(zend_object_store_bucket));
	objects->top = 1; /* Skip 0 so that handles are true */
	objects->size = init_size;
	objects->free_list_head = -1;
	memset(&objects->object_buckets[0], 0, sizeof(zend_object_store_bucket));
}

ZEND_API void zend_objects_store_destroy(zend_objects_store *objects)
{
	efree(objects->object_buckets);
	objects->object_buckets = NULL;
}

ZEND_API void zend_objects_store_call_destructors(zend_objects_store *objects TSRMLS_DC)
{
	zend_uint i = 1;

	for (i = 1; i < objects->top ; i++) {
		if (objects->object_buckets[i].valid) {
			struct _store_object *obj = &objects->object_buckets[i].bucket.obj;

			if (!objects->object_buckets[i].destructor_called) {
				objects->object_buckets[i].destructor_called = 1;
				if (obj->dtor && obj->object) {
					obj->refcount++;
					obj->dtor(obj->object, i TSRMLS_CC);
					obj = &objects->object_buckets[i].bucket.obj;
					obj->refcount--;

					if (obj->refcount == 0) {
						/* in case gc_collect_cycle is triggered before free_storage */
						GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
					}
				}
			}
		}
	}
}

ZEND_API void zend_objects_store_mark_destructed(zend_objects_store *objects TSRMLS_DC)
{
	zend_uint i;

	if (!objects->object_buckets) {
		return;
	}
	for (i = 1; i < objects->top ; i++) {
		if (objects->object_buckets[i].valid) {
			objects->object_buckets[i].destructor_called = 1;
		}
	}
}

ZEND_API void zend_objects_store_free_object_storage(zend_objects_store *objects TSRMLS_DC)
{
	zend_uint i = 1;

	for (i = 1; i < objects->top ; i++) {
		if (objects->object_buckets[i].valid) {
			struct _store_object *obj = &objects->object_buckets[i].bucket.obj;

			GC_REMOVE_ZOBJ_FROM_BUFFER(obj);

			objects->object_buckets[i].valid = 0;
			if (obj->free_storage) {
				obj->free_storage(obj->object TSRMLS_CC);
			}
			/* Not adding to free list as we are shutting down anyway */
		}
	}
}

/* Store objects API */

ZEND_API zend_object_handle zend_objects_store_put(void *object, zend_objects_store_dtor_t dtor, zend_objects_free_object_storage_t free_storage, zend_objects_store_clone_t clone TSRMLS_DC)
{
	zend_object_handle handle;
	struct _store_object *obj;

	if (EG(objects_store).free_list_head != -1) {
		handle = EG(objects_store).free_list_head;
		EG(objects_store).free_list_head = EG(objects_store).object_buckets[handle].bucket.free_list.next;
	} else {
		if (EG(objects_store).top == EG(objects_store).size) {
			EG(objects_store).size <<= 1;
			EG(objects_store).object_buckets = (zend_object_store_bucket *) erealloc(EG(objects_store).object_buckets, EG(objects_store).size * sizeof(zend_object_store_bucket));
		}
		handle = EG(objects_store).top++;
	}
	obj = &EG(objects_store).object_buckets[handle].bucket.obj;
	EG(objects_store).object_buckets[handle].destructor_called = 0;
	EG(objects_store).object_buckets[handle].valid = 1;
	EG(objects_store).object_buckets[handle].apply_count = 0;

	obj->refcount = 1;
	GC_OBJ_INIT(obj);
	obj->object = object;
	obj->dtor = dtor?dtor:(zend_objects_store_dtor_t)zend_objects_destroy_object;
	obj->free_storage = free_storage;
	obj->clone = clone;
	obj->handlers = NULL;

#if ZEND_DEBUG_OBJECTS
	fprintf(stderr, "Allocated object id #%d\n", handle);
#endif
	return handle;
}

ZEND_API zend_uint zend_objects_store_get_refcount(zval *object TSRMLS_DC)
{
	zend_object_handle handle = Z_OBJ_HANDLE_P(object);

	return EG(objects_store).object_buckets[handle].bucket.obj.refcount;
}

ZEND_API void zend_objects_store_add_ref(zval *object TSRMLS_DC)
{
	zend_object_handle handle = Z_OBJ_HANDLE_P(object);

	EG(objects_store).object_buckets[handle].bucket.obj.refcount++;
#if ZEND_DEBUG_OBJECTS
	fprintf(stderr, "Increased refcount of object id #%d\n", handle);
#endif
}

/*
 * Add a reference to an objects store entry given the object handle.
 */
ZEND_API void zend_objects_store_add_ref_by_handle(zend_object_handle handle TSRMLS_DC)
{
	EG(objects_store).object_buckets[handle].bucket.obj.refcount++;
}

#define ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST()																	\
			EG(objects_store).object_buckets[handle].bucket.free_list.next = EG(objects_store).free_list_head;	\
			EG(objects_store).free_list_head = handle;															\
			EG(objects_store).object_buckets[handle].valid = 0;

ZEND_API void zend_objects_store_del_ref(zval *zobject TSRMLS_DC)
{
	zend_object_handle handle;

	handle = Z_OBJ_HANDLE_P(zobject);

	Z_ADDREF_P(zobject);
	zend_objects_store_del_ref_by_handle_ex(handle, Z_OBJ_HT_P(zobject) TSRMLS_CC);
	Z_DELREF_P(zobject);

	GC_ZOBJ_CHECK_POSSIBLE_ROOT(zobject);
}

/*
 * Delete a reference to an objects store entry given the object handle.
 */
ZEND_API void zend_objects_store_del_ref_by_handle_ex(zend_object_handle handle, const zend_object_handlers *handlers TSRMLS_DC) /* {{{ */
{
	struct _store_object *obj;
	int failure = 0;

	if (!EG(objects_store).object_buckets) {
		return;
	}

	obj = &EG(objects_store).object_buckets[handle].bucket.obj;

	/*	Make sure we hold a reference count during the destructor call
		otherwise, when the destructor ends the storage might be freed
		when the refcount reaches 0 a second time
	 */
	if (EG(objects_store).object_buckets[handle].valid) {
		if (obj->refcount == 1) {
			if (!EG(objects_store).object_buckets[handle].destructor_called) {
				EG(objects_store).object_buckets[handle].destructor_called = 1;

				if (obj->dtor) {
					if (handlers && !obj->handlers) {
						obj->handlers = handlers;
					}
					zend_try {
						obj->dtor(obj->object, handle TSRMLS_CC);
					} zend_catch {
						failure = 1;
					} zend_end_try();
				}
			}

			/* re-read the object from the object store as the store might have been reallocated in the dtor */
			obj = &EG(objects_store).object_buckets[handle].bucket.obj;

			if (obj->refcount == 1) {
				GC_REMOVE_ZOBJ_FROM_BUFFER(obj);
				if (obj->free_storage) {
					zend_try {
						obj->free_storage(obj->object TSRMLS_CC);
					} zend_catch {
						failure = 1;
					} zend_end_try();
				}
				ZEND_OBJECTS_STORE_ADD_TO_FREE_LIST();
			}
		}
	}

	obj->refcount--;

#if ZEND_DEBUG_OBJECTS
	if (obj->refcount == 0) {
		fprintf(stderr, "Deallocated object id #%d\n", handle);
	} else {
		fprintf(stderr, "Decreased refcount of object id #%d\n", handle);
	}
#endif
	if (failure) {
		zend_bailout();
	}
}
/* }}} */

ZEND_API zend_object_value zend_objects_store_clone_obj(zval *zobject TSRMLS_DC)
{
	zend_object_value retval;
	void *new_object;
	struct _store_object *obj;
	zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);

	obj = &EG(objects_store).object_buckets[handle].bucket.obj;

	if (obj->clone == NULL) {
		zend_error(E_CORE_ERROR, "Trying to clone uncloneable object of class %s", Z_OBJCE_P(zobject)->name);
	}

	obj->clone(obj->object, &new_object TSRMLS_CC);
	obj = &EG(objects_store).object_buckets[handle].bucket.obj;

	retval.handle = zend_objects_store_put(new_object, obj->dtor, obj->free_storage, obj->clone TSRMLS_CC);
	retval.handlers = Z_OBJ_HT_P(zobject);
	EG(objects_store).object_buckets[handle].bucket.obj.handlers = retval.handlers;

	return retval;
}

ZEND_API void *zend_object_store_get_object(const zval *zobject TSRMLS_DC)
{
	zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);

	return EG(objects_store).object_buckets[handle].bucket.obj.object;
}

/*
 * Retrieve an entry from the objects store given the object handle.
 */
ZEND_API void *zend_object_store_get_object_by_handle(zend_object_handle handle TSRMLS_DC)
{
	return EG(objects_store).object_buckets[handle].bucket.obj.object;
}

/* zend_object_store_set_object:
 * It is ONLY valid to call this function from within the constructor of an
 * overloaded object.  Its purpose is to set the object pointer for the object
 * when you can't possibly know its value until you have parsed the arguments
 * from the constructor function.  You MUST NOT use this function for any other
 * weird games, or call it at any other time after the object is constructed.
 * */
ZEND_API void zend_object_store_set_object(zval *zobject, void *object TSRMLS_DC)
{
	zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);

	EG(objects_store).object_buckets[handle].bucket.obj.object = object;
}

/* Called when the ctor was terminated by an exception */
ZEND_API void zend_object_store_ctor_failed(zval *zobject TSRMLS_DC)
{
	zend_object_handle handle = Z_OBJ_HANDLE_P(zobject);
	zend_object_store_bucket *obj_bucket = &EG(objects_store).object_buckets[handle];

	obj_bucket->bucket.obj.handlers = Z_OBJ_HT_P(zobject);;
	obj_bucket->destructor_called = 1;
}

/* Proxy objects workings */
typedef struct _zend_proxy_object {
	zval *object;
	zval *property;
} zend_proxy_object;

static zend_object_handlers zend_object_proxy_handlers;

ZEND_API void zend_objects_proxy_destroy(zend_object *object, zend_object_handle handle TSRMLS_DC)
{
}

ZEND_API void zend_objects_proxy_free_storage(zend_proxy_object *object TSRMLS_DC)
{
	zval_ptr_dtor(&object->object);
	zval_ptr_dtor(&object->property);
	efree(object);
}

ZEND_API void zend_objects_proxy_clone(zend_proxy_object *object, zend_proxy_object **object_clone TSRMLS_DC)
{
	*object_clone = emalloc(sizeof(zend_proxy_object));
	(*object_clone)->object = object->object;
	(*object_clone)->property = object->property;
	zval_add_ref(&(*object_clone)->property);
	zval_add_ref(&(*object_clone)->object);
}

ZEND_API zval *zend_object_create_proxy(zval *object, zval *member TSRMLS_DC)
{
	zend_proxy_object *pobj = emalloc(sizeof(zend_proxy_object));
	zval *retval;

	pobj->object = object;
	zval_add_ref(&pobj->object);
	ALLOC_ZVAL(pobj->property);
	INIT_PZVAL_COPY(pobj->property, member);
	zval_copy_ctor(pobj->property);

	MAKE_STD_ZVAL(retval);
	Z_TYPE_P(retval) = IS_OBJECT;
	Z_OBJ_HANDLE_P(retval) = zend_objects_store_put(pobj, (zend_objects_store_dtor_t)zend_objects_proxy_destroy, (zend_objects_free_object_storage_t) zend_objects_proxy_free_storage, (zend_objects_store_clone_t) zend_objects_proxy_clone TSRMLS_CC);
	Z_OBJ_HT_P(retval) = &zend_object_proxy_handlers;

	return retval;
}

ZEND_API void zend_object_proxy_set(zval **property, zval *value TSRMLS_DC)
{
	zend_proxy_object *probj = zend_object_store_get_object(*property TSRMLS_CC);

	if (Z_OBJ_HT_P(probj->object) && Z_OBJ_HT_P(probj->object)->write_property) {
		Z_OBJ_HT_P(probj->object)->write_property(probj->object, probj->property, value, 0 TSRMLS_CC);
	} else {
		zend_error(E_WARNING, "Cannot write property of object - no write handler defined");
	}
}

ZEND_API zval* zend_object_proxy_get(zval *property TSRMLS_DC)
{
	zend_proxy_object *probj = zend_object_store_get_object(property TSRMLS_CC);

	if (Z_OBJ_HT_P(probj->object) && Z_OBJ_HT_P(probj->object)->read_property) {
		return Z_OBJ_HT_P(probj->object)->read_property(probj->object, probj->property, BP_VAR_R, 0 TSRMLS_CC);
	} else {
		zend_error(E_WARNING, "Cannot read property of object - no read handler defined");
	}

	return NULL;
}

ZEND_API zend_object_handlers *zend_get_std_object_handlers(void)
{
	return &std_object_handlers;
}

static zend_object_handlers zend_object_proxy_handlers = {
	ZEND_OBJECTS_STORE_HANDLERS,

	NULL,						/* read_property */
	NULL,						/* write_property */
	NULL,						/* read dimension */
	NULL,						/* write_dimension */
	NULL,						/* get_property_ptr_ptr */
	zend_object_proxy_get,		/* get */
	zend_object_proxy_set,		/* set */
	NULL,						/* has_property */
	NULL,						/* unset_property */
	NULL,						/* has_dimension */
	NULL,						/* unset_dimension */
	NULL,						/* get_properties */
	NULL,						/* get_method */
	NULL,						/* call_method */
	NULL,						/* get_constructor */
	NULL,						/* get_class_entry */
	NULL,						/* get_class_name */
	NULL,						/* compare_objects */
	NULL,						/* cast_object */
	NULL,						/* count_elements */
};

/*
 * Local variables:
 * tab-width: 4
 * c-basic-offset: 4
 * indent-tabs-mode: t
 * End:
 */


text:
/* eslint-env browser */

import {isError} from '../utils';

// Copied from https://github.com/graingert/angular.js/blob/a43574052e9775cbc1d7dd8a086752c979b0f020/test/AngularSpec.js#L1883
describe('isError', () => {
  function testErrorFromDifferentContext(createError) {
    const iframe = document.createElement('iframe');
    document.body.appendChild(iframe);
    try {
      const error = createError(iframe.contentWindow);
      expect(isError(error)).toBe(true);
    } finally {
      iframe.parentElement.removeChild(iframe);
    }
  }

  it('should not assume objects are errors', () => {
    const fakeError = {message: 'A fake error', stack: 'no stack here'};
    expect(isError(fakeError)).toBe(false);
  });

  it('should detect simple error instances', () => {
    expect(isError(new Error())).toBe(true);
  });

  it('should detect errors from another context', () => {
    testErrorFromDifferentContext(win => new win.Error());
  });

  it('should detect DOMException errors from another context', () => {
    testErrorFromDifferentContext(win => {
      try {
        win.document.querySelectorAll('');
      } catch (e) {
        return e;
      }
      return null;
    });
  });
});


text:
using System;
using System.Linq;
using FluentAssertions;
using Serilog.Events;
using Serilog.Parsing;
using Xunit;

namespace Serilog.Sinks.Elasticsearch.Tests
{
    public class BulkActionTests : ElasticsearchSinkTestsBase
    {
        [Fact]
        public void DefaultBulkActionV7()
        {
            _options.IndexFormat = "logs";
            _options.TypeName = "_doc";
            _options.PipelineName = null;
            using (var sink = new ElasticsearchSink(_options))
            {
                sink.Emit(ADummyLogEvent());
                sink.Emit(ADummyLogEvent());
            }

            var bulkJsonPieces = this.AssertSeenHttpPosts(_seenHttpPosts, 2, 1);
            const string expectedAction = @"{""index"":{""_type"":""_doc"",""_index"":""logs""}}";
            bulkJsonPieces[0].Should().Be(expectedAction);
        }

        [Fact]
        public void BulkActionV7OverrideTypeName()
        {
            _options.IndexFormat = "logs";
            _options.TypeName = "logevent"; // This is the default value when creating the sink via configuration
            _options.AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7;
            _options.PipelineName = null;
            using (var sink = new ElasticsearchSink(_options))
            {
                sink.Emit(ADummyLogEvent());
                sink.Emit(ADummyLogEvent());
            }

            var bulkJsonPieces = this.AssertSeenHttpPosts(_seenHttpPosts, 2, 1);
            const string expectedAction = @"{""index"":{""_type"":""_doc"",""_index"":""logs""}}";
            bulkJsonPieces[0].Should().Be(expectedAction);
        }

        [Fact]
        public void DefaultBulkActionV8()
        {
            _options.IndexFormat = "logs";
            _options.TypeName = null;
            _options.PipelineName = null;
            using (var sink = new ElasticsearchSink(_options))
            {
                sink.Emit(ADummyLogEvent());
                sink.Emit(ADummyLogEvent());
            }

            var bulkJsonPieces = this.AssertSeenHttpPosts(_seenHttpPosts, 2, 1);
            const string expectedAction = @"{""index"":{""_index"":""logs""}}";
            bulkJsonPieces[0].Should().Be(expectedAction);
        }

        [Fact]
        public void BulkActionDataStreams()
        {
            _options.IndexFormat = "logs-my-stream";
            _options.TypeName = null;
            _options.PipelineName = null;
            _options.BatchAction = ElasticOpType.Create;

            using (var sink = new ElasticsearchSink(_options))
            {
                sink.Emit(ADummyLogEvent());
                sink.Emit(ADummyLogEvent());
            }

            var bulkJsonPieces = this.AssertSeenHttpPosts(_seenHttpPosts, 2, 1);
            const string expectedAction = @"{""create"":{""_index"":""logs-my-stream""}}";
            bulkJsonPieces[0].Should().Be(expectedAction);
        }

        [Fact]
        public void PipelineAction()
        {
            _options.IndexFormat = "logs-my-stream";
            _options.TypeName = "_doc";
            _options.PipelineName = "my-pipeline";
            _options.BatchAction = ElasticOpType.Index;

            using (var sink = new ElasticsearchSink(_options))
            {
                sink.Emit(ADummyLogEvent());
                sink.Emit(ADummyLogEvent());
            }

            var bulkJsonPieces = this.AssertSeenHttpPosts(_seenHttpPosts, 2, 1);
            const string expectedAction = @"{""index"":{""_type"":""_doc"",""_index"":""logs-my-stream"",""pipeline"":""my-pipeline""}}";
            bulkJsonPieces[0].Should().Be(expectedAction);
        }

        private static LogEvent ADummyLogEvent() {
            return new LogEvent(DateTimeOffset.Now, LogEventLevel.Information, null,
                new MessageTemplate("A template", Enumerable.Empty<MessageTemplateToken>()),
                Enumerable.Empty<LogEventProperty>());
        }
    }
}


text:
import {Component, OnInit} from '@angular/core';
import {Title} from '@angular/platform-browser';

@Component({
    templateUrl: './profile.component.html',
})
export class ProfileComponent implements OnInit {

    public constructor(private title: Title) {}

    public ngOnInit() {
        this.title.setTitle('Profile | Demo App');
    }
}


text:
	<title>Kerry Godliman's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Kerry Godliman's panel show appearances

Kerry Godliman has appeared in 44 episodes between 2013-2022.  Kerry Godliman on IMDB. Kerry Godliman on Wikipedia. Kerry Godliman on Chortle.

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2022-06-23 / Taskmaster

2019-12-31 / Mock The Week

2019-12-06 / Mock The Week

2019-11-29 / Mock The Week

2019-10-02 / Taskmaster

2019-06-13 / Mock The Week

2019-05-23 / Mock The Week

2019-05-02 / Frankie Boyle's New World Order

2019-04-07 / 8 Out of 10 Cats

2018-12-21 / Mock The Week

2018-12-03 / I'm Sorry I Haven't A Clue

2018-11-26 / I'm Sorry I Haven't A Clue

2018-11-07 / Taskmaster

2018-10-31 / Taskmaster

2018-10-24 / Taskmaster

2018-10-17 / Taskmaster

2018-10-10 / Taskmaster

2018-10-03 / Taskmaster

2018-09-28 / Mock The Week

2018-09-26 / Taskmaster

2018-09-21 / Mock The Week

2018-09-19 / Taskmaster

2018-09-12 / Taskmaster

2018-09-05 / Taskmaster

2018-07-05 / Mock The Week

2018-04-20 / The News Quiz

2018-01-19 / The News Quiz

2017-09-29 / Mock The Week

2017-09-15 / The News Quiz

2017-06-22 / Mock The Week

2017-06-20 / 8 Out of 10 Cats

2017-02-10 / The News Quiz

2016-12-09 / Breaking The News

2016-09-09 / The News Quiz

2016-08-01 / Do The Right Thing

2016-06-03 / The News Quiz

2016-05-20 / The News Quiz

2016-02-26 / The News Quiz

2014-10-20 / Never Mind The Buzzcocks

2014-09-22 / Just A Minute

2014-09-01 / Just A Minute

2014-06-16 / Alan Davies: As Yet Untitled

2014-02-04 / Dilemma

2013-12-13 / Loose Women