text:
#include "ArchiveException.h"
#include "aeron_archive_client/MessageHeader.h"
#include "aeron_archive_client/ControlResponse.h"
#include "aeron_archive_client/RecordingDescriptor.h"
#include "aeron_archive_client/RecordingSignalEvent.h"
#include "RecordingDescriptorPoller.h"

using namespace aeron;
using namespace aeron::archive::client;

static aeron::controlled_poll_fragment_handler_t controlHandler(RecordingDescriptorPoller &poller)
{
    return
        [&](AtomicBuffer &buffer, util::index_t offset, util::index_t length, Header &header)
        {
            return poller.onFragment(buffer, offset, length, header);
        };
}

RecordingDescriptorPoller::RecordingDescriptorPoller(
    std::shared_ptr<Subscription> subscription,
    const exception_handler_t &errorHandler,
    std::int64_t controlSessionId,
    int fragmentLimit) :
    m_fragmentAssembler(controlHandler(*this)),
    m_fragmentHandler(m_fragmentAssembler.handler()),
    m_errorHandler(errorHandler),
    m_subscription(std::move(subscription)),
    m_controlSessionId(controlSessionId),
    m_fragmentLimit(fragmentLimit)
{
}

RecordingDescriptorPoller::RecordingDescriptorPoller(
    std::shared_ptr<Subscription> subscription,
    const exception_handler_t &errorHandler,
    const on_recording_signal_t &recordingSignalConsumer,
    std::int64_t controlSessionId,
    int fragmentLimit) :
    m_fragmentAssembler(controlHandler(*this)),
    m_fragmentHandler(m_fragmentAssembler.handler()),
    m_errorHandler(errorHandler),
    m_onRecordingSignal(recordingSignalConsumer),
    m_subscription(std::move(subscription)),
    m_controlSessionId(controlSessionId),
    m_fragmentLimit(fragmentLimit)
{
}

ControlledPollAction RecordingDescriptorPoller::onFragment(
    AtomicBuffer &buffer, util::index_t offset, util::index_t length, Header &header)
{
    if (m_isDispatchComplete)
    {
        return ControlledPollAction::ABORT;
    }

    MessageHeader msgHeader(
        buffer.sbeData() + offset,
        static_cast<std::uint64_t>(length),
        MessageHeader::sbeSchemaVersion());

    const std::uint16_t schemaId = msgHeader.schemaId();
    if (schemaId != MessageHeader::sbeSchemaId())
    {
        throw ArchiveException(
            "expected schemaId=" + std::to_string(MessageHeader::sbeSchemaId()) +
            ", actual=" + std::to_string(schemaId),
            SOURCEINFO);
    }

    switch (msgHeader.templateId())
    {
        case ControlResponse::SBE_TEMPLATE_ID:
        {
            ControlResponse response(
                buffer.sbeData() + offset + MessageHeader::encodedLength(),
                static_cast<std::uint64_t>(length) - MessageHeader::encodedLength(),
                msgHeader.blockLength(),
                msgHeader.version());

            if (response.controlSessionId() == m_controlSessionId)
            {
                const ControlResponseCode::Value code = response.code();
                const std::int64_t correlationId = response.correlationId();

                if (ControlResponseCode::Value::RECORDING_UNKNOWN == code && correlationId == m_correlationId)
                {
                    m_isDispatchComplete = true;
                    return ControlledPollAction::BREAK;
                }

                if (ControlResponseCode::Value::ERROR == code)
                {
                    ArchiveException ex(
                        static_cast<std::int32_t>(response.relevantId()),
                        correlationId,
                        "response for correlationId=" + std::to_string(m_correlationId) +
                            ", error: " + response.errorMessage(),
                        SOURCEINFO);

                    if (correlationId == m_correlationId)
                    {
                        throw ArchiveException(ex);
                    }
                    else if (nullptr != m_errorHandler)
                    {
                        m_errorHandler(ex);
                    }
                }
            }

            break;
        }

        case RecordingDescriptor::SBE_TEMPLATE_ID:
        {
            RecordingDescriptor descriptor(
                buffer.sbeData() + offset + MessageHeader::encodedLength(),
                static_cast<std::uint64_t>(length) - MessageHeader::encodedLength(),
                msgHeader.blockLength(),
                msgHeader.version());

            const std::int64_t correlationId = descriptor.correlationId();
            if (descriptor.controlSessionId() == m_controlSessionId && correlationId == m_correlationId)
            {
                m_consumer(
                    m_controlSessionId,
                    correlationId,
                    descriptor.recordingId(),
                    descriptor.startTimestamp(),
                    descriptor.stopTimestamp(),
                    descriptor.startPosition(),
                    descriptor.stopPosition(),
                    descriptor.initialTermId(),
                    descriptor.segmentFileLength(),
                    descriptor.termBufferLength(),
                    descriptor.mtuLength(),
                    descriptor.sessionId(),
                    descriptor.streamId(),
                    descriptor.getStrippedChannelAsString(),
                    descriptor.getOriginalChannelAsString(),
                    descriptor.getSourceIdentityAsString());

                if (0 == --m_remainingRecordCount)
                {
                    m_isDispatchComplete = true;
                    return ControlledPollAction::BREAK;
                }
            }

            break;
        }

        case RecordingSignalEvent::SBE_TEMPLATE_ID:
        {
            RecordingSignalEvent recordingSignalEvent(
                buffer.sbeData() + offset + MessageHeader::encodedLength(),
                static_cast<std::uint64_t>(length) - MessageHeader::encodedLength(),
                msgHeader.blockLength(),
                msgHeader.version());

            m_onRecordingSignal(
                recordingSignalEvent.controlSessionId(),
                recordingSignalEvent.recordingId(),
                recordingSignalEvent.subscriptionId(),
                recordingSignalEvent.position(),
                recordingSignalEvent.signalRaw());

            break;
        }
    }

    return ControlledPollAction::CONTINUE;
}


text:
"""
Views for filebrowser in TinyMCE
"""
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_control
from django.views.generic.base import RedirectView
from django.views.generic.base import TemplateView
from django.views.generic.edit import CreateView
from django.views.generic.list import ListView

from zinnia.models import Entry

from zinnia_tinymce.models import FileModel

class StaffMemberRequiredMixin(object):

    @method_decorator(staff_member_required)
    @method_decorator(cache_control(max_age=0))
    def dispatch(self, *args, **kwargs):
        return super(StaffMemberRequiredMixin, self).dispatch(*args, **kwargs)

class EntryLinksView(StaffMemberRequiredMixin,
                     ListView):
    model = Entry
    template_name = 'zinnia_tinymce/entry_links.js'
    content_type = 'application/javascript'

class ImageLinksView(StaffMemberRequiredMixin,
                     ListView):
    template_name = 'zinnia_tinymce/image_links.js'
    content_type = 'application/javascript'

    def get_queryset(self):
        return FileModel.objects.filter(file_type='image')

class FileLinksView(StaffMemberRequiredMixin,
                    ListView):
    template_name = 'zinnia_tinymce/file_links.js'
    content_type = 'application/javascript'

    def get_queryset(self):
        return FileModel.objects.filter(file_type='file')

class FileBrowserCallBackView(StaffMemberRequiredMixin,
                              TemplateView):
    template_name = 'zinnia_tinymce/filebrowser.js'
    content_type = 'application/javascript'

class FileBrowserView(StaffMemberRequiredMixin,
                      CreateView):
    model = FileModel
    fields = ['uploaded_file']
    success_url = '.'
    upload_tab_active = False
    limit = 20

    def get_context_data(self, **kwargs):
        context = super(FileBrowserView, self).get_context_data(**kwargs)
        if self.object:
            context['uploaded_file'] = self.object
        file_type = self.kwargs['file_type']
        context['file_type'] = file_type
        context['upload_tab_active'] = self.upload_tab_active
        context['files'] = FileModel.objects.filter(
            file_type=file_type)[:self.limit]
        return context

    def post(self, request, *args, **kwargs):
        self.upload_tab_active = False
        return super(FileBrowserView, self).post(request, *args, **kwargs)

    def form_valid(self, form):
        form.instance.file_type = self.kwargs['file_type']
        self.object = form.save()
        return super(FileBrowserView, self).form_valid(form)

class RemoveFileView(StaffMemberRequiredMixin,
                     RedirectView):
    permanent = False
    pattern_name = 'tinymce-filebrowser'

    def get_redirect_url(self, *args, **kwargs):
        pk = self.kwargs['pk']
        file_type = self.kwargs['file_type']

        f = get_object_or_404(FileModel, pk=pk)
        f.delete()

        return super(RemoveFileView, self).get_redirect_url(
            file_type=file_type)

redpajama_set_name: RedPajamaGithub


text:
'use strict';

module.exports = {

  tagName: 'meta',
  type: 'meta',

  import: function(el, node, converter) {
    node.id = 'meta';
    var titleEl = el.find('title');
    if (titleEl) {
      node.title = converter.annotatedText(titleEl, ['meta', 'title']);
    } else {
      node.title = '';
    }
  },

  export: function(node, el, converter) {
    el.append(el.createElement('title').append(
      converter.annotatedText(['meta', 'title'])
    ));
  }

};


text:
/* ==========================================================================
   Insert Your Custom Styles Below. All styles located in this file will
   override existing main.css stylesheets.
   ========================================================================== */

#content h1 { color:#22b573; font-size:29px; line-height:35px; letter-spacing:-1px; }
#content h2 { color:#22b573; }
.blog-post .metadata p { display:inline-block; }
.blog-posts { margin:0; list-style-type:none; }

.comment-list { margin-left:0; list-style-type:none; }
.comment a { font-weight:200; }
.lead-meta { font-size:12px; }
ul.media { list-style-type:none; }
.blog-post-detail-body { border-bottom: 1px dotted #E4E4E4; padding-bottom: 40px; margin-bottom:30px; }
.post-comment legend { border:0; font-size: 21px; font-weight: 200; line-height: 30px; font-family:'Open Sans', sans-serif; margin-top:20px; }
.post-comment ol { list-style-type:none; margin-left:0; }
.post-comment input[type="text"], .post-comment textarea { width:90%; }

.pager { text-align:left; padding-left:75px; }
.pager li { margin-left:-4px; }
.pager li > a, .pager li>span { padding:10px 19px; border-radius:0; -moz-border-radius:0; -webkit-border-radius:0; border:0; background-color:#F1F4F5; }
.pager li > a:hover, .pager li>span { background-color:#E4E9EA;}

/* Edit Mode Widgets */
/* These are the edit controls that appear when you're logged-in */
.widget-control { position: relative; border: 1px dotted #5f97af; }
.widget-control .manage-actions { position:absolute; top: 0px; right: 0px; z-index:101; }
.widget-control .manage-actions a { display: block; background-color: #dbdbdb; color: #434343; padding: 3px 6px;  }
.widget-control .manage-actions a:hover { background-color: #434343; color: #fff; text-decoration: none; }

/* Content Mode */
.content-control { border: 1px dotted #5f97af; overflow:auto; position: relative; }
.content-control .manage-actions { position:absolute; top: 0px; right: 0px; z-index:101; }
.content-control .manage-actions a { display: block; background-color: #dbdbdb; color: #434343; padding: 3px 6px;  }
.content-control .manage-actions a:hover { background-color: #434343; color: #fff; text-decoration: none; }


text:
from lsh.lsh.lsh_base import LshBase
from lsh.utils.similarity import jaccard_similarity
from lsh.utils.similarity import compute_positive_hash
from lsh.models.documents.jaccard_document import JaccardDocument
import copy

def _get_documents(hash_code, band_dict):
    if hash_code and band_dict:
        return band_dict.get(hash_code, None)
    return None

def _update_bucket(hash_code, band_dict, new_document):
    docs = band_dict.get(hash_code, None)
    if docs:
        updated_docs = copy.deepcopy(docs)
        updated_docs.append(new_document)
        band_dict[hash_code] = updated_docs
        # print "updated!!"
        # for doc in updated_docs:
        #     print doc.get_original_document()

class LshJaccard(LshBase):

    def __init__(self, num_bands=20, rows_per_band=10, threshold=0.0):

        # number of bands (i.e. buckets) to create
        self.num_bands = num_bands

        # this will be the number of signatures in a vector to be hashed
        self.num_rows_per_band = rows_per_band

        #should be thread safe if one instance of this class is used by threads in a pool for example
        #we may need to make a centralized resource to implement this...for now this is good enough.
        self.bands = self._create_band_dicts()

        #note, the default settings give you a threshold ~.74
        if threshold == 0.0:
            self.threshold = self._calculate_threshold()
        else:
            self.threshold = threshold

    def run(self, document_to_examine):

        #step 1: get document hash signature list
        signatures = list(document_to_examine.get_signatures_list())
        start = 0

        #get current band
        for band_idx in xrange(0, self.num_bands):

            #step 2: get minhash signature vector for current band
            vector = self._get_vector(signatures, self.num_rows_per_band, start)

            #step 3: hash current vector and add to it a new bucket or compare and record the document (and vector)
            # that hashed to an existing bucket
            if vector:
                # note, wrapping in tuple as it will maintain order and is immutable
                # immutability enables us to calculate a hash for it
                vector_tuple = tuple(vector)

                if vector_tuple:
                    vector_hash = self._calculate_hash(vector_tuple)

                    #step 4: get current band
                    current_band_dict = self._get_band_by_index(band_idx)

                    #step 5: get docs from the current band's bucket that has the current vector_hash as it's key
                    docs = _get_documents(vector_hash, current_band_dict)

                    #if we don't have docs, add the current doc to a new list and update band dict
                    if not docs:
                        current_band_dict[vector_hash] = [document_to_examine]
                    else:
                        #step 6: check similarity of each document pair

                        #6a: update the current band's bucket that this current document to be examined hashed to
                        _update_bucket(vector_hash, current_band_dict, document_to_examine)

                        #6b: iterate through the current band's bucket of documents, calculate similarity
                        # scores for each pair and yield results
                        for doc in docs:
                            score = self._calculate_similarity_score(document_to_examine, doc)

                            if self._documents_are_similar(score):
                                match_found = True
                            else:
                                match_found = False

                            if score > 0.0:
                                doc1 = document_to_examine.get_original_document()
                                doc2 = doc.get_original_document()
                                yield self._build_results_dict(score, match_found, doc1, doc2, band_idx)

            # update starting value to get next vector
            start = start + self.num_rows_per_band + 1

    #--- helper functions ----

    def _build_results_dict(self, score, match_found, doc_1, doc_2, band_matched):
        """
            Build LSH results dictionary.
            :param score:
            :param match_found:
            :param doc_1:
            :param doc_2:
            :return: results dict that contains candidate documents, threshold and LSH similarity score.
        """
        results_dict = {"score": score,
                        "match_found": match_found,
                        "document_1": doc_1,
                        "document_2": doc_2,
                        "threshold": self.threshold,
                        "band_matched": band_matched}
        return results_dict

    #TODO refactor so that users can specify their own hashing function(s)
    def _calculate_hash(self, obj):
        """
            This method computes hash of object using a dynamic hashing function.
            :param obj: object we are computing hash code for.
            :return: hash code (long integer)
        """

        # hash value to positive integer
        h1 = compute_positive_hash(obj)

        #calculate hash code: h(obj) mod 2^b (where b is num_bands)
        return h1 % 2**self.num_bands

    def _documents_are_similar(self, similarity_score):
        """
            Checks if similarity score against threshold.
            :param similarity_score:
            :return: True if similarity score is greater than or equal to threshold, otherwise False
        """
        return similarity_score >= self.threshold

    def _get_band_by_index(self, idx):
        """
         Gets band by idx from bands collection.
            :param idx:
            :return: None if bands None or idx is greater than number of length of bands collection.
        """
        if self.bands and idx < len(self.bands):
            return self.bands[idx]

        return None

    def _get_vector(self, signatures, n, start):
        """
            Slices signatures into lists of n rows.
            :param signatures: list of minhash signatures
            :param n: number of rows to include in slice
            :return: list (vector)
        """
        for i in xrange(start, len(signatures), n):
            #yes, technically this is a list slice not a vector
            return signatures[i:i+n]

    def _calculate_similarity_score(self, document_1, document_2):
        """
            Calculate similarity score for givens documents.
            :param document_1:
            :param document_2:
            :return: 0.0 if score can't be calculated otherwise returns calculated value
        """
        score = 0.0

        if document_1 and document_2:
            shingles_set_1 = document_1.get_shingles_as_set()
            shingles_set_2 = document_2.get_shingles_as_set()

            score = jaccard_similarity(shingles_set_1, shingles_set_2)

        return score

    def _calculate_threshold(self):
        """
            Calculate threshold.
            :return: threshold returned, if threshold can't be calculated returns 0.0
        """

        #(1/b)^(1/r)
        # b = # of bands
        # r = # rows in a band

        _b = float(self.num_bands)
        _r = float(self.num_rows_per_band)

        if _b > 0 and _r > 0:
            return (1.0/_b)**(1.0/_r)

        return 0.0

    def _create_band_dicts(self):
        """
            Create a list of bands (dicts). Each dict represents one band (bucket).
            :return: list of dicts that represents bands.
        """
        buckets = None

        if self.num_bands > 0:

            buckets = []

            #create x bands (each index represents one band)
            for _ in range(0, self.num_bands):
                buckets.append({})

        return buckets

# for quick testing only...remote and add unit tests instead
# if __name__ == '__main__':
#
#     from lsh.utils.similarity import jaccard_similarity
#     from lsh.shingles.shingles import shingle_generator, ShingleType
#     from lsh.minhash import minhash
#
#     test_docs = list()
#     test_docs.append("Mary had a little lamb, His fleece was white as snow, And everywhere that Mary went, The lamb was sure to go.")
#     test_docs.append("Mary had a little lamb, His fleece was wte as snow, And everywhere thot Mary went, The lamb was sure to go.")
#     test_docs.append("Maryhad a little lomb, is fleece was whit as snow, And evewhere thot Mary went, The lomb was sure to go.")
#     test_docs.append("Mary had a little lamb, His fleece wa")
#     test_docs.append("Mary")
#     test_docs.append("Mary had a little lamb, His fleece was white as snow, And everywhere that Mary went, The lamb was sure to go.")
#
#     def faux_doc_generator():
#         for doc in test_docs:
#             yield doc
#
#     # Examples: Lower the number of bands the higher the threshold becomes
#     # num_bands divides evenly into the number
#     #num_bands=100, rows_per_band=2 => 0.1
#     #num_bands=50, rows_per_band=4 => 0.37
#     #num_bands=10, rows_per_band=20 => 0.89
#     #num_bands=20, rows_per_band=10 => 0.74
#     #num_bands=5, rows_per_band=40 => 0.96
#
#     lshj = LshJaccard(num_bands=20, rows_per_band=10)
#     print "-- number of bands: %s" % str(lshj.num_bands)
#     print "-- number of rows per band: %s" % str(lshj.num_rows_per_band)
#     print "-- default threshold: %s" % str(lshj._calculate_threshold())
#     print ""
#
#     for shingles_list, original_document in shingle_generator(faux_doc_generator()):
#         # get minhash signatures for each shingle list
#         min_hash_signatures = minhash.run(shingles_list)
#
#         #create document and run LSH for Jaccard Distance
#         doc_obj = JaccardDocument(original_document, shingles_list, min_hash_signatures)
#
#         for results in lshj.run(doc_obj):
#             if results:
#                 print results


text:
This is a client for the OpenConfig gRPC interface that pushes telemetry to
OpenTSDB.  Non-numerical data isn't supported by OpenTSDB and is silently
dropped.

This tool requires a config file to specify how to map the path of the
notificatons coming out of the OpenConfig gRPC interface onto OpenTSDB
metric names, and how to extract tags from the path.

## Getting Started
To begin, a list of subscriptions is required (excerpt from `sampleconfig.json`):

```json
	"subscriptions": [
		"/Sysdb/interface/counter/eth/lag",
		"/Sysdb/interface/counter/eth/slice/phy",

		"/Sysdb/environment/temperature/status",
		"/Sysdb/environment/cooling/status",
		"/Sysdb/environment/power/status",

		"/Sysdb/hardware/xcvr/status/all/xcvrStatus"
	],
	...
```

Note that subscriptions should not end with a trailing `/` as that will cause
the subscription to fail.

Afterwards, the metrics are defined (excerpt from `sampleconfig.json`):

```json
	"metrics": {
		"tempSensor": {
			"path": "/Sysdb/(environment)/temperature/status/tempSensor/(?P<sensor>.+)/((?:maxT|t)emperature)"
		},
		...
	}
```

In the metrics path, unnamed matched groups are used to make up the metric name, and named matched groups
are used to extract optional tags. Note that unnamed groups are required, otherwise the metric
name will be empty and the update will be silently dropped.

For example, using the above metrics path applied to an update for the path
`/Sysdb/environment/temperature/status/tempSensor/TempSensor1/temperature`
will lead to the metric name `environment.temperature` and tags `sensor=TempSensor1`.

You can optionally rewrite values of type string with integer values using StaticValueMap.
``` "metrics":{
      "operStatus":{
         "path":"/Sysdb/interface/status/eth/phy/slice/1/intfStatus/(?P<intf>.+)/operStatus$",
         "StaticValueMap":{
             "intfOperUp": 1,
             "intfOperDown": 0,
             "intfOperNotPresent": 0,
             "default": 0
         }
      }
   }
```
## Usage

See the `-help` output, but here's an example to push all the metrics defined
in the sample config file:
```
octsdb -addr <switch-hostname>:6042 -config sampleconfig.json -text | nc <tsd-hostname> 4242
```


text:
package mutating

import (
	"context"
	"io"

	"k8s.io/apiserver/pkg/admission"
	"k8s.io/apiserver/pkg/admission/configuration"
	"k8s.io/apiserver/pkg/admission/plugin/webhook/generic"
)

const (
	// PluginName indicates the name of admission plug-in
	PluginName = "MutatingAdmissionWebhook"
)

// Register registers a plugin
func Register(plugins *admission.Plugins) {
	plugins.Register(PluginName, func(configFile io.Reader) (admission.Interface, error) {
		plugin, err := NewMutatingWebhook(configFile)
		if err != nil {
			return nil, err
		}

		return plugin, nil
	})
}

// Plugin is an implementation of admission.Interface.
type Plugin struct {
	*generic.Webhook
}

var _ admission.MutationInterface = &Plugin{}

// NewMutatingWebhook returns a generic admission webhook plugin.
func NewMutatingWebhook(configFile io.Reader) (*Plugin, error) {
	handler := admission.NewHandler(admission.Connect, admission.Create, admission.Delete, admission.Update)
	p := &Plugin{}
	var err error
	p.Webhook, err = generic.NewWebhook(handler, configFile, configuration.NewMutatingWebhookConfigurationManager, newMutatingDispatcher(p))
	if err != nil {
		return nil, err
	}

	return p, nil
}

// ValidateInitialization implements the InitializationValidator interface.
func (a *Plugin) ValidateInitialization() error {
	if err := a.Webhook.ValidateInitialization(); err != nil {
		return err
	}
	return nil
}

// Admit makes an admission decision based on the request attributes.
func (a *Plugin) Admit(ctx context.Context, attr admission.Attributes, o admission.ObjectInterfaces) error {
	return a.Webhook.Dispatch(ctx, attr, o)
}


text:
Uno for Ghost is the result of my first 'mini-project' of 2014. The theme features a minimal, responsive design with a cover page, disqus comment integration, foundation icons and various colour options.

## Demo
There's a demo of the theme running on my personal website, [daleanthony.com](http://daleanthony.com)

## Features

**Cover page**
The landing page for Uno is a full screen 'cover' featuring your avatar, blog title, mini-bio and cover image.

**Built with SASS, using BEM**
If you know HTML and CSS making modifications to the theme should be super simple.

**Responsive**
Uno looks great on all devices, even those weird phablets that nobody buys.

**Disqus comments**
Disqus integration allows users to comment on your posts.

**Foundation icons**
Uno contains the [Foundation icon font by Zurb](http://zurb.com/playground/foundation-icon-fonts-3) which means you can easily add icons. A full list of available icons can be found on the [Foundation Icon](http://zurb.com/playground/foundation-icon-fonts-3) website.

**No-JS fallback**
While JS is widely used, some themes and websites don't provide fallback for when no JS is available (I'm looking at you [Squarespace](http://blog.squarespace.com/)). If for some weird reason a visitor has JS disabled your blog will still be useable.

**Development**
Ghost is still a work in progress with many features not yet implemented, as Ghost gets updated new features will be added to Uno.

**1 theme, 5 colour options**
Uno includes 5 different colour options for you to chose from.


text:
import Layout from '../components/layout'
import Link from 'next/link'

export default function Home() {
  return (
    <Layout>

Hello! I'm Kevin, a software engineer who loves solving problems with code and building
          products that make the Internet a better place for everyone. I'm always learning something
          new.

Most recently, I worked across several teams
        at <Link href="/work">Deliveroo</Link> since 2016, focusing primarily on making the
        delivery network more resilient and helping riders get paid as quickly as possible.

When I'm not writing code, I have quite a few
        activities that fight for my attention. Among other things I enjoy reading books, exploring
        the outdoors on my bike or on foot, playing video-games,
        taking pictures, cooking and playing the
        violin.

    </Layout>
  )
}


text:
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using MegaManager.Data.Main.Map;
using MegaManager.Domain.Main;

namespace MegaManager.Infra.Data
{
    public class MegaManagerContext : DbContext
    {
             public MegaManagerContext() : base("MegaManagerContext")
             {
                  Configuration.LazyLoadingEnabled = false;
                  Configuration.ProxyCreationEnabled = false;
             }

             public DbSet<Gabarito> Gabaritos { get; set; }
             public DbSet<Resultado> Resultados { get; set; }
             public DbSet<Previsao> Previsoes { get; set; }

             protected override void OnModelCreating(DbModelBuilder modelBuilder)
             {
                 modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
                 modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
                 modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

                 modelBuilder.Properties()
                        .Where(p => p.Name == "Id") //p.ReflectedType.Name
                        .Configure(p => p.IsKey());

                 modelBuilder.Properties()
                        .Where(p => p.Name == "Id")
                        .Configure(p => p.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity));

                 modelBuilder.Properties<string>()
                        .Configure(p => p.HasColumnType("varchar"));

                 modelBuilder.Properties<string>()
                       .Configure(p => p.HasMaxLength(255));

                 modelBuilder.Configurations.Add(new GabaritoMap());
                 modelBuilder.Configurations.Add(new ResultadoMap());
                 modelBuilder.Configurations.Add(new PrevisaoMap());
             }
    }
}


text:
<?php

namespace Smartbox\Integration\FrameworkBundle\Tools\SmokeTests;

use Smartbox\CoreBundle\Utils\SmokeTest\SmokeTestInterface;
use Smartbox\CoreBundle\Utils\SmokeTest\Output\SmokeTestOutput;
use Smartbox\CoreBundle\Utils\SmokeTest\Output\SmokeTestOutputMessage;

/**
 * Class ConnectivityCheckSmokeTest.
 */
class ConnectivityCheckSmokeTest implements SmokeTestInterface
{
    const TAG_TEST_CONNECTIVITY = 'smartesb.smoke_test.test_connectivity';

    /**
     * @var null|string
     */
    protected $description = 'Generic SmokeTest to check connectivity.';

    /**
     * @var CanCheckConnectivityInterface[]
     */
    protected $items = [];

    /**
     * ConnectivityCheckSmokeTest constructor.
     *
     * @param string|null                     $description
     * @param CanCheckConnectivityInterface[] $items
     */
    public function __construct($description = null, $items = [])
    {
        if (null !== $description) {
            $this->description = $description;
        }
        $this->items = $items;
    }

    /**
     * @param $name
     * @param CanCheckConnectivityInterface $item
     */
    public function addItem($name, CanCheckConnectivityInterface $item)
    {
        if (array_key_exists($name, $this->items)) {
            throw new \RuntimeException(
                sprintf(
                    'Item with name "%s" already exists. Please provide unique name.',
                    $name
                )
            );
        }

        $this->items[$name] = $item;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function run()
    {
        $smokeTestOutput = new SmokeTestOutput();
        $exitCode = SmokeTestOutput::OUTPUT_CODE_SUCCESS;

        // if there are no items to check their connectivity this smoke test passes
        if (empty($this->items)) {
            $smokeTestOutput->setCode($exitCode);
            $smokeTestOutput->addInfoMessage('I\'m useless... There are no items which needs to check their connectivity.');

            return $smokeTestOutput;
        }

        foreach ($this->items as $name => $item) {
            try {
                $smokeTestOutputForItem = $item->checkConnectivityForSmokeTest();

                if (!$smokeTestOutputForItem->isOK()) {
                    $exitCode = SmokeTestOutput::OUTPUT_CODE_FAILURE;
                }

                $messages = $smokeTestOutputForItem->getMessages();
                foreach ($messages as $message) {
                    $messageText = sprintf(
                        '[%s]: %s',
                        $name,
                        $message->getValue()
                    );
                    switch($message->getType()) {
                        case SmokeTestOutputMessage::OUTPUT_MESSAGE_TYPE_INFO:
                            $smokeTestOutput->addInfoMessage($messageText);
                            break;
                        case SmokeTestOutputMessage::OUTPUT_MESSAGE_TYPE_FAILURE:
                            $smokeTestOutput->addFailureMessage($messageText);
                            break;
                        case SmokeTestOutputMessage::OUTPUT_MESSAGE_TYPE_SUCCESS:
                            $smokeTestOutput->addSuccessMessage($messageText);
                            break;
                        default:
                            $smokeTestOutput->addFailureMessage($messageText);
                            break;
                    }
                }
            } catch (\Exception $e) {
                $exitCode = SmokeTestOutput::OUTPUT_CODE_FAILURE;
                $smokeTestOutput->addFailureMessage(
                    sprintf(
                        '[%s]: %s',
                        $name,
                        '['.get_class($e).'] '.$e->getMessage()
                    )
                );
            }
        }

        if ($exitCode === SmokeTestOutput::OUTPUT_CODE_SUCCESS) {
            $smokeTestOutput->addSuccessMessage('Connectivity checked.');
        }

        $smokeTestOutput->setCode($exitCode);

        return $smokeTestOutput;
    }
}


text:
package uk.ac.edukapp.security;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import net.oauth.OAuth;
import net.oauth.OAuthMessage;

/**
 * An HttpServletRequest, encapsulated as an OAuthMessage.
 *
 * @author John Kristian
 */
public class HttpRequestMessage extends OAuthMessage {

    public HttpRequestMessage(HttpServletRequest request, String URL) {
        super(request.getMethod(), URL, getParameters(request));
        this.request = request;
        copyHeaders(request, getHeaders());
    }

    private final HttpServletRequest request;

    @Override
    public InputStream getBodyAsStream() throws IOException {
        return request.getInputStream();
    }

    @Override
    public String getBodyEncoding() {
        return request.getCharacterEncoding();
    }

    private static void copyHeaders(HttpServletRequest request, Collection<Map.Entry<String, String>> into) {
        @SuppressWarnings("unchecked")
        Enumeration<String> names = request.getHeaderNames();
        if (names != null) {
            while (names.hasMoreElements()) {
                String name = names.nextElement();
                @SuppressWarnings("unchecked")
                Enumeration<String> values = request.getHeaders(name);
                if (values != null) {
                    while (values.hasMoreElements()) {
                        String value = values.nextElement();
                        into.add(new OAuth.Parameter(name, value));
                    }
                }
            }
        }
    }

    public static List<OAuth.Parameter> getParameters(HttpServletRequest request) {
        List<OAuth.Parameter> list = new ArrayList<OAuth.Parameter>();
        for (@SuppressWarnings("unchecked")
        Enumeration<String> headers = request.getHeaders("Authorization"); headers != null
                && headers.hasMoreElements();) {
            String header = headers.nextElement();
            for (OAuth.Parameter parameter : OAuthMessage
                    .decodeAuthorization(header)) {
                if (!"realm".equalsIgnoreCase(parameter.getKey())) {
                    list.add(parameter);
                }
            }
        }
        for (Object e : request.getParameterMap().entrySet()) {
            @SuppressWarnings("unchecked")
            Map.Entry<String, String[]> entry = (Map.Entry<String, String[]>) e;
            String name = entry.getKey();
            for (String value : entry.getValue()) {
                if(!name.equals("_")){
                  if (name.equals("oauth_signature")){
                    //
                    // Hack - for some reason spaces aren't being replaced
                    //
                    value = value.replaceAll("\\s", "+");
                  }
                  list.add(new OAuth.Parameter(name, value));
                }
            }
        }
        return list;
    }

}


text:
package pkgmirror

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/NYTimes/gziphandler"
	log "github.com/Sirupsen/logrus"
	"github.com/bakins/logrus-middleware"
	"github.com/rande/goapp"
	"goji.io"
)

func GetApp(conf *Config, l *goapp.Lifecycle) (*goapp.App, error) {

	app := goapp.NewApp()

	// init logger
	logger := log.New()
	if level, err := log.ParseLevel(conf.LogLevel); err != nil {
		return app, errors.New(fmt.Sprintf("Unable to parse the log level: %s", conf.LogLevel))
	} else {
		logger.Level = level
	}

	if len(conf.DataDir) == 0 {
		return app, errors.New("Please configure DataDir")
	}

	app.Set("logger", func(app *goapp.App) interface{} {
		return logger
	})

	app.Set("config", func(app *goapp.App) interface{} {
		return conf
	})

	app.Set("bolt.compacter", func(app *goapp.App) interface{} {
		logger := app.Get("logger").(*log.Logger)

		return &BoltCompacter{
			Logger:    logger,
			TxMaxSize: 65536,
		}
	})

	app.Set("mux", func(app *goapp.App) interface{} {
		m := goji.NewMux()

		m.Use(func(h http.Handler) http.Handler {
			gzip := gziphandler.GzipHandler(h)

			return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
				skip := false
				if len(r.URL.Path) > 4 && r.URL.Path[1:4] == "npm" {
					skip = true
				}

				if len(r.URL.Path) > 8 && r.URL.Path[1:9] == "composer" {
					skip = true
				}

				if r.URL.Path == "/api/sse" {
					skip = true
				}

				if skip {
					h.ServeHTTP(w, r)
				} else {
					gzip.ServeHTTP(w, r)
				}
			})
		})

		m.Use(func(h http.Handler) http.Handler {
			lm := &logrusmiddleware.Middleware{
				Logger: logger,
				Name:   "pkgmirror",
			}

			return lm.Handler(h, "http")
		})

		return m
	})

	return app, nil
}


text:
import { Section, Chapter } from 'core/components'
import { PageType } from 'core/types'
import { SyntaxHighlighter, prism, FooterNav } from '..'
export const Page: PageType = () => {
    return (
        <Chapter filename="deploying">

Deploying your story

                    NextJS, and therefore Windrift, has two mechanisms of deploying your
                    application: a purely "static" generation mechanism, and one that requires use
                    of a backend server. Most Windrift stories are static only, meaning they need no
                    backend and can be deployed on any site capable of hosting HTML files. This
                    document will focus on static deployment and hosting.

Generating a static build

                    During development using npm run dev, you are running a local Node
                    server that comes packaged with NextJS. To build statically, you'll use a
                    different command:

                    npm run export

                    This command will generate a local folder, out, containing one HTML
                    page for each of your stories. For example, when run from the default Windrift
                    install, you'll get this manual plus all other included sample stories:

                <SyntaxHighlighter language="bash" style={prism}>
                    {`$ npm run build
[...]

Page                              Size     First Load JS
┌   /_app                         0 B            69.2 kB
├ ● /[story]/[[...chapter]]       59.5 kB         129 kB
├   ├ /manual
├   ├ /minimal
├   ├ /stone-harbor
├   └ /stone-harbor-pt
└ ○ /404                          194 B          69.4 kB
+ First Load JS shared by all     69.2 kB
  ├ chunks/framework.c93ed7.js    42.6 kB
  ├ chunks/main.1f2c59.js         23.6 kB
  ├ chunks/pages/_app.dbf9d9.js   576 B
  ├ chunks/webpack.9c0dc3.js      2.46 kB
  └ css/c02acf3b427bae0b01cb.css  339 B

λ  (Server)  server-side renders at runtime (uses getInitialProps or getServerSideProps)
○  (Static)  automatically rendered as static HTML (uses no initial props)
●  (SSG)     automatically generated as static HTML + JSON (uses getStaticProps)
   (ISR)     incremental static regeneration (uses revalidate in getStaticProps)

info  - Loaded env from /Users/liza/github/windrift/.env
info  - Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
info  - using build directory: /Users/liza/github/windrift/.next
info  - Copying "static build" directory
info  - No "exportPathMap" found in "next.config.js". Generating map from "./pages"
info  - Launching 9 workers
info  - Copying "public" directory
info  - Exporting (1/1)
Export successful. Files written to /Users/liza/github/windrift/out

$ ls -F out
404/             manual/            images/          stone-harbor/    stories/
_next/           global.scss      minimal/         stone-harbor-pt/ styles/
`}
                </SyntaxHighlighter>

                    Note that each story is containined in a subdirectory containing an{' '}
                    index.html file. The easiest way to deploy a Windrift instance is
                    to copy the entire out folder to a bucket in Amazon S3, to use
                    Github Pages, or copy to any HTML-based hosting environment.

                    Don't just copy the single HTML file for your story—the actual source code is
                    contained in the _next/ folder at the top of the tree. Any images
                    or CSS will also be at the root of the out folder. If you need to
                    output the JavaScript at a different location, you can modify{' '}
                    next.config.js at the root of the Windrift installation to use a
                    different assetPath, but this will not affect images or other
                    static assets. (Unfortunately the NextJS options for fine-grained control over
                    exported static asset paths are{' '}
                    somewhat limited—you
                    may be better off doing a post-hoc transformation of the generated HTML.)

                    More information on the options and limitations of static output can be found in
                    the{' '}

                        NextJS static HTML export
                    {' '}
                    page.

Hosting with itch.io

                    At the moment the file structure output by NextJS's static export is
                    incompatible with itch.io's{' '}
                    requirements for HTML games. A
                    workaround commonly suggested by other React game developers is to host your
                    exported story on something like Github Pages, then on itch.io upload an HTML
                    file that contains just an iframe to your hosted story on Github.

Deploying with dynamic content

                    One of NextJS's strengths is that it allows React developers to easily mix
                    server-side dynamic content with static, front-end-only content. Though not
                    covered in this version of the manual, NextJS provides tools for building rich
                    server-side APIs which can be used to connect to backend databases, talk to
                    third-party APIs, or procedurally generate content in real time.

                    Future versions of Windrift will directly support server-side tooling, but
                    stories that use these features won't be able to use purely static export
                    processes. Fortunately, NextJS has wide support in the ecosystem, so it should
                    be straightforward to find documentation on how to deploy a NextJS app on AWS,
                    Google Cloud, or "serverless" backends like Netlify or Serverless.com.

Hosting with Vercel

                    By far the most straightforward hosting mechanism for any NextJS application is
                    to use the hosting site Vercel, which is run by
                    the same company that produces NextJS itself. (This manual is itself hosted on
                    Vercel at windrift.app.) Hosting with
                    Vercel is free, well-documented, and provides many other benefits including use
                    of NextJS's server-side features. However, Vercel may not exist forever, so it
                    is always desirable to use purely static exports for longevity and inclusion on
                    sites like the IF Archive, assuming the
                    story itself allows for this option.

                        Consult the NextJS documentation
                    {' '}
                    for the most current instructions on deploying with Vercel.

                <FooterNav text="How to write in Markdown..." next="writing-in-md.mdx" />

        </Chapter>
    )
}


text:
'use strict';

var unified = require('unified');
var parse = require('remark-parse');
var remark2rehype = require('remark-rehype');
var raw = require('rehype-raw');
var stringify = require('rehype-stringify');

module.exports = unified()
  .use(parse)
  .use(remark2rehype, {allowDangerousHTML: true})
  .use(raw)
  .use(stringify)
  .freeze();


text:
package nl.xillio.migrationtool.dialogs;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeItem;
import javafx.util.Pair;
import me.biesaart.utils.Log;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

/**
 * A dialog to remove an item in the project view.
 */
public class RenameDialog extends FXMLDialog {
    private static final Logger LOGGER = Log.get();

    @FXML
    private TextField tfname;

    private final TreeItem<Pair<File, String>> treeItem;

    /**
     * Default constructor.
     *
     * @param treeItem the tree item on which the item will be deleted
     */
    public RenameDialog(final TreeItem<Pair<File, String>> treeItem) {
        super("/fxml/dialogs/Rename.fxml");
        this.treeItem = treeItem;
        setTitle("Rename");
        tfname.setText(this.treeItem.getValue().getKey().getName());
    }

    @FXML
    private void cancelBtnPressed(final ActionEvent event) {
        close();
    }

    @FXML
    private void okayBtnPressed(final ActionEvent event) {
        // Get the old file, new file name and new file.
        final File oldFile = treeItem.getValue().getKey();
        String fileName = tfname.getText();

        // If the file is renamed without extension, add the old extension.
        String oldExtension = FilenameUtils.getExtension(oldFile.toString());
        if (oldFile.isFile() && FilenameUtils.getExtension(fileName).isEmpty()) {
            fileName += "." + oldExtension;
        }

        final File newFile = new File(oldFile.getParent(), fileName);
        try {
            // Rename the item and update the tree item.
            Files.move(oldFile.toPath(), newFile.toPath(), StandardCopyOption.ATOMIC_MOVE);
            treeItem.setValue(new Pair<>(newFile, tfname.getText()));
            close();
        } catch (IOException e) {
            LOGGER.error("IOException while renaming file.", e);
            new AlertDialog(Alert.AlertType.ERROR, "Failed to rename file/folder", "",
                    "Something went wrong while renaming a file/folder.\n" + e.getMessage()).showAndWait();
        }
    }
}


text:
<?xml version="1.0" ?>
<INPUT>

	<MEDALS>
		<MEDAL Id="1" MEDAL_THRESHOLD="45000" TYPE="Gold"/>
		<MEDAL Id="2" MEDAL_THRESHOLD="69000" TYPE="Silver"/>
		<MEDAL Id="3" MEDAL_THRESHOLD="89000" TYPE="Bronze"/>

	</MEDALS>

	<SpeedSettings Default="18" Max="150" Min="0"/>

	<PenaltySettings SpeedLost="0.1" TimeLost="15"/>

	<PROBLEM_SET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="4" numerator="6"/>
			</TARGET>
			<QUESTION INDEX="1">
				<Content TYPE="String">
					<ContentSettings string="2"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="2.25"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="2">
				<Content TYPE="String">
					<ContentSettings string="0"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="3">
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="2"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="10" numerator="1"/>
			</TARGET>
			<QUESTION INDEX="4">
				<Content TYPE="String">
					<ContentSettings string="0.7"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="5">
				<Content TYPE="String">
					<ContentSettings string="0"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.9"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="6">
				<Content TYPE="String">
					<ContentSettings string="0.6"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="100" numerator="41"/>
			</TARGET>
			<QUESTION INDEX="7">
				<Content TYPE="String">
					<ContentSettings string="0.16"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.72"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="8">
				<Content TYPE="String">
					<ContentSettings string="0.34"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.8"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="9">
				<Content TYPE="String">
					<ContentSettings string="0.11"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="0.33"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="8" numerator="13"/>
			</TARGET>
			<QUESTION INDEX="10">
				<Content TYPE="String">
					<ContentSettings string="0.375"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.25"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="11">
				<Content TYPE="String">
					<ContentSettings string="1.875"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="2"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="12">
				<Content TYPE="String">
					<ContentSettings string="0.375"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="3" numerator="1"/>
			</TARGET>
			<QUESTION INDEX="13">
				<Content TYPE="String">
					<ContentSettings string="0"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Answer VALUE="1"/>
			</QUESTION>
			<QUESTION INDEX="14">
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.333"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="15">
				<Content TYPE="String">
					<ContentSettings string="0.666"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
		</PROBLEM_SUBSET>
		<PROBLEM_SUBSET>
			<TARGET TYPE="Fraction">
				<ContentSettings denominator="10" numerator="16"/>
			</TARGET>
			<QUESTION INDEX="16">
				<Content TYPE="String">
					<ContentSettings string="2"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="2.1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
			<QUESTION INDEX="17">
				<Content TYPE="String">
					<ContentSettings string="0.4"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="1.5"/>
				</Content>
				<Answer VALUE="2"/>
			</QUESTION>
			<QUESTION INDEX="18">
				<Content TYPE="String">
					<ContentSettings string="2"/>
				</Content>
				<Content TYPE="String">
					<ContentSettings string="2.1"/>
				</Content>
				<Answer VALUE="0"/>
			</QUESTION>
		</PROBLEM_SUBSET>

	</PROBLEM_SET>

</INPUT>


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!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/html; charset=UTF-8" />
    <title>cpuprc</title>
    <link rel="stylesheet" type="text/css" href="csound.css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.78.1" />
    <link rel="home" href="index.html" title="Manuel de référence canonique de Csound" />
    <link rel="up" href="OpcodesTop.html" title="Opcodes et opérateurs de l'orchestre" />
    <link rel="prev" href="cpumeter.html" title="cpumeter" />
    <link rel="next" href="cross2.html" title="cross2" />

          cpuprc

          Précédent
          Opcodes et opérateurs de l'orchestre
           Suivant

          cpuprc

cpuprc —
      Contrôle l'allocation des ressources cpu par instrument, pour optimiser la sortie
      en temps réel.

Description

      Contrôle l'allocation des ressources cpu par instrument, pour optimiser la sortie
      en temps réel.

Syntaxe

cpuprc insnum, ipercent

cpuprc Sinsname, ipercent

Initialisation

      insnum -- numéro de l'instrument

      Sinsname -- nom de l'instrument

      ipercent -- pourcentage du temps de traitement cpu à allouer.
      On peut aussi l'exprimer sous forme fractionnaire.

Exécution

      cpuprc fixe le pourcentage du temps de traitement cpu
      utilisé par un instrument, afin d'éviter un sous-remplissage du tampon dans
      les exécutions en temps réel. L'utilisateur doit fixer la valeur de
      ipercent pour chaque instrument qui sera activé en temps
      réel. En supposant que le temps de traitement cpu total soit 1OO% en théorie,
      cette valeur de pourcentage ne peut être définie qu'empiriquement, car il y
      a trop de facteurs qui contribuent à limiter la polyphonie en temps réel sur
      différents ordinateurs.

      Par exemple si ipercent est fixé à 5% pour l'instrument 1,
      le nombre maximum de voix que l'on pourra allouer en temps réel est 20
      (5% * 20 = 100%). Si l'on essaye de jouer une note supplémentaire alors que les
      20 notes précédentes sont toujours jouées, Csound empêche l'allocation de cette
      note et affiche le message d'avertissement suivant :

impossible d'allouer la dernière note car il n'y a plus de temps cpu disponible

      Afin d'éviter les sous-remplissages de tampon audio, il est suggéré de fixer
      le nombre maximum de voix à une valeur légèrement inférieure à la puissance
      de traitement réelle de l'ordinateur. Parfois, un instrument peut avoir besoin
      de plus de temps de traitement que la normale. Si, par exemple, l'instrument
      contient un oscillateur qui lit une table trop grande pour la mémoire cache,
      il sera plus lent qu'en temps normal. De plus, chaque programme s'exécutant
      concuramment dans l'environnement multitâche, peut consommer de la puissance
      processeur à divers degrés.

      Au début, tous les instruments reçoivent une valeur par défaut de
      ipercent égale à 0.0% (c'est-à-dire un temps de traitement
      nul équivalent à une vitesse de processeur infinie). Ce réglage convient très
      bien pour les sessions en temps différé.

      Toutes les instances de cpuprc doivent être définies dans
      la section d'en-tête et non dans le corps de l'instrument.

Exemples

      Voici un exemple de l'opcode cpuprc. Il utilise le fichier
      cpuprc.csd.

            Exemple 167. Exemple de l'opcode cpuprc.

Voir les sections Audio en Temps Réel
        et Options de la Ligne de Commande pour plus
        d'information sur l'utilisation des options de la ligne de commande.

<CsoundSynthesizer>
<CsOptions>
; Select audio/midi flags here according to platform
-odac     ;;;realtime audio out
;-iadc    ;;;uncomment -iadc if realtime audio input is needed too
; For Non-realtime ouput leave only the line below:
; -o cpuprc.wav -W ;;; for file output any platform
</CsOptions>
<CsInstruments>

sr = 44100
ksmps = 32
nchnls = 2
0dbfs  = 1

cpuprc 1, 2
cpuprc 2, 30

instr 1 ;cpu processing-time percent usage is set to 2% for each note

asig oscil 0.2, 440, 1
     outs asig, asig

endin

instr 2	;cpu processing-time percent usage is set to 30% for each note
	;so the 4 notes of the score exceeds 100% by far
asig oscil 0.2, 440, 1
     outs asig, asig

endin
</CsInstruments>
<CsScore>
f 1 0 32768 10 1	; sine wave

i 1 0 1
i 1 0 1
i 1 0 1
i 1 0 1

;too many notes to process,
;check Csound output!
i 2 3 1
i 2 3 1
i 2 3 1
i 2 3 1
e
</CsScore>
</CsoundSynthesizer>

Voir aussi

      maxalloc,
      prealloc

Crédits

            Auteur : Gabriel Maldonado

            Italie

            Juillet 1999

Nouveau dans la version 3.57 de Csound ; ajout des instruments nommés
    dans la version 5.13

          Précédent

            Niveau supérieur

           Suivant

          cpumeter

            Sommaire

           cross2


text:
module Yammer
  class Base
    def initialize(options = {})
      client_options = {
        :site => options.delete(:yammer_url) || 'https://www.yammer.com'
      }

      @api_path   = '/api/v1/'

      options[:consumer] = {} unless options[:consumer]
      options[:access] = {} unless options[:access]

      consumer = OAuth::Consumer.new(options[:consumer][:key], options[:consumer][:secret], client_options)
      client.http.set_debug_output($stderr) if options[:verbose] == true
      @access_token = OAuth::AccessToken.new(consumer, options[:access][:token], options[:access][:secret])
    end

    private
      def yammer_request(http_method, options)
        request_uri = @api_path + options.delete(:resource).to_s
        [:action, :id].each {|k| request_uri += "/#{options.delete(k)}" if options.has_key?(k) }
        request_uri += ".json"

        request_uri += "?access_token=#{options.delete(:access_token)}" if options[:access_token]

        if options.any?
          request_uri += request_uri.include?('?') ? '&' : '?'
          request_uri += "#{create_query_string(options)}" unless http_method == :post
        end

        if http_method == :post
          handle_response(@access_token.send(http_method, request_uri, options))
        else
          handle_response(@access_token.send(http_method, request_uri))
        end
      end

      def create_query_string(options)
        options.map {|k, v| "#{OAuth::Helper.escape(k)}=#{OAuth::Helper.escape(v)}"}.join('&')
      end

      def handle_response(response)
        case response.code.to_i
        when 200..201
          response
        else
          raise "Error. HTTP Response #{response.code}"
        end
      end
  end
end


text:
package org.apache.pdfbox.pdmodel.font;

import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.pdmodel.common.COSObjectable;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.common.PDStream;

/**
 * A font descriptor.
 *
 * @author Ben Litchfield
 */
public final class PDFontDescriptor implements COSObjectable
{
    private static final int FLAG_FIXED_PITCH = 1;
    private static final int FLAG_SERIF = 2;
    private static final int FLAG_SYMBOLIC = 4;
    private static final int FLAG_SCRIPT = 8;
    private static final int FLAG_NON_SYMBOLIC = 32;
    private static final int FLAG_ITALIC = 64;
    private static final int FLAG_ALL_CAP = 65536;
    private static final int FLAG_SMALL_CAP = 131072;
    private static final int FLAG_FORCE_BOLD = 262144;

    private final COSDictionary dic;
    private float xHeight = Float.NEGATIVE_INFINITY;
    private float capHeight = Float.NEGATIVE_INFINITY;
    private int flags = -1;

    /**
     * Package-private constructor, for embedding.
     */
    PDFontDescriptor()
    {
        dic = new COSDictionary();
        dic.setItem( COSName.TYPE, COSName.FONT_DESC );
    }

    /**
     * Creates a PDFontDescriptor from a COS dictionary.
     *
     * @param desc The wrapped COS Dictionary.
     */
    public PDFontDescriptor( COSDictionary desc )
    {
        dic = desc;
    }

    /**
     * A convenience method that checks the flag bit.
     *
     * @return The flag value.
     */
    public boolean isFixedPitch()
    {
        return isFlagBitOn( FLAG_FIXED_PITCH );
    }

    /**
     * A convenience method that sets the flag bit.
     *
     * @param flag The flag value.
     */
    public void setFixedPitch( boolean flag )
    {
        setFlagBit( FLAG_FIXED_PITCH, flag );
    }

    /**
     * A convenience method that checks the flag bit.
     *
     * @return The flag value.
     */
    public boolean isSerif()
    {
        return isFlagBitOn( FLAG_SERIF );
    }

    /**
     * A convenience method that sets the flag bit.
     *
     * @param flag The flag value.
     */
    public void setSerif( boolean flag )
    {
        setFlagBit( FLAG_SERIF, flag );
    }

    /**
     * A convenience method that checks the flag bit.
     *
     * @return The flag value.
     */
    public boolean isSymbolic()
    {
        return isFlagBitOn( FLAG_SYMBOLIC );
    }

    /**
     * A convenience method that sets the flag bit.
     *
     * @param flag The flag value.
     */
    public void setSymbolic( boolean flag )
    {
        setFlagBit( FLAG_SYMBOLIC, flag );
    }

    /**
     * A convenience method that checks the flag bit.
     *
     * @return The flag value.
     */
    public boolean isScript()
    {
        return isFlagBitOn( FLAG_SCRIPT );
    }

    /**
     * A convenience method that sets the flag bit.
     *
     * @param flag The flag value.
     */
    public void setScript( boolean flag )
    {
        setFlagBit( FLAG_SCRIPT, flag );
    }

    /**
     * A convenience method that checks the flag bit.
     *
     * @return The flag value.
     */
    public boolean isNonSymbolic()
    {
        return isFlagBitOn( FLAG_NON_SYMBOLIC );
    }

    /**
     * A convenience method that sets the flag bit.
     *
     * @param flag The flag value.
     */
    public void setNonSymbolic( boolean flag )
    {
        setFlagBit( FLAG_NON_SYMBOLIC, flag );
    }

    /**
     * A convenience method that checks the flag bit.
     *
     * @return The flag value.
     */
    public boolean isItalic()
    {
        return isFlagBitOn( FLAG_ITALIC );
    }

    /**
     * A convenience method that sets the flag bit.
     *
     * @param flag The flag value.
     */
    public void setItalic( boolean flag )
    {
        setFlagBit( FLAG_ITALIC, flag );
    }

    /**
     * A convenience method that checks the flag bit.
     *
     * @return The flag value.
     */
    public boolean isAllCap()
    {
        return isFlagBitOn( FLAG_ALL_CAP);
    }

    /**
     * A convenience method that sets the flag bit.
     *
     * @param flag The flag value.
     */
    public void setAllCap( boolean flag )
    {
        setFlagBit( FLAG_ALL_CAP, flag );
    }

    /**
     * A convenience method that checks the flag bit.
     *
     * @return The flag value.
     */
    public boolean isSmallCap()
    {
        return isFlagBitOn( FLAG_SMALL_CAP );
    }

    /**
     * A convenience method that sets the flag bit.
     *
     * @param flag The flag value.
     */
    public void setSmallCap( boolean flag )
    {
        setFlagBit( FLAG_SMALL_CAP, flag );
    }

    /**
     * A convenience method that checks the flag bit.
     *
     * @return The flag value.
     */
    public boolean isForceBold()
    {
        return isFlagBitOn( FLAG_FORCE_BOLD );
    }

    /**
     * A convenience method that sets the flag bit.
     *
     * @param flag The flag value.
     */
    public void setForceBold( boolean flag )
    {
        setFlagBit( FLAG_FORCE_BOLD, flag );
    }

    private boolean isFlagBitOn( int bit )
    {
        return (getFlags() & bit) != 0;
    }

    private void setFlagBit( int bit, boolean value )
    {
        int flags = getFlags();
        if( value )
        {
            flags = flags | bit;
        }
        else
        {
            flags = flags & (0xFFFFFFFF ^ bit);
        }
        setFlags( flags );
    }

    /**
     * Convert this standard java object to a COS object.
     *
     * @return The cos object that matches this Java object.
     */
    public COSDictionary getCOSObject()
    {
        return dic;
    }

    /**
     * Get the font name.
     *
     * @return The name of the font.
     */
    public String getFontName()
    {
        String retval = null;
        COSName name = (COSName)dic.getDictionaryObject( COSName.FONT_NAME );
        if( name != null )
        {
            retval = name.getName();
        }
        return retval;
    }

    /**
     * This will set the font name.
     *
     * @param fontName The new name for the font.
     */
    public void setFontName( String fontName )
    {
        COSName name = null;
        if( fontName != null )
        {
            name = COSName.getPDFName( fontName );
        }
        dic.setItem( COSName.FONT_NAME, name );
    }

    /**
     * A string representing the preferred font family.
     *
     * @return The font family.
     */
    public String getFontFamily()
    {
        String retval = null;
        COSString name = (COSString)dic.getDictionaryObject( COSName.FONT_FAMILY );
        if( name != null )
        {
            retval = name.getString();
        }
        return retval;
    }

    /**
     * This will set the font family.
     *
     * @param fontFamily The font family.
     */
    public void setFontFamily( String fontFamily )
    {
        COSString name = null;
        if( fontFamily != null )
        {
            name = new COSString( fontFamily );
        }
        dic.setItem( COSName.FONT_FAMILY, name );
    }

    /**
     * The weight of the font.  According to the PDF spec "possible values are
     * 100, 200, 300, 400, 500, 600, 700, 800 or 900"  Where a higher number is
     * more weight and appears to be more bold.
     *
     * @return The font weight.
     */
    public float getFontWeight()
    {
        return dic.getFloat( COSName.FONT_WEIGHT,0 );
    }

    /**
     * Set the weight of the font.
     *
     * @param fontWeight The new weight of the font.
     */
    public void setFontWeight( float fontWeight )
    {
        dic.setFloat( COSName.FONT_WEIGHT, fontWeight );
    }

    /**
     * A string representing the preferred font stretch.
     * According to the PDF Spec:
     * The font stretch value; it must be one of the following (ordered from
     * narrowest to widest): UltraCondensed, ExtraCondensed, Condensed, SemiCondensed,
     * Normal, SemiExpanded, Expanded, ExtraExpanded or UltraExpanded.
     *
     * @return The stretch of the font.
     */
    public String getFontStretch()
    {
        String retval = null;
        COSName name = (COSName)dic.getDictionaryObject( COSName.FONT_STRETCH );
        if( name != null )
        {
            retval = name.getName();
        }
        return retval;
    }

    /**
     * This will set the font stretch.
     *
     * @param fontStretch The new stretch for the font.
     */
    public void setFontStretch( String fontStretch )
    {
        COSName name = null;
        if( fontStretch != null )
        {
            name = COSName.getPDFName( fontStretch );
        }
        dic.setItem( COSName.FONT_STRETCH, name );
    }

    /**
     * This will get the font flags.
     *
     * @return The font flags.
     */
    public int getFlags()
    {
        if (flags == -1)
        {
            flags = dic.getInt( COSName.FLAGS, 0 );
        }
        return flags;
    }

    /**
     * This will set the font flags.
     *
     * @param flags The new font flags.
     */
    public void setFlags( int flags )
    {
        dic.setInt( COSName.FLAGS, flags );
        this.flags = flags;
    }

    /**
     * This will get the fonts bounding box.
     *
     * @return The fonts bounding box.
     */
    public PDRectangle getFontBoundingBox()
    {
        COSArray rect = (COSArray)dic.getDictionaryObject( COSName.FONT_BBOX );
        PDRectangle retval = null;
        if( rect != null )
        {
            retval = new PDRectangle( rect );
        }
        return retval;
    }

    /**
     * Set the fonts bounding box.
     *
     * @param rect The new bouding box.
     */
    public void setFontBoundingBox( PDRectangle rect )
    {
        COSArray array = null;
        if( rect != null )
        {
            array = rect.getCOSArray();
        }
        dic.setItem( COSName.FONT_BBOX, array );
    }

    /**
     * This will get the italic angle for the font.
     *
     * @return The italic angle.
     */
    public float getItalicAngle()
    {
        return dic.getFloat( COSName.ITALIC_ANGLE, 0 );
    }

    /**
     * This will set the italic angle for the font.
     *
     * @param angle The new italic angle for the font.
     */
    public void setItalicAngle( float angle )
    {
        dic.setFloat( COSName.ITALIC_ANGLE, angle );
    }

    /**
     * This will get the ascent for the font.
     *
     * @return The ascent.
     */
    public float getAscent()
    {
        return dic.getFloat( COSName.ASCENT, 0 );
    }

    /**
     * This will set the ascent for the font.
     *
     * @param ascent The new ascent for the font.
     */
    public void setAscent( float ascent )
    {
        dic.setFloat( COSName.ASCENT, ascent );
    }

    /**
     * This will get the descent for the font.
     *
     * @return The descent.
     */
    public float getDescent()
    {
        return dic.getFloat( COSName.DESCENT, 0 );
    }

    /**
     * This will set the descent for the font.
     *
     * @param descent The new descent for the font.
     */
    public void setDescent( float descent )
    {
        dic.setFloat( COSName.DESCENT, descent );
    }

    /**
     * This will get the leading for the font.
     *
     * @return The leading.
     */
    public float getLeading()
    {
        return dic.getFloat( COSName.LEADING, 0 );
    }

    /**
     * This will set the leading for the font.
     *
     * @param leading The new leading for the font.
     */
    public void setLeading( float leading )
    {
        dic.setFloat( COSName.LEADING, leading );
    }

    /**
     * This will get the CapHeight for the font.
     *
     * @return The cap height.
     */
    public float getCapHeight()
    {
        if(capHeight==Float.NEGATIVE_INFINITY)
        {
            /* We observed a negative value being returned with
             * the Scheherazade font. PDFBOX-429 was logged for this.
             * We are not sure if returning the absolute value
             * is the correct fix, but it seems to work.  */
            capHeight = java.lang.Math.abs(dic.getFloat( COSName.CAP_HEIGHT, 0 ));
        }
        return capHeight;
    }

    /**
     * This will set the cap height for the font.
     *
     * @param capHeight The new cap height for the font.
     */
    public void setCapHeight( float capHeight )
    {
        dic.setFloat( COSName.CAP_HEIGHT, capHeight );
        this.capHeight = capHeight;
    }

    /**
     * This will get the x height for the font.
     *
     * @return The x height.
     */
    public float getXHeight()
    {
        if(xHeight==Float.NEGATIVE_INFINITY)
        {
            /* We observed a negative value being returned with
             * the Scheherazade font. PDFBOX-429 was logged for this.
             * We are not sure if returning the absolute value
             * is the correct fix, but it seems to work.  */
            xHeight = java.lang.Math.abs(dic.getFloat( COSName.XHEIGHT, 0 ));
        }
        return xHeight;
    }

    /**
     * This will set the x height for the font.
     *
     * @param xHeight The new x height for the font.
     */
    public void setXHeight( float xHeight )
    {
        dic.setFloat( COSName.XHEIGHT, xHeight );
        this.xHeight = xHeight;
    }

    /**
     * This will get the stemV for the font.
     *
     * @return The stem v value.
     */
    public float getStemV()
    {
        return dic.getFloat( COSName.STEM_V, 0 );
    }

    /**
     * This will set the stem V for the font.
     *
     * @param stemV The new stem v for the font.
     */
    public void setStemV( float stemV )
    {
        dic.setFloat( COSName.STEM_V, stemV );
    }

    /**
     * This will get the stemH for the font.
     *
     * @return The stem h value.
     */
    public float getStemH()
    {
        return dic.getFloat( COSName.STEM_H, 0 );
    }

    /**
     * This will set the stem H for the font.
     *
     * @param stemH The new stem h for the font.
     */
    public void setStemH( float stemH )
    {
        dic.setFloat( COSName.STEM_H, stemH );
    }

    /**
     * This will get the average width for the font.
     *
     * @return The average width value.
     */
    public float getAverageWidth()
    {
        return dic.getFloat( COSName.AVG_WIDTH, 0 );
    }

    /**
     * This will set the average width for the font.
     *
     * @param averageWidth The new average width for the font.
     */
    public void setAverageWidth( float averageWidth )
    {
        dic.setFloat( COSName.AVG_WIDTH, averageWidth );
    }

    /**
     * This will get the max width for the font.
     *
     * @return The max width value.
     */
    public float getMaxWidth()
    {
        return dic.getFloat( COSName.MAX_WIDTH, 0 );
    }

    /**
     * This will set the max width for the font.
     *
     * @param maxWidth The new max width for the font.
     */
    public void setMaxWidth( float maxWidth )
    {
        dic.setFloat( COSName.MAX_WIDTH, maxWidth );
    }

    /**
     * Returns true if widths are present in the font descriptor.
     */
    public boolean hasWidths()
    {
        return dic.containsKey(COSName.WIDTHS) || dic.containsKey(COSName.MISSING_WIDTH);
    }

    /**
     * This will get the missing width for the font.
     *
     * @return The missing width value.
     */
    public float getMissingWidth()
    {
        return dic.getFloat( COSName.MISSING_WIDTH, 0 );
    }

    /**
     * This will set the missing width for the font.
     *
     * @param missingWidth The new missing width for the font.
     */
    public void setMissingWidth( float missingWidth )
    {
        dic.setFloat( COSName.MISSING_WIDTH, missingWidth );
    }

    /**
     * This will get the character set for the font.
     *
     * @return The character set value.
     */
    public String getCharSet()
    {
        String retval = null;
        COSString name = (COSString)dic.getDictionaryObject( COSName.CHAR_SET );
        if( name != null )
        {
            retval = name.getString();
        }
        return retval;
    }

    /**
     * This will set the character set for the font.
     *
     * @param charSet The new character set for the font.
     */
    public void setCharacterSet( String charSet )
    {
        COSString name = null;
        if( charSet != null )
        {
            name = new COSString( charSet );
        }
        dic.setItem( COSName.CHAR_SET, name );
    }

    /**
     * A stream containing a Type 1 font program.
     *
     * @return A stream containing a Type 1 font program.
     */
    public PDStream getFontFile()
    {
        PDStream retval = null;
        COSBase obj = dic.getDictionaryObject(COSName.FONT_FILE);
        if(obj instanceof COSStream)
        {
            retval = new PDStream( (COSStream)obj );
        }
        return retval;
    }

    /**
     * Set the type 1 font program.
     *
     * @param type1Stream The type 1 stream.
     */
    public void setFontFile( PDStream type1Stream )
    {
        dic.setItem( COSName.FONT_FILE, type1Stream );
    }

    /**
     * A stream containing a true type font program.
     *
     * @return A stream containing a true type font program.
     */
    public PDStream getFontFile2()
    {
        PDStream retval = null;
        COSBase obj = dic.getDictionaryObject(COSName.FONT_FILE2);
        if(obj instanceof COSStream)
        {
            retval = new PDStream((COSStream)obj);
        }
        return retval;
    }

    /**
     * Set the true type font program.
     *
     * @param ttfStream The true type stream.
     */
    public void setFontFile2( PDStream ttfStream )
    {
        dic.setItem( COSName.FONT_FILE2, ttfStream );
    }

    /**
     * A stream containing a font program that is not true type or type 1.
     *
     * @return A stream containing a font program.
     */
    public PDStream getFontFile3()
    {
        PDStream retval = null;
        COSBase obj = dic.getDictionaryObject(COSName.FONT_FILE3);
        if(obj instanceof COSStream)
        {
            retval = new PDStream((COSStream)obj);
        }
        return retval;
    }

    /**
     * Set a stream containing a font program that is not true type or type 1.
     *
     * @param stream The font program stream.
     */
    public void setFontFile3( PDStream stream )
    {
        dic.setItem( COSName.FONT_FILE3, stream );
    }

    /**
     * Set a stream containing a CIDSet.
     *
     * @param stream The font program stream.
     */
    public void setCIDSet( PDStream stream )
    {
    	dic.setItem( COSName.CID_SET, stream );
    }
}


text:
/*************************
*   Precompiled Header   *
**************************/
#include "precomp_editor.h"

/**********************
*   System Includes   *
***********************/

/*************************
*   3rd Party Includes   *
**************************/

/***************************
*   Game Engine Includes   *
****************************/
#include "UI/UIDefs.h"
#include "UIMainMenu.h"
#include "ImGuiManager.h"
#include "ImGuiMainMenu.h"
#include "UI/Main Menu/UIFileMenu.h"
#include "UI/Main Menu/UIViewMenu.h"

//Always include last
#include "Memory\MemLeaks.h"

/********************
*   Function Defs   *
*********************/

UIMainMenu::UIMainMenu(ImGuiManager& imGuiManager)
    : m_ImGuiManager(imGuiManager)
    , m_ImGuiMainMenu(imGuiManager.GetImGuiMainMenu())
{
}

UIMainMenu::~UIMainMenu()
{
    DeleteMem(m_FileMenu);
    DeleteMem(m_ViewMenu);
}

void UIMainMenu::AddEditorMenus()
{
    m_FileMenu = new UIFileMenu(m_ImGuiManager, AE_UI_FILE_MENU_PRIORITY);
    m_FileMenu->Initialize();
    m_ImGuiMainMenu.AddMenuObject(m_FileMenu);

    m_ViewMenu = new UIViewMenu(m_ImGuiManager, AE_UI_VIEW_MENU_PRIORITY);
    m_ViewMenu->Initialize();
    m_ImGuiMainMenu.AddMenuObject(m_ViewMenu);
}


text:
    <umb-load-indicator ng-if="vm.page.loading"></umb-load-indicator>

    <form name="contentForm"
          ng-submit="vm.save()"
          novalidate
          val-form-manager>
        <umb-editor-view ng-if="!vm.page.loading">
            <umb-editor-header
                menu="vm.page.menu"
                name="vm.content.name"
                name-locked="vm.page.nameLocked"
                hide-icon="true"
                hide-description="true"
                hide-alias="true">
            </umb-editor-header>

            <umb-editor-container class="form-horizontal">

                <umb-property ng-repeat="translation in vm.content.translations" property="translation.property">
                    <textarea ng-model="translation.translation"></textarea>
                </umb-property>
            </umb-editor-container>

            <umb-editor-footer>

                <umb-editor-footer-content-right>

                    <umb-button
                        type="submit"
                        button-style="success"
                        state="vm.page.saveButtonState"
                        shortcut="ctrl+s"
                        label="Save"
                        label-key="buttons_save">
                    </umb-button>

                </umb-editor-footer-content-right>

            </umb-editor-footer>
        </umb-editor-view>
    </form>


text:
package org.kaazing.nuklei.echo.internal.streams;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.rules.RuleChain.outerRule;
import static uk.co.real_logic.agrona.IoUtil.createEmptyFile;

import java.io.File;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.DisableOnDebug;
import org.junit.rules.TestRule;
import org.junit.rules.Timeout;
import org.kaazing.k3po.junit.annotation.Specification;
import org.kaazing.k3po.junit.rules.K3poRule;
import org.kaazing.nuklei.test.NukleusRule;

import uk.co.real_logic.agrona.concurrent.ringbuffer.RingBufferDescriptor;

public class ConnectIT
{
    private final K3poRule k3po = new K3poRule()
        .setScriptRoot("org/kaazing/nuklei/specification/echo");

    private final TestRule timeout = new DisableOnDebug(new Timeout(5, SECONDS));

    private final NukleusRule nukleus = new NukleusRule("echo")
        .setDirectory("target/nukleus-itests")
        .setCommandBufferCapacity(1024)
        .setResponseBufferCapacity(1024)
        .setCounterValuesBufferCapacity(1024);

    @Before
    public void setupStreamFiles() throws Exception
    {
        int streamCapacity = 1024 * 1024;

        File destination = new File("target/nukleus-itests/destination/streams/echo");
        createEmptyFile(destination.getAbsoluteFile(), streamCapacity + RingBufferDescriptor.TRAILER_LENGTH);
    }

    @Rule
    public final TestRule chain = outerRule(k3po).around(timeout).around(nukleus);

    @Test
    @Specification({
        "control/connect.destination/controller",
        "streams/connect/establish.connection/destination" })
    public void shouldEstablishConnection() throws Exception
    {
        k3po.finish();
    }

    @Test
    @Specification({
        "control/connect.destination/controller",
        "streams/connect/echo.destination.data/destination" })
    public void shouldEchoDestinationData() throws Exception
    {
        k3po.finish();
    }

    @Test
    @Specification({
        "control/connect.destination/controller",
        "streams/connect/initiate.destination.close/destination" })
    public void shouldInitiateDestinationClose() throws Exception
    {
        k3po.finish();
    }

    @Ignore("TODO: nukleus CLOSE command")
    @Test
    @Specification({
        "control/connect.destination/controller",
        "streams/connect/initiate.nukleus.close/destination" })
    public void shouldInitiateNukleusClose() throws Exception
    {
        k3po.finish();
    }
}


text:
//Copyright (c) Microsoft Corporation.  All rights reserved.

namespace Microsoft.WindowsAPI.Taskbar
{

    internal enum TaskbarProxyWindowType
    {
        TabbedThumbnail,
        ThumbnailToolbar,
    }

    /// <summary>
    /// Known category to display
    /// </summary>
    public enum JumpListKnownCategoryType
    {
        /// <summary>
        /// Don't display either known category. You must have at least one
        /// user task or custom category link in order to not see the
        /// default 'Recent' known category
        /// </summary>
        Neither = 0,

        /// <summary>
        /// Display the 'Recent' known category
        /// </summary>
        Recent,

        /// <summary>
        /// Display the 'Frequent' known category
        /// </summary>
        Frequent,
    }

    /// <summary>
    /// Represents the thumbnail progress bar state.
    /// </summary>
    public enum TaskbarProgressBarState
    {
        /// <summary>
        /// No progress is displayed.
        /// </summary>
        NoProgress = 0,

        /// <summary>
        /// The progress is indeterminate (marquee).
        /// </summary>
        Indeterminate = 0x1,

        /// <summary>
        /// Normal progress is displayed.
        /// </summary>
        Normal = 0x2,

        /// <summary>
        /// An error occurred (red).
        /// </summary>
        Error = 0x4,

        /// <summary>
        /// The operation is paused (yellow).
        /// </summary>
        Paused = 0x8
    }
}


text:
#!/bin/bash

defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false
defaults write NSGlobalDomain KeyRepeat -int 1
defaults write NSGlobalDomain InitialKeyRepeat -int 10
chflags nohidden ~/Library
mkdir ~/Desktop/Screenshots
defaults write com.apple.screencapture location ~/Desktop/Screenshots

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
curl -s https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
brew update && brew upgrade

brew install automake colordiff curl git
brew install hub libmemcached memcached openssl
brew cask install iterm2
brew cask install firefox
brew cask install google
brew cask install opera

brew cask install sublime-text
brew cask install filezilla
brew cask install virtualbox
brew cask install axure-rp
brew cask install sequel-pro
brew cask install mysqlworkbench
brew cask install tunnelblick

xcode-select --install
brew install node
sudo npm install -g phonegap
sudo npm install -g cordova
brew install ant watchman
sudo npm install -g react-native-cli

brew cask install java
brew install maven
brew install gradle
brew install android-sdk
brew install android-ndk
android update sdk --no-ui
brew cask install android-studio

brew install imagemagick ffmpeg
npm install -g bower

brew cask install vagrant
brew cask install vagrant-manager
vagrant plugin install vagrant-parallels
brew install ansible
brew install docker boot2docker
brew cask install docker-compose

brew install v8
sudo gem install therubyracer
sudo gem install libv8 -v 3.16.14.3 -- --with-system-v8

brew cask install alfred
brew cask install skype
brew cask install spotify

brew install mysql
brew pin mysql

brew tap homebrew/services; brew tap homebrew/dupes
brew install php71 --with-fpm --without-apache; php -v; php-fpm -v
brew services start php71

brew install nginx; brew services start nginx
echo 'Nginx configuration is in : /usr/local/etc/nginx';
echo 'export PATH="/usr/local/sbin:$PATH"' >> ~/.bash_profile && . ~/.bash_profile
mkdir -p ~/Library/LaunchAgents
ln -sfv /usr/local/opt/php71/homebrew.mxcl.php71.plist ~/Library/LaunchAgents/
launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.php71.plist
sudo cp -v /usr/local/opt/nginx/*.plist /Library/LaunchDaemons/
sudo chown root:wheel /Library/LaunchDaemons/homebrew.mxcl.nginx.plist
sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.nginx.plist

mkdir -p /usr/local/etc/nginx/logs
mkdir -p /usr/local/etc/nginx/sites-available
mkdir -p /usr/local/etc/nginx/sites-enabled
mkdir -p /usr/local/etc/nginx/conf.d
mkdir -p /usr/local/etc/nginx/ssl

cp /usr/local/Cellar/mysql/*/homebrew.mxcl.mysql.plist ~/Library/LaunchAgents/
launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

sudo mkdir -p /var/www
sudo chown :staff /var/www
sudo chmod 775 /var/www
mkdir -p ~/Documents/Development/nativeReact
cd ~/Documents/Development
ln -s /var/www/


text:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSemicolonToken = exports.isOpeningParenToken = exports.isOpeningBracketToken = exports.isOpeningBraceToken = exports.isNotSemicolonToken = exports.isNotOpeningParenToken = exports.isNotOpeningBracketToken = exports.isNotOpeningBraceToken = exports.isNotCommentToken = exports.isNotCommaToken = exports.isNotColonToken = exports.isNotClosingParenToken = exports.isNotClosingBracketToken = exports.isNotClosingBraceToken = exports.isNotArrowToken = exports.isCommentToken = exports.isCommaToken = exports.isColonToken = exports.isClosingParenToken = exports.isClosingBracketToken = exports.isClosingBraceToken = exports.isArrowToken = void 0;
const eslintUtils = __importStar(require("eslint-utils"));
const isArrowToken = eslintUtils.isArrowToken;
exports.isArrowToken = isArrowToken;
const isNotArrowToken = eslintUtils.isNotArrowToken;
exports.isNotArrowToken = isNotArrowToken;
const isClosingBraceToken = eslintUtils.isClosingBraceToken;
exports.isClosingBraceToken = isClosingBraceToken;
const isNotClosingBraceToken = eslintUtils.isNotClosingBraceToken;
exports.isNotClosingBraceToken = isNotClosingBraceToken;
const isClosingBracketToken = eslintUtils.isClosingBracketToken;
exports.isClosingBracketToken = isClosingBracketToken;
const isNotClosingBracketToken = eslintUtils.isNotClosingBracketToken;
exports.isNotClosingBracketToken = isNotClosingBracketToken;
const isClosingParenToken = eslintUtils.isClosingParenToken;
exports.isClosingParenToken = isClosingParenToken;
const isNotClosingParenToken = eslintUtils.isNotClosingParenToken;
exports.isNotClosingParenToken = isNotClosingParenToken;
const isColonToken = eslintUtils.isColonToken;
exports.isColonToken = isColonToken;
const isNotColonToken = eslintUtils.isNotColonToken;
exports.isNotColonToken = isNotColonToken;
const isCommaToken = eslintUtils.isCommaToken;
exports.isCommaToken = isCommaToken;
const isNotCommaToken = eslintUtils.isNotCommaToken;
exports.isNotCommaToken = isNotCommaToken;
const isCommentToken = eslintUtils.isCommentToken;
exports.isCommentToken = isCommentToken;
const isNotCommentToken = eslintUtils.isNotCommentToken;
exports.isNotCommentToken = isNotCommentToken;
const isOpeningBraceToken = eslintUtils.isOpeningBraceToken;
exports.isOpeningBraceToken = isOpeningBraceToken;
const isNotOpeningBraceToken = eslintUtils.isNotOpeningBraceToken;
exports.isNotOpeningBraceToken = isNotOpeningBraceToken;
const isOpeningBracketToken = eslintUtils.isOpeningBracketToken;
exports.isOpeningBracketToken = isOpeningBracketToken;
const isNotOpeningBracketToken = eslintUtils.isNotOpeningBracketToken;
exports.isNotOpeningBracketToken = isNotOpeningBracketToken;
const isOpeningParenToken = eslintUtils.isOpeningParenToken;
exports.isOpeningParenToken = isOpeningParenToken;
const isNotOpeningParenToken = eslintUtils.isNotOpeningParenToken;
exports.isNotOpeningParenToken = isNotOpeningParenToken;
const isSemicolonToken = eslintUtils.isSemicolonToken;
exports.isSemicolonToken = isSemicolonToken;
const isNotSemicolonToken = eslintUtils.isNotSemicolonToken;
exports.isNotSemicolonToken = isNotSemicolonToken;
//# sourceMappingURL=predicates.js.map