text:
module RubyJmeter
  module Nodes
    module Plugins
      # @TODO objProp, collectionProp
      class PerfmonCollector < Nodes::Base
        allowed %i(error_logging server port metric parameters filename interval_grouping graph_aggregated
          include_sample_labels exclude_sample_labels start_offset end_offset include_checkbox_state
          exclude_checkbox_state)

        defaults error_logging: false, interval_grouping: 1000, graph_aggregated: false, include_checkbox_state: false,
          exclude_checkbox_state: false

        def node
          metricNodes = params.collect do |m|
            "
            <collectionProp name=\"\">
              <stringProp name=\"\">#{m[:server]}</stringProp>
              <stringProp name=\"\">#{m[:port]}</stringProp>
              <stringProp name=\"\">#{m[:metric]}</stringProp>
              <stringProp name=\"\">#{m[:parameters]}</stringProp>
            </collectionProp>
          "
          end

          metricConnections = Nokogiri::XML(<<-XML.strip_heredoc)
          <collectionProp name="metricConnections">
              #{metricNodes.join "\n"}
          </collectionProp>
          XML

          Nokogiri::XML(<<-XML.strip_heredoc)
          <kg.apc.jmeter.perfmon.PerfMonCollector guiclass="kg.apc.jmeter.vizualizers.PerfMonGui" testclass="kg.apc.jmeter.perfmon.PerfMonCollector" testname="" enabled="true">
            <boolProp name="ResultCollector.error_logging" />
            <objProp>
              <name>saveConfig</name>
              <value class="SampleSaveConfiguration">
                <time>true</time>
                <latency>true</latency>
                <timestamp>true</timestamp>
                <success>true</success>
                true
                true
                <message>false</message>
                <threadName>true</threadName>
                <dataType>false</dataType>
                <encoding>false</encoding>
                <assertions>false</assertions>
                <subresults>false</subresults>
                <responseData>false</responseData>
                <samplerData>false</samplerData>
                <xml>true</xml>
                <fieldNames>false</fieldNames>
                <responseHeaders>false</responseHeaders>
                <requestHeaders>false</requestHeaders>
                <responseDataOnError>false</responseDataOnError>
                <saveAssertionResultsFailureMessage>false</saveAssertionResultsFailureMessage>
                <assertionsResultsToSave>0</assertionsResultsToSave>
                <bytes>true</bytes>
                <threadCounts>true</threadCounts>
                <sampleCount>true</sampleCount>
              </value>
            </objProp>
            <stringProp name="filename" />
            <longProp name="interval_grouping" />
            <boolProp name="graph_aggregated" />
            <stringProp name="include_sample_labels" />
            <stringProp name="exclude_sample_labels" />
            <stringProp name="start_offset" />
            <stringProp name="end_offset" />
            <boolProp name="include_checkbox_state" />
            <boolProp name="exclude_checkbox_state" />
            #{metricConnections.root.to_s}
          </kg.apc.jmeter.perfmon.PerfMonCollector>
          XML
        end
      end
    end
  end
end


text:
'*********************************************************
'
' Copyright (c) Microsoft. All rights reserved.
' THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
' ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
' IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
' PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
'
'*********************************************************
Imports Windows.UI.Xaml
Imports Windows.UI.Xaml.Controls
Imports Windows.UI.Xaml.Navigation
Imports SDKTemplate
Imports System
Imports Windows.Storage

Namespace Global.ApplicationDataSample

    ''' <summary>
    ''' An empty page that can be used on its own or navigated to within a Frame.
    ''' </summary>
    Public NotInheritable Partial Class SettingContainer
        Inherits Page

        Dim rootPage As MainPage = MainPage.Current

        Dim localSettings As ApplicationDataContainer = Nothing

        Const containerName As String = "exampleContainer"

        Const settingName As String = "exampleSetting"

        Public Sub New()
            Me.InitializeComponent()
            localSettings = ApplicationData.Current.LocalSettings
            DisplayOutput()
        End Sub

        Sub CreateContainer_Click(sender As [Object], e As RoutedEventArgs)
            Dim container As ApplicationDataContainer = localSettings.CreateContainer(containerName, ApplicationDataCreateDisposition.Always)
            DisplayOutput()
        End Sub

        Sub DeleteContainer_Click(sender As [Object], e As RoutedEventArgs)
            localSettings.DeleteContainer(containerName)
            DisplayOutput()
        End Sub

        Sub WriteSetting_Click(sender As [Object], e As RoutedEventArgs)
            If localSettings.Containers.ContainsKey(containerName) Then
                localSettings.Containers(containerName).Values(settingName) = "Hello World"
            End If

            DisplayOutput()
        End Sub

        Sub DeleteSetting_Click(sender As [Object], e As RoutedEventArgs)
            If localSettings.Containers.ContainsKey(containerName) Then
                localSettings.Containers(containerName).Values.Remove(settingName)
            End If

            DisplayOutput()
        End Sub

        Sub DisplayOutput()
            Dim hasContainer As Boolean = localSettings.Containers.ContainsKey(containerName)
            Dim hasSetting As Boolean = If(hasContainer, localSettings.Containers(containerName).Values.ContainsKey(settingName), False)
            Dim output As String = String.Format("Container Exists: {0}" & vbLf & "Setting Exists: {1}", If(hasContainer, "true", "false"), If(hasSetting, "true", "false"))
            OutputTextBlock.Text = output
        End Sub

        ''' <summary>
        ''' Invoked when this page is about to be displayed in a Frame.
        ''' </summary>
        ''' <param name="e">Event data that describes how this page was reached.  The Parameter
        ''' property is typically used to configure the page.</param>
        Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs)
        End Sub
    End Class
End Namespace

redpajama_set_name: RedPajamaGithub


text:
#include <aws/lexv2-models/model/ImportResourceSpecification.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace LexModelsV2
{
namespace Model
{

ImportResourceSpecification::ImportResourceSpecification() :
    m_botImportSpecificationHasBeenSet(false),
    m_botLocaleImportSpecificationHasBeenSet(false)
{
}

ImportResourceSpecification::ImportResourceSpecification(JsonView jsonValue) :
    m_botImportSpecificationHasBeenSet(false),
    m_botLocaleImportSpecificationHasBeenSet(false)
{
  *this = jsonValue;
}

ImportResourceSpecification& ImportResourceSpecification::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("botImportSpecification"))
  {
    m_botImportSpecification = jsonValue.GetObject("botImportSpecification");

    m_botImportSpecificationHasBeenSet = true;
  }

  if(jsonValue.ValueExists("botLocaleImportSpecification"))
  {
    m_botLocaleImportSpecification = jsonValue.GetObject("botLocaleImportSpecification");

    m_botLocaleImportSpecificationHasBeenSet = true;
  }

  return *this;
}

JsonValue ImportResourceSpecification::Jsonize() const
{
  JsonValue payload;

  if(m_botImportSpecificationHasBeenSet)
  {
   payload.WithObject("botImportSpecification", m_botImportSpecification.Jsonize());

  }

  if(m_botLocaleImportSpecificationHasBeenSet)
  {
   payload.WithObject("botLocaleImportSpecification", m_botLocaleImportSpecification.Jsonize());

  }

  return payload;
}

} // namespace Model
} // namespace LexModelsV2
} // namespace Aws


text:
/**
 * @fileoverview Helper to get the versions of browsers.
 */

import { BrowserSupportCollection } from '../types';
import { browserVersions } from './normalize-version';
import { convertBrowserSupportCollectionToMDN } from './convert-browser-names';

class UserBrowsers {
    public convert(targetedBrowsers: string[]): BrowserSupportCollection {
        const browserCollection = {} as BrowserSupportCollection;

        targetedBrowsers.forEach((browserInfo: string) => {
            const [browserName, browserVersion] = browserInfo.split(' ');

            browserCollection[browserName] = browserCollection[browserName] || [];
            browserCollection[browserName] = [...browserCollection[browserName], ...this.getBrowserVersions(browserVersion)];
        });

        return convertBrowserSupportCollectionToMDN(browserCollection);
    }

    private getBrowserVersions(version: string): number[] {
        // We support to have two versions in same targeted browser
        if (version.match(/-/)) {
            const [first, second] = version.split('-');

            return [browserVersions.normalize(first), browserVersions.normalize(second)];
        }

        return [browserVersions.normalize(version)];
    }
}

export const userBrowsers = new UserBrowsers();


text:
/*--------------------------------------------------------*\
|                                                          |
|                          hprose                          |
|                                                          |
| Official WebSite: https://hprose.com                     |
|                                                          |
|  ValueTupleDeserializer.cs                               |
|                                                          |
|  ValueTupleDeserializer class for C#.                    |
|                                                          |
|  LastModified: Jun 30, 2020                              |
|  Author: Ma Bingyao <andot@hprose.com>                   |
|                                                          |
\*________________________________________________________*/

using System;
using System.IO;

namespace Hprose.IO.Deserializers {
    using static Tags;

    internal static class ValueTupleHelper<T> {
        public static volatile Func<Reader, int, T> read;
        static ValueTupleHelper() {
            Type type = typeof(T);
            if (type.IsGenericType) {
                var t = type.GetGenericTypeDefinition();
                if (t.Name.StartsWith("ValueTuple`")) {
                    Type[] args = type.GetGenericArguments();
                    typeof(ValueTupleHelper).GetMethod($"Initialize{args.Length}").MakeGenericMethod(args).Invoke(null, null);
                    return;
                }
            }
            read = (reader, count) => {
                T result = --count >= 0 ? Deserializer<T>.Instance.Deserialize(reader) : default;
                for (int i = count; i > 0; --i) {
                    Deserializer.Instance.Deserialize(reader);
                }
                return result;
            };
        }
    }

    internal static class ValueTupleHelper {
        public static void Initialize1<T1>() {
            ValueTupleHelper<ValueTuple<T1>>.read = (reader, count) => {
                var result = new ValueTuple<T1>(
                    --count >= 0 ? Deserializer<T1>.Instance.Deserialize(reader) : default
                );
                for (int i = count; i > 0; --i) {
                    Deserializer.Instance.Deserialize(reader);
                }
                return result;
            };
        }
        public static void Initialize2<T1, T2>() {
            ValueTupleHelper<ValueTuple<T1, T2>>.read = (reader, count) => {
                var result = new ValueTuple<T1, T2>(
                    --count >= 0 ? Deserializer<T1>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T2>.Instance.Deserialize(reader) : default
                );
                for (int i = count; i > 0; --i) {
                    Deserializer.Instance.Deserialize(reader);
                }
                return result;
            };
        }
        public static void Initialize3<T1, T2, T3>() {
            ValueTupleHelper<ValueTuple<T1, T2, T3>>.read = (reader, count) => {
                var result = new ValueTuple<T1, T2, T3>(
                    --count >= 0 ? Deserializer<T1>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T2>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T3>.Instance.Deserialize(reader) : default
                );
                for (int i = count; i > 0; --i) {
                    Deserializer.Instance.Deserialize(reader);
                }
                return result;
            };
        }
        public static void Initialize4<T1, T2, T3, T4>() {
            ValueTupleHelper<ValueTuple<T1, T2, T3, T4>>.read = (reader, count) => {
                var result = new ValueTuple<T1, T2, T3, T4>(
                    --count >= 0 ? Deserializer<T1>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T2>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T3>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T4>.Instance.Deserialize(reader) : default
                );
                for (int i = count; i > 0; --i) {
                    Deserializer.Instance.Deserialize(reader);
                }
                return result;
            };
        }
        public static void Initialize5<T1, T2, T3, T4, T5>() {
            ValueTupleHelper<ValueTuple<T1, T2, T3, T4, T5>>.read = (reader, count) => {
                var result = new ValueTuple<T1, T2, T3, T4, T5>(
                    --count >= 0 ? Deserializer<T1>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T2>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T3>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T4>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T5>.Instance.Deserialize(reader) : default
                );
                for (int i = count; i > 0; --i) {
                    Deserializer.Instance.Deserialize(reader);
                }
                return result;
            };
        }
        public static void Initialize6<T1, T2, T3, T4, T5, T6>() {
            ValueTupleHelper<ValueTuple<T1, T2, T3, T4, T5, T6>>.read = (reader, count) => {
                var result = new ValueTuple<T1, T2, T3, T4, T5, T6>(
                    --count >= 0 ? Deserializer<T1>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T2>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T3>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T4>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T5>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T6>.Instance.Deserialize(reader) : default
                );
                for (int i = count; i > 0; --i) {
                    Deserializer.Instance.Deserialize(reader);
                }
                return result;
            };
        }
        public static void Initialize7<T1, T2, T3, T4, T5, T6, T7>() {
            ValueTupleHelper<ValueTuple<T1, T2, T3, T4, T5, T6, T7>>.read = (reader, count) => {
                var result = new ValueTuple<T1, T2, T3, T4, T5, T6, T7>(
                    --count >= 0 ? Deserializer<T1>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T2>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T3>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T4>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T5>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T6>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T7>.Instance.Deserialize(reader) : default
                );
                for (int i = count; i > 0; --i) {
                    Deserializer.Instance.Deserialize(reader);
                }
                return result;
            };
        }
        public static void Initialize8<T1, T2, T3, T4, T5, T6, T7, TRest>() where TRest : struct {
            ValueTupleHelper<ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>>.read = (reader, count) => {
                return new ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>(
                    --count >= 0 ? Deserializer<T1>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T2>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T3>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T4>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T5>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T6>.Instance.Deserialize(reader) : default,
                    --count >= 0 ? Deserializer<T7>.Instance.Deserialize(reader) : default,
                    ValueTupleHelper<TRest>.read(reader, count)
                );
            };
        }
    }

    internal class ValueTupleDeserializer : Deserializer<ValueTuple> {
        public static ValueTuple Read(Reader reader) {
            Stream stream = reader.Stream;
            int count = ValueReader.ReadCount(stream);
            reader.AddReference(default(ValueTuple));
            for (int i = count; i > 0; --i) {
                Deserializer.Instance.Deserialize(reader);
            }
            stream.ReadByte();
            return default;
        }
        public override ValueTuple Read(Reader reader, int tag) => tag switch {
            TagEmpty => default,
            TagList => Read(reader),
            _ => base.Read(reader, tag),
        };
    }

    internal class ValueTupleDeserializer<T> : Deserializer<T> {
        public static T Read(Reader reader) {
            Stream stream = reader.Stream;
            int count = ValueReader.ReadCount(stream);
            reader.AddReference(null);
            int index = reader.LastReferenceIndex;
            T tuple = ValueTupleHelper<T>.read(reader, count);
            reader.SetReference(index, tuple);
            stream.ReadByte();
            return tuple;
        }
        public override T Read(Reader reader, int tag) => tag switch {
            TagList => Read(reader),
            TagEmpty => default,
            _ => base.Read(reader, tag),
        };
    }
}


text:
module.exports = {
  plugins: [
    require('postcss-smart-import')({ /* ...options */ }),
    require('postcss-css-variables')(),
      require('postcss-cssnext')({
        features: {
          customProperties: false
        }
      }),
      require('postcss-responsive-type')()
  ]
}


text:
#ifndef MAGICKCORE_DISTORT_H
#define MAGICKCORE_DISTORT_H

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif

/*
  These two enum are linked, with common enumerated values.  Both
  DistortImages() and SparseColor() often share code to determine functional
  coefficients for common methods.

  Caution should be taken to ensure that only the common methods contain the
  same enumerated value, while all others remain unique across both
  enumerations.
*/
typedef enum
{
  UndefinedDistortion,
  AffineDistortion,
  AffineProjectionDistortion,
  ScaleRotateTranslateDistortion,
  PerspectiveDistortion,
  PerspectiveProjectionDistortion,
  BilinearForwardDistortion,
  BilinearDistortion = BilinearForwardDistortion,
  BilinearReverseDistortion,
  PolynomialDistortion,
  ArcDistortion,
  PolarDistortion,
  DePolarDistortion,
  Cylinder2PlaneDistortion,
  Plane2CylinderDistortion,
  BarrelDistortion,
  BarrelInverseDistortion,
  ShepardsDistortion,
  ResizeDistortion,
  SentinelDistortion
} DistortImageMethod;

typedef enum
{
  UndefinedColorInterpolate = UndefinedDistortion,
  BarycentricColorInterpolate = AffineDistortion,
  BilinearColorInterpolate = BilinearReverseDistortion,
  PolynomialColorInterpolate = PolynomialDistortion,
  ShepardsColorInterpolate = ShepardsDistortion,
  /*
    Methods unique to SparseColor().
  */
  VoronoiColorInterpolate = SentinelDistortion,
  InverseColorInterpolate,
  ManhattanColorInterpolate
} SparseColorMethod;

extern MagickExport Image
  *AffineTransformImage(const Image *,const AffineMatrix *,ExceptionInfo *),
  *DistortImage(const Image *,const DistortImageMethod,const size_t,
    const double *,MagickBooleanType,ExceptionInfo *exception),
  *DistortResizeImage(const Image *,const size_t,const size_t,ExceptionInfo *),
  *RotateImage(const Image *,const double,ExceptionInfo *),
  *SparseColorImage(const Image *,const ChannelType,const SparseColorMethod,
    const size_t,const double *,ExceptionInfo *);

#if defined(__cplusplus) || defined(c_plusplus)
}
#endif

#endif


text:
package com.jgeppert.struts2.jquery.mobile.views.jsp.ui;

import com.jgeppert.struts2.jquery.mobile.components.Head;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.components.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Johannes Geppert
 */

public class HeadTag extends com.jgeppert.struts2.jquery.views.jsp.ui.HeadTag {

    private static final long serialVersionUID = 8907797097962067205L;

    protected String compressed;
    protected String jqueryui;

    public Component getBean(ValueStack stack, HttpServletRequest req,
                             HttpServletResponse res) {
        return new Head(stack, req, res);
    }

    protected void populateParams() {
        super.populateParams();

        Head head = (Head) component;
        head.setCompressed(compressed);
        head.setJqueryui(jqueryui);
    }

    public void setCompressed(String compressed) {
        this.compressed = compressed;
    }

    public void setJqueryui(String jqueryui) {
        this.jqueryui = jqueryui;
    }

}


text:
"""
Django settings for django_and_angular project.

Generated by 'django-admin startproject' using Django 1.8.1.

For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'lfaeph5!@0pzr4*hlpiid3twqw3arueur+9!srnr5rrw#t)#mm'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'gameGap',
    'rest_framework',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'django_and_angular.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'django_and_angular.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
if 'RDS_DB_NAME' in os.environ:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': os.environ['RDS_DB_NAME'],
            'USER': os.environ['RDS_USERNAME'],
            'PASSWORD': os.environ['RDS_PASSWORD'],
            'HOST': os.environ['RDS_HOSTNAME'],
            'PORT': os.environ['RDS_PORT'],
        }
    }

else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'gameGap',
        }
    }

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'compressor.finders.CompressorFinder',
)

COMPRESS_ENABLED = os.environ.get('COMPRESS_ENABLED', False)

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'static')


text:
/* ========================= Module _Folder ========================= */

#include "Python.h"

#include "pymactoolbox.h"

/* Macro to test whether a weak-loaded CFM function exists */
#define PyMac_PRECHECK(rtn) do { if ( &rtn == NULL )  {\
    PyErr_SetString(PyExc_NotImplementedError, \
    "Not available in this shared library/OS version"); \
    return NULL; \
    }} while(0)

#include <Carbon/Carbon.h>

static PyObject *Folder_Error;

static PyObject *Folder_FindFolder(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    short vRefNum;
    OSType folderType;
    Boolean createFolder;
    FSVolumeRefNum  foundVRefNum;
    SInt32 foundDirID;
    if (!PyArg_ParseTuple(_args, "hO&b",
                          &vRefNum,
                          PyMac_GetOSType, &folderType,
                          &createFolder))
        return NULL;
    _err = FindFolder(vRefNum,
                      folderType,
                      createFolder,
                      &foundVRefNum,
                      &foundDirID);
    if (_err != noErr) return PyMac_Error(_err);
    _res = Py_BuildValue("hl",
                         foundVRefNum,
                         foundDirID);
    return _res;
}

static PyObject *Folder_ReleaseFolder(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    short vRefNum;
    OSType folderType;
    if (!PyArg_ParseTuple(_args, "hO&",
                          &vRefNum,
                          PyMac_GetOSType, &folderType))
        return NULL;
    _err = ReleaseFolder(vRefNum,
                         folderType);
    if (_err != noErr) return PyMac_Error(_err);
    Py_INCREF(Py_None);
    _res = Py_None;
    return _res;
}

static PyObject *Folder_FSFindFolder(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    short vRefNum;
    OSType folderType;
    Boolean createFolder;
    FSRef foundRef;
    if (!PyArg_ParseTuple(_args, "hO&b",
                          &vRefNum,
                          PyMac_GetOSType, &folderType,
                          &createFolder))
        return NULL;
    _err = FSFindFolder(vRefNum,
                        folderType,
                        createFolder,
                        &foundRef);
    if (_err != noErr) return PyMac_Error(_err);
    _res = Py_BuildValue("O&",
                         PyMac_BuildFSRef, &foundRef);
    return _res;
}

static PyObject *Folder_AddFolderDescriptor(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    FolderType foldType;
    FolderDescFlags flags;
    FolderClass foldClass;
    FolderLocation foldLocation;
    OSType badgeSignature;
    OSType badgeType;
    Str255 name;
    Boolean replaceFlag;
    if (!PyArg_ParseTuple(_args, "O&lO&O&O&O&O&b",
                          PyMac_GetOSType, &foldType,
                          &flags,
                          PyMac_GetOSType, &foldClass,
                          PyMac_GetOSType, &foldLocation,
                          PyMac_GetOSType, &badgeSignature,
                          PyMac_GetOSType, &badgeType,
                          PyMac_GetStr255, name,
                          &replaceFlag))
        return NULL;
    _err = AddFolderDescriptor(foldType,
                               flags,
                               foldClass,
                               foldLocation,
                               badgeSignature,
                               badgeType,
                               name,
                               replaceFlag);
    if (_err != noErr) return PyMac_Error(_err);
    Py_INCREF(Py_None);
    _res = Py_None;
    return _res;
}

static PyObject *Folder_GetFolderTypes(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    UInt32 requestedTypeCount;
    UInt32 totalTypeCount;
    FolderType theTypes;
    if (!PyArg_ParseTuple(_args, "l",
                          &requestedTypeCount))
        return NULL;
    _err = GetFolderTypes(requestedTypeCount,
                          &totalTypeCount,
                          &theTypes);
    if (_err != noErr) return PyMac_Error(_err);
    _res = Py_BuildValue("lO&",
                         totalTypeCount,
                         PyMac_BuildOSType, theTypes);
    return _res;
}

static PyObject *Folder_RemoveFolderDescriptor(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    FolderType foldType;
    if (!PyArg_ParseTuple(_args, "O&",
                          PyMac_GetOSType, &foldType))
        return NULL;
    _err = RemoveFolderDescriptor(foldType);
    if (_err != noErr) return PyMac_Error(_err);
    Py_INCREF(Py_None);
    _res = Py_None;
    return _res;
}

#ifndef __LP64__
static PyObject *Folder_GetFolderName(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    short vRefNum;
    OSType foldType;
    short foundVRefNum;
    Str255 name;
    if (!PyArg_ParseTuple(_args, "hO&O&",
                          &vRefNum,
                          PyMac_GetOSType, &foldType,
                          PyMac_GetStr255, name))
        return NULL;
    _err = GetFolderName(vRefNum,
                         foldType,
                         &foundVRefNum,
                         name);
    if (_err != noErr) return PyMac_Error(_err);
    _res = Py_BuildValue("h",
                         foundVRefNum);
    return _res;
}

static PyObject *Folder_AddFolderRouting(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    OSType fileType;
    FolderType routeFromFolder;
    FolderType routeToFolder;
    RoutingFlags flags;
    Boolean replaceFlag;
    if (!PyArg_ParseTuple(_args, "O&O&O&lb",
                          PyMac_GetOSType, &fileType,
                          PyMac_GetOSType, &routeFromFolder,
                          PyMac_GetOSType, &routeToFolder,
                          &flags,
                          &replaceFlag))
        return NULL;
    _err = AddFolderRouting(fileType,
                            routeFromFolder,
                            routeToFolder,
                            flags,
                            replaceFlag);
    if (_err != noErr) return PyMac_Error(_err);
    Py_INCREF(Py_None);
    _res = Py_None;
    return _res;
}

static PyObject *Folder_RemoveFolderRouting(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    OSType fileType;
    FolderType routeFromFolder;
    if (!PyArg_ParseTuple(_args, "O&O&",
                          PyMac_GetOSType, &fileType,
                          PyMac_GetOSType, &routeFromFolder))
        return NULL;
    _err = RemoveFolderRouting(fileType,
                               routeFromFolder);
    if (_err != noErr) return PyMac_Error(_err);
    Py_INCREF(Py_None);
    _res = Py_None;
    return _res;
}

static PyObject *Folder_FindFolderRouting(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    OSType fileType;
    FolderType routeFromFolder;
    FolderType routeToFolder;
    RoutingFlags flags;
    if (!PyArg_ParseTuple(_args, "O&O&",
                          PyMac_GetOSType, &fileType,
                          PyMac_GetOSType, &routeFromFolder))
        return NULL;
    _err = FindFolderRouting(fileType,
                             routeFromFolder,
                             &routeToFolder,
                             &flags);
    if (_err != noErr) return PyMac_Error(_err);
    _res = Py_BuildValue("O&l",
                         PyMac_BuildOSType, routeToFolder,
                         flags);
    return _res;
}
#endif /* !__LP64__ */

static PyObject *Folder_InvalidateFolderDescriptorCache(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    short vRefNum;
    long dirID;
    if (!PyArg_ParseTuple(_args, "hl",
                          &vRefNum,
                          &dirID))
        return NULL;
    _err = InvalidateFolderDescriptorCache(vRefNum,
                                           dirID);
    if (_err != noErr) return PyMac_Error(_err);
    Py_INCREF(Py_None);
    _res = Py_None;
    return _res;
}

static PyObject *Folder_IdentifyFolder(PyObject *_self, PyObject *_args)
{
    PyObject *_res = NULL;
    OSErr _err;
    short vRefNum;
    long dirID;
    FolderType foldType;
    if (!PyArg_ParseTuple(_args, "hl",
                          &vRefNum,
                          &dirID))
        return NULL;
    _err = IdentifyFolder(vRefNum,
                          dirID,
                          &foldType);
    if (_err != noErr) return PyMac_Error(_err);
    _res = Py_BuildValue("O&",
                         PyMac_BuildOSType, foldType);
    return _res;
}

static PyMethodDef Folder_methods[] = {
    {"FindFolder", (PyCFunction)Folder_FindFolder, 1,
     PyDoc_STR("(short vRefNum, OSType folderType, Boolean createFolder) -> (short foundVRefNum, long foundDirID)")},
    {"ReleaseFolder", (PyCFunction)Folder_ReleaseFolder, 1,
     PyDoc_STR("(short vRefNum, OSType folderType) -> None")},
    {"FSFindFolder", (PyCFunction)Folder_FSFindFolder, 1,
     PyDoc_STR("(short vRefNum, OSType folderType, Boolean createFolder) -> (FSRef foundRef)")},
    {"AddFolderDescriptor", (PyCFunction)Folder_AddFolderDescriptor, 1,
     PyDoc_STR("(FolderType foldType, FolderDescFlags flags, FolderClass foldClass, FolderLocation foldLocation, OSType badgeSignature, OSType badgeType, Str255 name, Boolean replaceFlag) -> None")},
    {"GetFolderTypes", (PyCFunction)Folder_GetFolderTypes, 1,
     PyDoc_STR("(UInt32 requestedTypeCount) -> (UInt32 totalTypeCount, FolderType theTypes)")},
    {"RemoveFolderDescriptor", (PyCFunction)Folder_RemoveFolderDescriptor, 1,
     PyDoc_STR("(FolderType foldType) -> None")},
#ifndef __LP64__
    {"GetFolderName", (PyCFunction)Folder_GetFolderName, 1,
     PyDoc_STR("(short vRefNum, OSType foldType, Str255 name) -> (short foundVRefNum)")},
    {"AddFolderRouting", (PyCFunction)Folder_AddFolderRouting, 1,
     PyDoc_STR("(OSType fileType, FolderType routeFromFolder, FolderType routeToFolder, RoutingFlags flags, Boolean replaceFlag) -> None")},
    {"RemoveFolderRouting", (PyCFunction)Folder_RemoveFolderRouting, 1,
     PyDoc_STR("(OSType fileType, FolderType routeFromFolder) -> None")},
    {"FindFolderRouting", (PyCFunction)Folder_FindFolderRouting, 1,
     PyDoc_STR("(OSType fileType, FolderType routeFromFolder) -> (FolderType routeToFolder, RoutingFlags flags)")},
#endif /* !__LP64__ */
    {"InvalidateFolderDescriptorCache", (PyCFunction)Folder_InvalidateFolderDescriptorCache, 1,
     PyDoc_STR("(short vRefNum, long dirID) -> None")},
    {"IdentifyFolder", (PyCFunction)Folder_IdentifyFolder, 1,
     PyDoc_STR("(short vRefNum, long dirID) -> (FolderType foldType)")},
    {NULL, NULL, 0}
};

void init_Folder(void)
{
    PyObject *m;
    PyObject *d;

    m = Py_InitModule("_Folder", Folder_methods);
    d = PyModule_GetDict(m);
    Folder_Error = PyMac_GetOSErrException();
    if (Folder_Error == NULL ||
        PyDict_SetItemString(d, "Error", Folder_Error) != 0)
        return;
}

/* ======================= End module _Folder ======================= */


text:
module RubyOS::Memory
  class BestFitManager < Manager
    def assign_process_base_address(process)
      super
      final_hole = {}
      # Find the first available hole
      hole = find_hole
      raise OutOfMemoryError.new if hole.nil?

      # There is at least one other reserved spot, so we need store the current
      # whole information if the hole is large enough:
      if hole[:mem_available] >= process.memory_required
        final_hole = hole
      end

      loop do
        # Find the next 'hole'
        hole = find_hole(hole[:end_address])

        # There are no further holes
        break if hole.nil?

        if hole[:mem_available] >= process.memory_required
          # Only update the target hole if it's a better fit than the current
          # one.
          if final_hole.empty? || final_hole[:mem_available].send(self.comparitor, hole[:mem_available])
            final_hole = hole
          end
        end
      end

      # If we never set the 'hole' then there was no 'hole' big enough for the
      # requested process
      raise NoContiguousMemoryError.new if final_hole.empty?

      # Set memory info on process & reserve memory
      # NOTE The current memory limit is fixed to the required memory of the
      # process for now...
      final_hole[:memory_limit] = process.memory_required
      process.base_address = final_hole[:base_address]
      process.memory_limit = final_hole[:memory_limit]
      reserve_memory(process.base_address, process.memory_limit)
    end

    # Best fit wants to find the smaller hole size
    # This is only here so that the algorithm above can be reused for Worst Fit
    # (since they have exactly the same steps, only Worst fit want the *largest*
    # hole, not the smallest).
    def comparitor
      :>
    end
  end
end


text:
import Queue     as pqueue
import socket    as psocket
import threading as pthread
import itertools as it
from . import inetheaders, inetmsg, ineterr

AUTO_PING_SECONDS = 5.0

class Socket(object):

    def __init__(self, socket):

        self._txn_id     = it.count(start = 1)
        self._txn_queues = {}

        self._socket = None
        self.attach_socket(socket)

    def is_closed(self):
        return self._cancel.is_set()

    def detach_socket(self):
        assert self._socket, 'Invalid Socket State'

        self._cancel.set()
        self._read_thread.join()
        self._send_thread.join()

        socket, self._socket = self._socket, None
        return socket

    def attach_socket(self, socket):
        assert not self._socket, 'Invalid Socket State'

        self._socket = socket
        self._socket.settimeout(AUTO_PING_SECONDS)

        self._cancel      = pthread.Event()
        self._send_queue  = pqueue.Queue()
        self._send_thread = pthread.Thread(target = self._send_worker, args = (socket, self._send_queue, self._cancel))
        self._send_thread.daemon = True;
        self._send_thread.start()

        self._read_queue  = pqueue.Queue()
        self._read_thread = pthread.Thread(target = self._read_worker, args = (socket, self._read_queue, self._cancel))
        self._read_thread.daemon = True;
        self._read_thread.start()

    def _read_worker(self, socket, queue, cancel):

        fd = socket.makefile('rb')

        while (not cancel.is_set()):

            start_line = False
            headers    = False
            body       = False

            try:
                start_line, headers, body = inetmsg.read_message(fd)

            except psocket.timeout:
                continue

            except:
                cancel.set()
                continue

            if (isinstance(start_line, inetmsg.StatusLine)):

                if (not self._handle_response(start_line, headers, body, cancel)):
                    queue.put((start_line, headers, body), False)

    def _handle_response(self, start_line, headers, body, cancel):

        try:
            subject = headers.get(inetheaders.SUBJECT, 0)
            subject = subject.lower()
            txn_id  = subject.split(';')[0]
            txn_id  = int(txn_id.split('r')[0])

        except ValueError:
            cancel.set()

        if (txn_id in self._txn_queues):
            self._txn_queues[txn_id].put((start_line, headers, body), False)
            return True

        return False

    def _read(self, queue, timeout):

        start_line, headers, body = queue.get(timeout = timeout)

        if (isinstance(start_line, inetmsg.StatusLine)):

            if (start_line.code >= 400):
                err = ineterr.parse_error(body)

                if err.code == ineterr.PENDING:
                    err = ineterr.err(ineterr.BAD_SERVER_DATA, '_read, received PENDING')

                body = None

            else:
                err = ineterr.err(ineterr.SUCCESS)

        return err, start_line, headers, body

    def read(self, timeout = None):

        while True:

            try:
                err, start_line, headers, body = self._read(self._read_queue, timeout)

            except pqueue.Empty:
                return None

            if (isinstance(start_line, inetmsg.StatusLine)):
                err = ineterr.err(ineterr.BAD_SERVER_DATA, 'read, received status')

            if (body is None):
                continue

            try:
                __, protocol, command = start_line.uri.split('/')

            except ValueError:
                continue

            return (protocol, command, headers, body)

    def _send_worker(self, socket, queue, cancel):

        while (not cancel.is_set()):

            try:
                start_line, headers, body = queue.get(timeout = AUTO_PING_SECONDS)
                socket.sendall(inetmsg.build_message(start_line, headers, body))

            except pqueue.Empty:
                self._send(queue, inetmsg.RequestLine(method = 'P', uri='/Sts/Ping'))

    def _send(self, queue, start_line, headers = False, body = False):

        headers      = headers if headers else {}
        body         = body if body else ''
        content_type = headers.get(inetheaders.CONTENT_TYPE, 'application/xml')

        if (content_type == 'application/xml'):
            body += '\n'

        if (len(body) > 0):
            headers[inetheaders.CONTENT_LENGTH] = str(len(body))

        elif (inetheaders.CONTENT_LENGTH in headers):
            del headers[inetheaders.CONTENT_LENGTH]

        queue.put((start_line, headers, body))

    def send(self, protocol, command, headers = False, body = False):

        request_line = inetmsg.RequestLine(method='P', uri='/%s/%s' % (protocol, command))
        self._send(self._send_queue, request_line, headers, body)

    def _request(self, protocol, command, headers = False, body = False, timeout = None):

        txn_id                   = self._txn_id.next()
        self._txn_queues[txn_id] = pqueue.Queue()

        headers = headers if headers else {}
        headers[inetheaders.SUBJECT] = str(txn_id)

        self.send(protocol, command, headers, body)

        try:

            body_result = False
            next_seq = False
            while True:

                try:
                    err, start_line, headers, body = self._read(self._txn_queues[txn_id], timeout)

                except pqueue.Empty:
                    yield ineterr.err(ineterr.TIMEOUT), None
                    break

                if (isinstance(start_line, inetmsg.RequestLine)):
                    err = ineterr.err(ineterr.BAD_SERVER_DATA, '_request, received request')

                subject = headers[inetheaders.SUBJECT].split(';')[0]

                try:
                    __, seq = subject.lower().split('r')
                    seq = int(seq) if seq else False

                except ValueError:
                    err = ineterr.err(ineterr.BAD_SERVER_DATA, '_request, malformed subject')

                if (not seq and next_seq):
                    err = ineterr.err(ineterr.BAD_SERVER_DATA, '_request, out of sequence')
                elif (next_seq and seq != next_seq):
                    err = ineterr.err(ineterr.BAD_SERVER_DATA, '_request, out of sequence')
                elif (seq and seq != 1 and not next_seq):
                    err = ineterr.err(ineterr.BAD_SERVER_DATA, '_request, out of sequence')
                elif (seq):
                    next_seq = seq + 1

                complete = 'R' in subject
                if (not seq and not complete):
                    err = ineterr.err(ineterr.BAD_SERVER_DATA, '_request, invalid seq')

                if (err.code != ineterr.SUCCESS and not complete):
                    err = ineterr.err(ineterr.BAD_SERVER_DATA, '_request, pending error')

                if (inetheaders.CONTENT_RANGE in headers):

                    raw_range       = headers[inetheaders.CONTENT_RANGE]
                    type_segments   = raw_range.split(' ')
                    range_segments  = type_segments[1].split('/')
                    numerator_range = range_segments[0].split('-')
                    start_range     = int(numerator_range[0])
                    end_range       = int(numerator_range[1])
                    denominator     = int(range_segments[1])

                    if (start_range == 0):
                        body_result = body
                    else:
                        body_result += body

                    if ((end_range + 1) == denominator):

                        if (not len(body_result) == denominator):
                            err = ineterr.err(ineterr.BAD_SERVER_DATA, '_request, invalid chunked result')

                        yield err, (headers, body_result)

                    continue

                if (body):
                    yield err, (headers, body)
                else:
                    yield err, None

                if (err.code != ineterr.SUCCESS or complete):
                    break

        finally:
            del self._txn_queues[txn_id]

    def _request_one(self, protocol, command, headers, body, timeout):

        iter     = self._request(protocol, command, headers, body, timeout)
        err, msg = iter.next()

        if (err.code == ineterr.PENDING):
            iter.close()
            return ineterr.err(ineterr.BAD_SERVER_DATA, '_request_one, multi-part response'), None

        return err, msg

    def request_many(self, protocol, command, headers = False, body = False, timeout = None):

        return self._request(protocol, command, headers, body, timeout)

    def request_one(self, protocol, command, headers = False, body = False, timeout = None):

        err, msg = self._request_one(protocol, command, headers, body, timeout)

        if (err.code == ineterr.SUCCESS and not msg):
            return ineterr.err(ineterr.BAD_SERVER_DATA, 'request_one, reply not message'), None

        return err, msg

    def request_none(self, protocol, command, headers = False, body = False, timeout = None):

        err, msg = self._request_one(protocol, command, headers, body, timeout)

        if (msg):
            return ineterr.err(ineterr.BAD_SERVER_DATA, 'request_none, message response'), None

        return err


text:
namespace WP7Contrib.Communications.Compression
{
    internal enum ZlibStreamFlavor
    {
        ZLIB = 1950,
        DEFLATE = 1951,
        GZIP = 1952,
    }
}


text:
@implementation SDLMenuParams

- (instancetype)init {
    if (self = [super init]) {
    }
    return self;
}

- (instancetype)initWithDictionary:(NSMutableDictionary *)dict {
    if (self = [super initWithDictionary:dict]) {
    }
    return self;
}

- (void)setParentID:(NSNumber *)parentID {
    if (parentID != nil) {
        [store setObject:parentID forKey:NAMES_parentID];
    } else {
        [store removeObjectForKey:NAMES_parentID];
    }
}

- (NSNumber *)parentID {
    return [store objectForKey:NAMES_parentID];
}

- (void)setPosition:(NSNumber *)position {
    if (position != nil) {
        [store setObject:position forKey:NAMES_position];
    } else {
        [store removeObjectForKey:NAMES_position];
    }
}

- (NSNumber *)position {
    return [store objectForKey:NAMES_position];
}

- (void)setMenuName:(NSString *)menuName {
    if (menuName != nil) {
        [store setObject:menuName forKey:NAMES_menuName];
    } else {
        [store removeObjectForKey:NAMES_menuName];
    }
}

- (NSString *)menuName {
    return [store objectForKey:NAMES_menuName];
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="pull_style">
        <item name="pullDrawable">@drawable/pinter_pull</item>
    </style>
</resources>


text:
require 'bundler/setup'
require 'eventbus/message'

period = ARGV[0] || 0
message_file = ARGV[1]

# This script is dead simple. Supply it with two arguments:
# * A period in seconds at which the message will be continuously re-sent. For
#   example, specifying 60 would cause the message to be sent every 60 seconds.
#   Specifying 0 will cause the script to send the message once and exit.
#
# * A file containing the message to be sent. It will be read in exactly,
#   imported into an eventbus message, and sent out. It will be given
#   a new message id each time, as I suspect this is the desired behavior
#   most of the time. The file MUST be in the serialized JSON format as you'd
#   see it in the message dispatch view of the web UI.

def send_file(message_file)

  File.open(message_file, 'r') do |msg_file|

    json = msg_file.read

    # clear out a few fields we don't want to keep from the saved message
    msg_pre = JSON.parse(json)
    msg_pre["HEADER"].delete("message_id")
    msg_pre["HEADER"].delete("sender")

    msg = EventBus::Message.new
    msg.load(msg_pre.to_json)

    msg.send
  end

end

while(true)
  send_file(message_file)
  if period.to_i > 0
    sleep period.to_i
  else
    exit 0
  end
end


text:
using MasterChef.Data;
using MasterChef.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MasterChef.Web.Recipe
{
    public partial class Browse : System.Web.UI.Page
    {
        private IMasterChefData data;

        protected void Page_Load(object sender, EventArgs e)
        {
            var dbContext = new MasterChefDbContext();
            data = new MasterChefData(dbContext);

            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            var articles = data.Recipes.All()
                .OrderByDescending(r => r.CreatedOn)
                .Select(recipe => new RecipeViewModel
                {
                    ID = recipe.ID,
                    Description = recipe.Description,
                    Name = recipe.Name,
                    CreatedOn = recipe.CreatedOn,
                    CreatorID = recipe.CreatorID,
                    Creator = recipe.Creator.UserName,
                    ImagePath = recipe.Image.Path,
                    isCold = recipe.isCold,
                    isHot = recipe.isHot,
                    isSweet = recipe.isSweet,
                    isVegitarian = recipe.isVegitarian,
                    Likes = recipe.Likes.Count
                })
            .ToList();

            this.ListViewRecipes.DataSource = articles;
            this.ListViewRecipes.DataBind();
        }

        protected void GetFilteredRecipes(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.OrderBy.SelectedValue))
            {
                Session["OrderBy"] = this.OrderBy.SelectedValue;
            }
            if (!string.IsNullOrEmpty(this.OrderType.SelectedValue))
            {
                Session["OrderType"] = this.OrderType.SelectedValue;
            }

            var orderBy = (string)Session["OrderBy"];
            var orderType = (string)Session["OrderType"];

            var allRecipes = this.data.Recipes.All();

            if (orderType == "asc")
            {
                switch (orderBy)
                {
                    case "username":
                        allRecipes = allRecipes.OrderBy(a => a.Creator.UserName);
                        break;
                    case "name":
                        allRecipes = allRecipes.OrderBy(a => a.Name);
                        break;
                    case "createdOn":
                        allRecipes = allRecipes.OrderBy(a => a.CreatedOn);
                        break;
                    case "likes":
                        allRecipes = allRecipes.OrderBy(a => a.Likes.Count);
                        break;
                    default:
                        throw new ArgumentException("Wrong order type");
                }
            }
            else
            {
                switch (orderBy)
                {
                    case "username":
                        allRecipes = allRecipes.OrderByDescending(a => a.Creator.UserName);
                        break;
                    case "title":
                        allRecipes = allRecipes.OrderByDescending(a => a.Name);
                        break;
                    case "createdOn":
                        allRecipes = allRecipes.OrderByDescending(a => a.CreatedOn);
                        break;
                    case "likes":
                        allRecipes = allRecipes.OrderByDescending(a => a.Likes.Count);
                        break;
                    default:
                        throw new ArgumentException("Wrong order type");
                }
            }

            var listViewRecipes = allRecipes.Select(recipe => new RecipeViewModel
            {
                ID = recipe.ID,
                Description = recipe.Description,
                Name = recipe.Name,
                CreatedOn = recipe.CreatedOn,
                CreatorID = recipe.CreatorID,
                Creator = recipe.Creator.UserName,
                ImagePath = recipe.Image.Path,
                isCold = recipe.isCold,
                isHot = recipe.isHot,
                isSweet = recipe.isSweet,
                isVegitarian = recipe.isVegitarian,
                Likes = recipe.Likes.Count
            })
            .ToList();

            this.ListViewRecipes.DataSource = listViewRecipes;
            this.ListViewRecipes.DataBind();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:id="@+id/llCG"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:visibility="visible" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="4" >

                <Button
                    android:id="@+id/bBackToCharacters"
                    style="?android:attr/buttonStyleSmall"
                    android:layout_width="0px"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="Back" />

                <Button
                    android:id="@+id/bGenerate"
                    style="?android:attr/buttonStyleSmall"
                    android:layout_width="0px"
                    android:layout_height="wrap_content"
                    android:layout_weight="2"
                    android:text="Generate" />

                <Button
                    android:id="@+id/bSave"
                    style="?android:attr/buttonStyleSmall"
                    android:layout_width="0px"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:text="Save" />
            </LinearLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Input static attributes:"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="4" >

                <EditText
                    android:id="@+id/etRST"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:hint="ST"
                    android:inputType="number" >
                </EditText>

                <EditText
                    android:id="@+id/etRDX"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:hint="DX"
                    android:inputType="number" >
                </EditText>

                <EditText
                    android:id="@+id/etRIQ"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:hint="IQ"
                    android:inputType="number" >
                </EditText>

                <EditText
                    android:id="@+id/etRHT"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:hint="HT"
                    android:inputType="number" >
                </EditText>
            </LinearLayout>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Input static number of advantage types:"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:weightSum="4" >

                <EditText
                    android:id="@+id/etRA"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:hint="Adv"
                    android:inputType="number" >
                </EditText>

                <EditText
                    android:id="@+id/etRDA"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:hint="DAdv"
                    android:inputType="number" >
                </EditText>

                <EditText
                    android:id="@+id/etRPK"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:hint="Prk"
                    android:inputType="number" >
                </EditText>

                <EditText
                    android:id="@+id/etRQK"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ems="10"
                    android:hint="Qrk"
                    android:inputType="number" >
                </EditText>
            </LinearLayout>

            <include
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                layout="@layout/recordcard" />
        </LinearLayout>
    </ScrollView>

    <FrameLayout
        android:id="@+id/flProgress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ProgressBar
            android:id="@+id/pbCharacterGeneratedPercent"
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="visible" />

        <TextView
            android:id="@+id/tvProgress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:visibility="visible" />
    </FrameLayout>

</FrameLayout>


text:
package scaggold

import (
	"bufio"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

type Duplicator struct {
	fromPath  string
	toPath    string
	fromRegex *regexp.Regexp
	verbose   bool
	runnables []string
}

// Utility function
// Traling slash on right segument
func TrailSlash(path string) string {
	return strings.TrimRight(path, "/") + "/"
}

func NewDuplicator(fromPath, toPath string) *Duplicator {
	return &Duplicator{
		fromPath:  TrailSlash(fromPath),
		toPath:    TrailSlash(toPath),
		fromRegex: regexp.MustCompile("^" + TrailSlash(fromPath)),
		verbose:   true,
	}
}

func (d *Duplicator) Silent() {
	d.verbose = false
}

func (d *Duplicator) Run() bool {
	err := filepath.Walk(d.fromPath, d.walkFunc)
	if err != nil {
		fmt.Printf("%v\n", err)
		return false
	}

	for _, file := range d.runnables {
		fp, _ := os.Open(file)
		scanner := bufio.NewScanner(fp)
		scanner.Scan()
		shebang := []rune(scanner.Text())
		if string(shebang[0]) == "#" && string(shebang[1]) == "!" {
			command := string(shebang[2:])
			cmd := NewCommand(command)
			cmd.Arg(file)
			cmd.Exec()
		} //cmd := NewCommand("bash")
		//cmd.SendCommand("cd " + d.toPath)
		//cmd.SendCommand(file)
		//cmd.Exec()
	}

	return true
}

func (d *Duplicator) walkFunc(path string, info os.FileInfo, err error) error {
	rel := d.fromRegex.ReplaceAll([]byte(path), []byte(""))
	dest := d.toPath + string(rel)

	// Skip dotfile
	if len(rel) > 0 && string(rel[0]) == "." {
		if string(rel) == ".install" {
			d.runnables = append(d.runnables, path)
		}
		return nil
	}

	// Does walking directory?
	if info.IsDir() {
		os.Mkdir(dest, info.Mode())
		return nil
	}

	// Copy file
	if buffer, err := ioutil.ReadFile(path); err == nil {
		if err := ioutil.WriteFile(dest, buffer, info.Mode()); err == nil {
			if d.verbose {
				fmt.Printf("%s ====> %s\n", path, dest)
			}
			return nil
		} else {
			fmt.Printf("%v\n", err)
			return errors.New("File write error")
		}
	} else {
		fmt.Printf("%v\n", err)
		return errors.New("File read error")
	}

	return nil
}


text:
package eventDetailView

import (
	"fmt"

	"github.com/ecsteam/cloudfoundry-top-plugin/ui/uiCommon"
	"github.com/ecsteam/cloudfoundry-top-plugin/util"
)

func columnDeploymentName() *uiCommon.ListColumn {
	defaultColSize := 10
	sortFunc := func(c1, c2 util.Sortable) bool {
		return util.CaseInsensitiveLess(c1.(*DisplayEventDetailStats).DeploymentName, c2.(*DisplayEventDetailStats).DeploymentName)
	}
	displayFunc := func(data uiCommon.IData, columnOwner uiCommon.IColumnOwner) string {
		cellStats := data.(*DisplayEventDetailStats)
		return util.FormatDisplayData(cellStats.DeploymentName, defaultColSize)
	}
	rawValueFunc := func(data uiCommon.IData) string {
		cellStats := data.(*DisplayEventDetailStats)
		return cellStats.DeploymentName
	}
	c := uiCommon.NewListColumn("DNAME", "DNAME", defaultColSize,
		uiCommon.ALPHANUMERIC, true, sortFunc, false, displayFunc, rawValueFunc, nil)
	return c
}

func columnJobName() *uiCommon.ListColumn {
	defaultColSize := 45
	sortFunc := func(c1, c2 util.Sortable) bool {
		return util.CaseInsensitiveLess(c1.(*DisplayEventDetailStats).JobName, c2.(*DisplayEventDetailStats).JobName)
	}
	displayFunc := func(data uiCommon.IData, columnOwner uiCommon.IColumnOwner) string {
		cellStats := data.(*DisplayEventDetailStats)
		return util.FormatDisplayData(cellStats.JobName, defaultColSize)
	}
	rawValueFunc := func(data uiCommon.IData) string {
		cellStats := data.(*DisplayEventDetailStats)
		return cellStats.JobName
	}
	c := uiCommon.NewListColumn("JOB_NAME", "JOB_NAME", defaultColSize,
		uiCommon.ALPHANUMERIC, true, sortFunc, false, displayFunc, rawValueFunc, nil)
	return c
}

// Job Index in PCF 1.8 is now a GUID not a integer number
func columnJobIndex() *uiCommon.ListColumn {
	defaultColSize := 36
	sortFunc := func(c1, c2 util.Sortable) bool {
		return c1.(*DisplayEventDetailStats).JobIndex < c2.(*DisplayEventDetailStats).JobIndex
	}
	displayFunc := func(data uiCommon.IData, columnOwner uiCommon.IColumnOwner) string {
		cellStats := data.(*DisplayEventDetailStats)
		return util.FormatDisplayData(cellStats.JobIndex, defaultColSize)
	}
	rawValueFunc := func(data uiCommon.IData) string {
		cellStats := data.(*DisplayEventDetailStats)
		return cellStats.JobIndex
	}
	c := uiCommon.NewListColumn("JOB_IDX", "JOB_IDX", defaultColSize,
		uiCommon.ALPHANUMERIC, true, sortFunc, false, displayFunc, rawValueFunc, nil)
	return c
}

func columnIp() *uiCommon.ListColumn {
	defaultColSize := 16
	sortFunc := func(c1, c2 util.Sortable) bool {
		return util.Ip2long(c1.(*DisplayEventDetailStats).Ip) < util.Ip2long(c2.(*DisplayEventDetailStats).Ip)
	}
	displayFunc := func(data uiCommon.IData, columnOwner uiCommon.IColumnOwner) string {
		cellStats := data.(*DisplayEventDetailStats)
		return util.FormatDisplayData(cellStats.Ip, defaultColSize)
	}
	rawValueFunc := func(data uiCommon.IData) string {
		cellStats := data.(*DisplayEventDetailStats)
		return cellStats.Ip
	}
	c := uiCommon.NewListColumn("IP", "IP", defaultColSize,
		uiCommon.ALPHANUMERIC, true, sortFunc, false, displayFunc, rawValueFunc, nil)
	return c
}

func columnEventCount() *uiCommon.ListColumn {
	defaultColSize := 12
	sortFunc := func(c1, c2 util.Sortable) bool {
		return (c1.(*DisplayEventDetailStats).EventCount < c2.(*DisplayEventDetailStats).EventCount)
	}
	displayFunc := func(data uiCommon.IData, columnOwner uiCommon.IColumnOwner) string {
		stats := data.(*DisplayEventDetailStats)
		return fmt.Sprintf("%12v", util.Format(stats.EventCount))
	}
	rawValueFunc := func(data uiCommon.IData) string {
		stats := data.(*DisplayEventDetailStats)
		return fmt.Sprintf("%v", stats.EventCount)
	}
	c := uiCommon.NewListColumn("COUNT", "COUNT", defaultColSize,
		uiCommon.NUMERIC, false, sortFunc, true, displayFunc, rawValueFunc, nil)
	return c
}


text:
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <asm/types.h>
#include <linux/jffs2.h>
#include <lzo/lzo1x.h>
#include "compr.h"

extern int page_size;

static void *lzo_mem;
static void *lzo_compress_buf;

/*
 * Note about LZO compression.
 *
 * We want to use the _999_ compression routine which gives better compression
 * rates at the expense of time. Decompression time is unaffected. We might as
 * well use the standard lzo library routines for this but they will overflow
 * the destination buffer since they don't check the destination size.
 *
 * We therefore compress to a temporary buffer and copy if it will fit.
 *
 */
static int jffs2_lzo_cmpr(unsigned char *data_in, unsigned char *cpage_out,
			  uint32_t *sourcelen, uint32_t *dstlen, void *model)
{
	uint32_t compress_size;
	int ret;

	ret = lzo1x_999_compress(data_in, *sourcelen, lzo_compress_buf, &compress_size, lzo_mem);

	if (ret != LZO_E_OK)
		return -1;

	if (compress_size > *dstlen)
		return -1;

	memcpy(cpage_out, lzo_compress_buf, compress_size);
	*dstlen = compress_size;

	return 0;
}

static int jffs2_lzo_decompress(unsigned char *data_in, unsigned char *cpage_out,
				 uint32_t srclen, uint32_t destlen, void *model)
{
	int ret;
	uint32_t dl;

	ret = lzo1x_decompress_safe(data_in,srclen,cpage_out,&dl,NULL);

	if (ret != LZO_E_OK || dl != destlen)
		return -1;

	return 0;
}

static struct jffs2_compressor jffs2_lzo_comp = {
	.priority = JFFS2_LZO_PRIORITY,
	.name = "lzo",
	.compr = JFFS2_COMPR_LZO,
	.compress = &jffs2_lzo_cmpr,
	.decompress = &jffs2_lzo_decompress,
	.disabled = 1,
};

int jffs2_lzo_init(void)
{
	int ret;

	lzo_mem = malloc(LZO1X_999_MEM_COMPRESS);
	if (!lzo_mem)
		return -1;

	/* Worse case LZO compression size from their FAQ */
	lzo_compress_buf = malloc(page_size + (page_size / 16) + 64 + 3);
	if (!lzo_compress_buf) {
		free(lzo_mem);
		return -1;
	}

	ret = jffs2_register_compressor(&jffs2_lzo_comp);
	if (ret < 0) {
		free(lzo_compress_buf);
		free(lzo_mem);
	}

	return ret;
}

void jffs2_lzo_exit(void)
{
	jffs2_unregister_compressor(&jffs2_lzo_comp);
	free(lzo_compress_buf);
	free(lzo_mem);
}


text:
package status

import (
	"net/http"

	"github.com/mholt/caddy/caddyhttp/httpserver"
)

// Rule describes status rewriting rule
type Rule struct {
	// Base path. Request to this path and sub-paths will be answered with StatusCode
	Base string

	// Status code to return
	StatusCode int

	// Request matcher
	httpserver.RequestMatcher
}

// NewRule creates new Rule.
func NewRule(basePath string, status int) *Rule {
	return &Rule{
		Base:           basePath,
		StatusCode:     status,
		RequestMatcher: httpserver.PathMatcher(basePath),
	}
}

// BasePath implements httpserver.HandlerConfig interface
func (rule *Rule) BasePath() string {
	return rule.Base
}

// Status is a middleware to return status code for request
type Status struct {
	Rules []httpserver.HandlerConfig
	Next  httpserver.Handler
}

// ServeHTTP implements the httpserver.Handler interface
func (status Status) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	if cfg := httpserver.ConfigSelector(status.Rules).Select(r); cfg != nil {
		rule := cfg.(*Rule)

		if rule.StatusCode < 400 {
			// There's no ability to return response body --
			// write the response status code in header and signal
			// to other handlers that response is already handled
			w.WriteHeader(rule.StatusCode)
			return 0, nil
		}

		return rule.StatusCode, nil
	}

	return status.Next.ServeHTTP(w, r)
}


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

#pragma once

#include "EditorStyle.h"

/**
* Declares the Collision Analyzer window's visual style.
*/
class FCollisionAnalyzerStyle
{
public:

	class FStyle : public FSlateStyleSet
	{
	public:
		FStyle();

		void Initialize();
	};

	static void Initialize();

	static void Shutdown();

	static TSharedPtr<class ISlateStyle> Get();

	static TSharedPtr< FCollisionAnalyzerStyle::FStyle > StyleInstance;
};


text: export async function checkFiles() {}


text:
<html>
<head></head>
<body>
Classes for accessing files that contain dictionary information.
</body>
</html>


text:
"""
FIB Controller database (Portmap)
"""

import logging
from collections import namedtuple
from fabricflow.fibc.dbm.portmap import FIBCPort
from fabricflow.fibc.dbm.portmap import FIBCLink
from fabricflow.fibc.dbm.portmap import FIBCPortEntry

_LOG = logging.getLogger(__name__)

FIBMap = namedtuple('FIBMap', ("port", "link")) # port:FIBCPort, link:FIBCLink

def new_map_entry(dp_id, dp_port, re_id, name):
    """
    returns instance of FIBMap
    """
    port = FIBCPort(id=dp_id, port=dp_port)
    link = FIBCLink(re_id=re_id, name=name)
    return FIBMap(port=port, link=link)

class FIBMaps(object):
    """
    port-ifname mapping.
    """

    def __init__(self):
        self.ports = dict()
        self.links = dict()

    def insert(self, entry):
        """
        Insert entry(FIBMap)
        """
        if entry.port in self.ports or entry.link in self.links:
            raise KeyError

        self.ports[entry.port] = entry
        self.links[entry.link] = entry

    def find_by_port(self, dp_id, dp_port):
        """
        Select entry by port.
        """
        port = FIBCPort(id=dp_id, port=dp_port)
        return self.ports[port]

    def find_by_link(self, re_id, name):
        """
        Select entry by name.
        """
        link = FIBCLink(re_id=re_id, name=name)
        return self.links[link]

class FIBMapTable(object):
    """
    Table of FIBCPortEntry instances.
    """

    def __init__(self):
        self.entries = dict()
        self.maps = FIBMaps()

    def add(self, entry):
        """
        Insert entry(FIBCPortEntry)
        """
        key = entry["name"]
        self.entries[key] = entry
        return entry

    def insert_vm(self, re_id, name):
        """
        Insert entry(vm trigger)
        """
        mentry = self.maps.find_by_link(re_id, name)
        entry = FIBCPortEntry.new(
            dp_id=mentry.port.id,
            port=mentry.port.port,
            re_id=re_id,
            name=name,
        )

        return self.add(entry)

    def insert_dp(self, dp_id, dp_port):
        """
        Insert entry(dp trigger)
        """
        mentry = self.maps.find_by_port(dp_id, dp_port)
        entry = FIBCPortEntry.new(
            dp_id=dp_id,
            port=dp_port,
            re_id=mentry.link.re_id,
            name=mentry.link.name,
        )

        return self.add(entry)

    def delete_by_name(self, re_id, name):
        """
        Delete entry(vm trigger)
        """
        key = FIBCLink(re_id=re_id, name=name)
        if key in self.entries:
            return self.entries.pop(key, None)

        return None

    def find_by_key(self, key):
        """
        find entry by key(FIBCLink)
        """
        return self.entries.get(key, None)

    def find_by_name(self, re_id, name):
        """
        find entry by vm(re_id, ifname)
        """
        key = FIBCLink(re_id=re_id, name=name)
        return self.find_by_key(key)

    def find_by_dp(self, dp_id, dp_port):
        """
        find entry by dp(dp_id, dp_port)
        """
        key = FIBCPort(id=dp_id, port=dp_port)
        for entry in self.entries.values():
            if entry["dp"] == key:
                return entry

        return None

    def find_by_vs(self, vs_id, vs_port):
        """
        find entry by vs(vs_id, vs_port)
        """
        key = FIBCPort(id=vs_id, port=vs_port)
        for entry in self.entries.values():
            if entry["vs"] == key:
                return entry

        return None

    def list_by_link_ref(self, link):
        """
        Find port by link
        """
        entries = []
        for entry in self.entries.values():
            ref = entry.get("link", None)
            if ref is not None and ref == link:
                entries.append(entry)

        return sorted(entries)

    def subs(self, entry, exclude=True):
        """
        list sub interface entries(FIBCLink instances)
        """
        subs = self.list_by_link_ref(entry["name"])
        if not subs and not exclude:
            return [entry]

        entries = []
        for sub in subs:
            entries.extend(self.subs(sub), False)

        return entries

    def parent(self, entry):
        """
        find top of parent(FIBCLinl instance)
        """
        link = entry.get("link", None)
        if link is None:
            return entry

        return self.parent(self.find_by_key(link))


text:
/*******************************************************************************
* Author : Sagnik Chowdhury
* File   : Stream.cpp
* Brief  : Implementation of the stream class
*******************************************************************************/

#include "Stream.h"
#include <iostream>
#include <vulkan/vulkan.h>

namespace electron
{
    Stream::~Stream()
    {
        //Streams get killed automatically
        //We just need to return the used index to the stream manager
        std::cout << "\t\t\t\t\t\t> Stream destroyed" << std::endl;
    }

    const float& Stream::priority() const
    {
        return m_priority;
    }

    Stream::Family Stream::family() const
    {
        return m_familyIndex;
    }

    int Stream::index() const
    {
        return m_streamIndex;
    }

    void Stream::set_priority(float priority)
    {
        if(m_activated)
            return;

        m_priority = priority;
    }

    bool Stream::activate()
    {
        vkGetDeviceQueue(m_device, m_familyIndex, m_streamIndex, &m_queue);
        m_activated = true;
        return true;
    }

    // bool Stream::submit(std::initializer_list<CommandBuffer::Handle> commands,
    //                     std::initializer_list<Semaphore::Handle> waitSemaphores,
    //                     std::initializer_list<Semaphore::Handle> signalSemaphores)
    // {
    //     VkSubmitInfo submitInfo = {};
    //     submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
    //
    //     //TODO: Figure out a way to pass stages
    //     VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
    //
    // }

    bool Stream::submit(CommandBuffer::Handle command, Semaphore::Handle wait, Semaphore::Handle signal)
    {
        VkSubmitInfo submitInfo = {};
        submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;

        VkSemaphore waitSemaphores[] = {reinterpret_cast<VkSemaphore>(wait->getRawHandle())};
        VkPipelineStageFlags waitStages[] = {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT};
        submitInfo.waitSemaphoreCount = 1;
        submitInfo.pWaitSemaphores = waitSemaphores;
        submitInfo.pWaitDstStageMask = waitStages;

        submitInfo.commandBufferCount = 1;
        VkCommandBuffer cmd = reinterpret_cast<VkCommandBuffer>(command->getRawHandle());
        submitInfo.pCommandBuffers = &cmd;

        VkSemaphore signalSemaphores[] = {reinterpret_cast<VkSemaphore>(signal->getRawHandle())};
        submitInfo.signalSemaphoreCount = 1;
        submitInfo.pSignalSemaphores = signalSemaphores;

        if(vkQueueSubmit(m_queue, 1, &submitInfo, VK_NULL_HANDLE) != VK_SUCCESS)
            return false;

        return true;
    }

    bool Stream::present(SwapChain::Handle swapChain, uint32_t imgIndex, Semaphore::Handle wait)
    {
        VkPresentInfoKHR presentInfo = {};
        presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;

        presentInfo.waitSemaphoreCount = 1;
        VkSemaphore waitSemaphores[] = {reinterpret_cast<VkSemaphore>(wait->getRawHandle())};
        presentInfo.pWaitSemaphores = waitSemaphores;

        VkSwapchainKHR swapChains[] = {reinterpret_cast<VkSwapchainKHR>(swapChain->getRawHandle())};
        presentInfo.swapchainCount = 1;
        presentInfo.pSwapchains = swapChains;
        presentInfo.pImageIndices = &imgIndex;
        presentInfo.pResults = nullptr; // Optional

        if(vkQueuePresentKHR(m_queue, &presentInfo) != VK_SUCCESS)
            return false;

        return true;
    }

    void Stream::join()
    {
        vkQueueWaitIdle(m_queue);
    }

}


text:
using System.Collections.Generic;
using System.Text.Json;
using Azure;
using Azure.Core;
using Azure.ResourceManager.Network.Models;
using Azure.ResourceManager.Resources.Models;

namespace Azure.ResourceManager.Network
{
    public partial class ExpressRouteCrossConnectionData : IUtf8JsonSerializable
    {
        void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
        {
            writer.WriteStartObject();
            if (Optional.IsDefined(Id))
            {
                writer.WritePropertyName("id");
                writer.WriteStringValue(Id);
            }
            if (Optional.IsDefined(Location))
            {
                writer.WritePropertyName("location");
                writer.WriteStringValue(Location.Value);
            }
            if (Optional.IsCollectionDefined(Tags))
            {
                writer.WritePropertyName("tags");
                writer.WriteStartObject();
                foreach (var item in Tags)
                {
                    writer.WritePropertyName(item.Key);
                    writer.WriteStringValue(item.Value);
                }
                writer.WriteEndObject();
            }
            writer.WritePropertyName("properties");
            writer.WriteStartObject();
            if (Optional.IsDefined(ExpressRouteCircuit))
            {
                writer.WritePropertyName("expressRouteCircuit");
                JsonSerializer.Serialize(writer, ExpressRouteCircuit);
            }
            if (Optional.IsDefined(ServiceProviderProvisioningState))
            {
                writer.WritePropertyName("serviceProviderProvisioningState");
                writer.WriteStringValue(ServiceProviderProvisioningState.Value.ToString());
            }
            if (Optional.IsDefined(ServiceProviderNotes))
            {
                writer.WritePropertyName("serviceProviderNotes");
                writer.WriteStringValue(ServiceProviderNotes);
            }
            if (Optional.IsCollectionDefined(Peerings))
            {
                writer.WritePropertyName("peerings");
                writer.WriteStartArray();
                foreach (var item in Peerings)
                {
                    writer.WriteObjectValue(item);
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
            writer.WriteEndObject();
        }

        internal static ExpressRouteCrossConnectionData DeserializeExpressRouteCrossConnectionData(JsonElement element)
        {
            Optional<ETag> etag = default;
            Optional<ResourceIdentifier> id = default;
            Optional<string> name = default;
            Optional<ResourceType> type = default;
            Optional<AzureLocation> location = default;
            Optional<IDictionary<string, string>> tags = default;
            Optional<string> primaryAzurePort = default;
            Optional<string> secondaryAzurePort = default;
            Optional<int> sTag = default;
            Optional<string> peeringLocation = default;
            Optional<int> bandwidthInMbps = default;
            Optional<WritableSubResource> expressRouteCircuit = default;
            Optional<ServiceProviderProvisioningState> serviceProviderProvisioningState = default;
            Optional<string> serviceProviderNotes = default;
            Optional<NetworkProvisioningState> provisioningState = default;
            Optional<IList<ExpressRouteCrossConnectionPeeringData>> peerings = default;
            foreach (var property in element.EnumerateObject())
            {
                if (property.NameEquals("etag"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    etag = new ETag(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("id"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    id = new ResourceIdentifier(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("name"))
                {
                    name = property.Value.GetString();
                    continue;
                }
                if (property.NameEquals("type"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    type = new ResourceType(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("location"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    location = new AzureLocation(property.Value.GetString());
                    continue;
                }
                if (property.NameEquals("tags"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    Dictionary<string, string> dictionary = new Dictionary<string, string>();
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        dictionary.Add(property0.Name, property0.Value.GetString());
                    }
                    tags = dictionary;
                    continue;
                }
                if (property.NameEquals("properties"))
                {
                    if (property.Value.ValueKind == JsonValueKind.Null)
                    {
                        property.ThrowNonNullablePropertyIsNull();
                        continue;
                    }
                    foreach (var property0 in property.Value.EnumerateObject())
                    {
                        if (property0.NameEquals("primaryAzurePort"))
                        {
                            primaryAzurePort = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("secondaryAzurePort"))
                        {
                            secondaryAzurePort = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("sTag"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            sTag = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("peeringLocation"))
                        {
                            peeringLocation = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("bandwidthInMbps"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            bandwidthInMbps = property0.Value.GetInt32();
                            continue;
                        }
                        if (property0.NameEquals("expressRouteCircuit"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            expressRouteCircuit = JsonSerializer.Deserialize<WritableSubResource>(property0.Value.ToString());
                            continue;
                        }
                        if (property0.NameEquals("serviceProviderProvisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            serviceProviderProvisioningState = new ServiceProviderProvisioningState(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("serviceProviderNotes"))
                        {
                            serviceProviderNotes = property0.Value.GetString();
                            continue;
                        }
                        if (property0.NameEquals("provisioningState"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            provisioningState = new NetworkProvisioningState(property0.Value.GetString());
                            continue;
                        }
                        if (property0.NameEquals("peerings"))
                        {
                            if (property0.Value.ValueKind == JsonValueKind.Null)
                            {
                                property0.ThrowNonNullablePropertyIsNull();
                                continue;
                            }
                            List<ExpressRouteCrossConnectionPeeringData> array = new List<ExpressRouteCrossConnectionPeeringData>();
                            foreach (var item in property0.Value.EnumerateArray())
                            {
                                array.Add(ExpressRouteCrossConnectionPeeringData.DeserializeExpressRouteCrossConnectionPeeringData(item));
                            }
                            peerings = array;
                            continue;
                        }
                    }
                    continue;
                }
            }
            return new ExpressRouteCrossConnectionData(id.Value, name.Value, Optional.ToNullable(type), Optional.ToNullable(location), Optional.ToDictionary(tags), Optional.ToNullable(etag), primaryAzurePort.Value, secondaryAzurePort.Value, Optional.ToNullable(sTag), peeringLocation.Value, Optional.ToNullable(bandwidthInMbps), expressRouteCircuit, Optional.ToNullable(serviceProviderProvisioningState), serviceProviderNotes.Value, Optional.ToNullable(provisioningState), Optional.ToList(peerings));
        }
    }
}


text:
<?php
/**
 * [PHPFOX_HEADER]
 */

defined('PHPFOX') or exit('NO DICE!');

class YounetCore_Component_Block_view extends Phpfox_Component
{
	/**
	 * Class process method wnich is used to execute this component.
	 */
	public function process()
	{

		return 'block';
	}

	/**
	 * Garbage collector. Is executed after this class has completed
	 * its job and the template has also been displayed.
	 */
	public function clean()
	{
		(($sPlugin = Phpfox_Plugin::get('core.component_block_news_clean')) ? eval($sPlugin) : false);
	}
}

?>


text:
MIPS-coding-collection
======================

Different algorithms implemented in MIPS, This is hard to debug, tools for debugging this architecture are clunky and slow. this is for learning purposes only.


text:
package org.opensmartgridplatform.adapter.ws.core.application.mapping;

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Before;
import org.junit.Test;
import org.opensmartgridplatform.adapter.ws.schema.core.deviceinstallation.Device;
import org.opensmartgridplatform.domain.core.entities.Ssld;

public class DeviceInstallationMapperTest {

    private final static String DEVICE_IDENTIFICATION = "device_identification";
    private final static String ALIAS = "alias";
    private final static String CITY = "city";
    private final static String POSTAL_CODE = "postal_code";
    private final static String STREET = "street";
    private final static String NUMBER = "number";
    private final static String MUNICIPALITY = "municipality";
    private final static float GPS_LATITUDE = 50f;
    private final static float GPS_LONGITUDE = 5f;
    private final static boolean PUBLIC_KEY_PRESENT = true;

    DeviceInstallationMapper mapper = new DeviceInstallationMapper();

    @Before
    public void setup() {
        this.mapper.initialize();
    }

    @Test
    public void shouldConvertWsDeviceToSsld() {
        // given
        final Device device = this.createDevice();

        // when
        final Ssld ssld = this.mapper.map(device, Ssld.class);

        // then
        assertThat(ssld.getDeviceIdentification()).isEqualTo(DEVICE_IDENTIFICATION);
        assertThat(ssld.getAlias()).isEqualTo(ALIAS);
        assertThat(ssld.getContainerAddress()).isNotNull();
        assertThat(ssld.getContainerAddress().getCity()).isEqualTo(CITY);
        assertThat(ssld.getContainerAddress().getPostalCode()).isEqualTo(POSTAL_CODE);
        assertThat(ssld.getGpsCoordinates().getLatitude()).isEqualTo(GPS_LATITUDE);
        assertThat(ssld.getGpsCoordinates().getLongitude()).isEqualTo(GPS_LONGITUDE);
        assertThat(ssld.isPublicKeyPresent()).isEqualTo(PUBLIC_KEY_PRESENT);
    }

    private Device createDevice() {
        final Device device = new Device();
        device.setDeviceIdentification(DEVICE_IDENTIFICATION);
        device.setAlias(ALIAS);
        device.setContainerCity(CITY);
        device.setContainerPostalCode(POSTAL_CODE);
        device.setContainerStreet(STREET);
        device.setContainerNumber(NUMBER);
        device.setContainerMunicipality(MUNICIPALITY);
        device.setGpsLatitude(GPS_LATITUDE);
        device.setGpsLongitude(GPS_LONGITUDE);
        device.setPublicKeyPresent(PUBLIC_KEY_PRESENT);
        return device;
    }
}


text:
/*globals define,  _*/
/*jshint browser: true*/

/**
 * @author rkereskenyi / https://github.com/rkereskenyi
 */

define(['js/PanelBase/PanelBaseWithHeader',
    'js/Widgets/PartBrowser/PartBrowserWidget',
    './PartBrowserPanelControl'
], function (PanelBaseWithHeader,
             PartBrowserWidget,
             PartBrowserPanelControl) {
    'use strict';

    var PartBrowserPanel,
        __parent__ = PanelBaseWithHeader;

    PartBrowserPanel = function (layoutManager, params) {
        var options = {};
        //set properties from options
        options[PanelBaseWithHeader.OPTIONS.LOGGER_INSTANCE_NAME] = 'PartBrowserPanel';
        options[PanelBaseWithHeader.OPTIONS.HEADER_TITLE] = false;

        //call parent's constructor
        __parent__.apply(this, [options]);

        this._client = params.client;

        //initialize UI
        this._initialize();

        this.logger.debug('PartBrowserPanel ctor finished');
    };

    //inherit from PanelBaseWithHeader
    _.extend(PartBrowserPanel.prototype, __parent__.prototype);

    PartBrowserPanel.prototype._initialize = function () {
        //set Widget title
        this.setTitle('Part Browser');

        this._partBrowserWidget = new PartBrowserWidget(this.$el);

        this._panelControl = new PartBrowserPanelControl(this._client, this._partBrowserWidget);
    };

    /* OVERRIDE FROM WIDGET-WITH-HEADER */
    /* METHOD CALLED WHEN THE WIDGET'S READ-ONLY PROPERTY CHANGES */
    PartBrowserPanel.prototype.onReadOnlyChanged = function (isReadOnly) {
        //apply parent's onReadOnlyChanged
        __parent__.prototype.onReadOnlyChanged.call(this, isReadOnly);

        this._partBrowserWidget.setReadOnly(isReadOnly);
    };

    return PartBrowserPanel;
});


text:
package brlyman.results;

/**
 * Represents a test which passed.
 */
public class Pass implements Result
{
    public Pass(final String test_name)
    {
        this.test_name = test_name;
    }

    @Override
    public String name()
    {
        return test_name;
    }

    @Override
    public String message()
    {
        return "✔";
    }

    @Override
    public void apply(Process process)
    {
        process.forPass(this);
    }

    private final String test_name;
}