text:
using HarmonyLib;
using UnityEngine;
using Verse;
using RimWorld;
using System.Linq;
using System.Collections.Generic;
using Verse.Sound;

namespace BetterPawnControl.Patches
{

    [HarmonyPatch(typeof(PawnTable), nameof(PawnTable.PawnTableOnGUI))]
    static class PawnTable_PawnTableOnGUI
    {
        private const string NUMBERS_DEFNAME = "Numbers_Animals";

        static void Postfix(PawnTable __instance, Vector2 position, PawnTableDef ___def)
        {

            if (___def == PawnTableDefOf.Assign)
            {
                DrawAssignBPCButtons(__instance, position);
            }

            if (___def == PawnTableDefOf.Restrict)
            {
                DrawSheduleBPCButtons(__instance, position);
            }

            if (___def == PawnTableDefOf.Work && !Widget_ModsAvailable.DisableBPCOnWorkTab)
            {
                DrawWorkBPCButtons(__instance, position);
            }

            if (___def == PawnTableDefOf.Animals || ___def.defName == NUMBERS_DEFNAME)
            {
                DrawAnimalBPCButtons(__instance, position);
            }

            if (___def == PawnTableDefOf.Mechs )
            {
                DrawMechBPCButtons(__instance, position);
            }
        }

        private static void DrawWorkBPCButtons(PawnTable __instance, Vector2 position)
        {
            if (WorkManager.DirtyPolicy)
            {
                WorkManager.LoadState(WorkManager.links, WorkManager.Colonists().ToList(), WorkManager.GetActivePolicy());
                WorkManager.DirtyPolicy = false;
            }

            DrawBPCButtons_WorkTab(position, 5f, __instance.Size.y + 15f, WorkManager.Colonists().ToList());
        }

        private static void DrawAnimalBPCButtons(PawnTable __instance, Vector2 position)
        {
            if (AnimalManager.DirtyPolicy)
            {
                AnimalManager.LoadState(AnimalManager.links, AnimalManager.Animals().ToList(), AnimalManager.GetActivePolicy());
                AnimalManager.DirtyPolicy = false;
            }

            if (Widget_ModsAvailable.AnimalTabAvailable)
            {
                position.x += 40f;
                position.y += 7f;
            }

            DrawBPCButtons_AnimalTab(position, 5f, __instance.Size.y + 15f);
        }

        private static void DrawSheduleBPCButtons(PawnTable __instance, Vector2 position)
        {
            if (ScheduleManager.DirtyPolicy)
            {
                ScheduleManager.LoadState(ScheduleManager.links, ScheduleManager.Colonists().ToList(), ScheduleManager.GetActivePolicy());
                ScheduleManager.DirtyPolicy = false;
            }

            if (Widget_ModsAvailable.CSLAvailable)
            {
                position.x += 87f;
            }

            DrawBPCButtons_ScheduleTab(position, 5f, __instance.Size.y + 15f, ScheduleManager.Colonists().ToList());
        }

        private static void DrawAssignBPCButtons(PawnTable __instance, Vector2 position)
        {
            if (AssignManager.DirtyPolicy)
            {
                AssignManager.LoadState(AssignManager.links, AssignManager.Colonists().ToList(), AssignManager.GetActivePolicy());
                AssignManager.DirtyPolicy = false;
            }

            DrawBPCButtons_AssignTab(position, 5f, __instance.Size.y + 15f, AssignManager.Colonists().ToList());
        }

        private static void DrawMechBPCButtons(PawnTable __instance, Vector2 position)
        {
            if (MechManager.DirtyPolicy)
            {
                MechManager.LoadState(MechManager.links, MechManager.Mechs().ToList(), MechManager.GetActivePolicy());
                MechManager.DirtyPolicy = false;
            }

            DrawBPCButtons_MechTab(position, 5f, __instance.Size.y + 15f);
        }

        private static void DrawBPCButtons_AssignTab(Vector2 position, float X_ExtraSpace, float Y_ExtraSpace, List<Pawn> colonists)
        {

            Rect pos = new Rect(position.x + X_ExtraSpace, position.y + Y_ExtraSpace, 600f, 65f);
            float offSetX = 0f;

            GUI.BeginGroup(pos);

            Text.Font = GameFont.Tiny;
            Text.Anchor = TextAnchor.LowerCenter;
            Rect rect1 = new Rect(offSetX, -8f, 165f, Mathf.Round(pos.height / 3f));
            Widgets.Label(rect1, "BPC.CurrentAssignPolicy".Translate());

            Text.Font = GameFont.Small;
            Text.Anchor = TextAnchor.UpperLeft;
            Rect rect2 = new Rect(offSetX, Mathf.Round(pos.height / 4f) - 4f, rect1.width, Mathf.Round(pos.height / 4f) + 4f);

            if (Widgets.ButtonText(rect2, AssignManager.GetActivePolicy().label, true, false, true))
            {
                AssignManager.SaveCurrentState(colonists);
                OpenAssignPolicySelectMenu(AssignManager.links, colonists);
            }

            offSetX += rect1.width;
            Rect rect3 = new Rect(offSetX, 0f, 20f, Mathf.Round(pos.height / 2f));
            if (Widgets.ButtonText(rect3, "", true, false, true))
            {
                Find.WindowStack.Add(new Dialog_ManagePolicies(Find.CurrentMap));
            }
            Rect rect4 = new Rect(offSetX + 3f, rect3.height / 4f, 14f, 14f);
            GUI.DrawTexture(rect4, Resources.Textures.Settings);
            TooltipHandler.TipRegion(rect4, "BPC.Settings".Translate());

            offSetX += rect3.width;
            Rect rect5 = new Rect(offSetX + 3f, rect3.height / 4f - 6f, 21f, 28f);
            if (Widgets.ButtonImage(rect5, ContentFinder<Texture2D>.Get("UI/Buttons/Copy", true)))
            {
                AssignManager.CopyToClipboard();
                SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
                AssignManager.showPaste = true;
            }
            TooltipHandler.TipRegion(rect5, "BPC.Copy".Translate());

            if (AssignManager.showPaste)
            {
                offSetX += rect3.width;
                Rect rect6 = new Rect(offSetX + 3f, rect3.height / 4f - 6f, 21f, 28f);
                if (Widgets.ButtonImage(rect6, ContentFinder<Texture2D>.Get("UI/Buttons/Paste", true)))
                {
                    AssignManager.PasteToActivePolicy();
                    SoundDefOf.Tick_Low.PlayOneShotOnCamera(null);
                }
                TooltipHandler.TipRegion(rect6, "BPC.Paste".Translate());
            }

            GUI.EndGroup();
        }

        private static void OpenAssignPolicySelectMenu(List<AssignLink> links, List<Pawn> pawns)
        {
            List<FloatMenuOption> list = new List<FloatMenuOption>();

            foreach (Policy assignPolicy in AssignManager.policies)
            {
                list.Add(
                    new FloatMenuOption(assignPolicy.label,
                        delegate
                        {
                            AssignManager.LoadState(links, pawns, assignPolicy);
                        },
                        MenuOptionPriority.Default, null, null, 0f, null));
            }
            Find.WindowStack.Add(new FloatMenu(list));
        }

        private static void DrawBPCButtons_ScheduleTab(Vector2 position, float X_ExtraSpace, float Y_ExtraSpace, List<Pawn> colonists)
        {

            Rect pos = new Rect(position.x + X_ExtraSpace, position.y + Y_ExtraSpace, 600f, 65f);
            float offSetX = 0f;

            GUI.BeginGroup(pos);

            Text.Font = GameFont.Tiny;
            Text.Anchor = TextAnchor.LowerCenter;
            Rect rect1 = new Rect(offSetX, -8f, 165f, Mathf.Round(pos.height / 3f));
            Widgets.Label(rect1, "BPC.CurrentRestrictPolicy".Translate());

            Text.Font = GameFont.Small;
            Text.Anchor = TextAnchor.UpperLeft;
            Rect rect2 = new Rect(offSetX, Mathf.Round(pos.height / 4f) - 4f, rect1.width, Mathf.Round(pos.height / 4f) + 4f);

            if (Widgets.ButtonText(rect2, ScheduleManager.GetActivePolicy().label, true, false, true))
            {
                ScheduleManager.SaveCurrentState(colonists);
                OpenSchedulePolicySelectMenu(ScheduleManager.links, colonists);
            }
            offSetX += rect1.width;
            Rect rect3 = new Rect(offSetX, 0f, 20f, Mathf.Round(pos.height / 2f));
            if (Widgets.ButtonText(rect3, "", true, false, true))
            {
                Find.WindowStack.Add(new Dialog_ManagePolicies(Find.CurrentMap));
            }
            Rect rect4 = new Rect(offSetX + 3f, rect3.height / 4f, 14f, 14f);
            GUI.DrawTexture(rect4, Resources.Textures.Settings);
            TooltipHandler.TipRegion(rect4, "BPC.Settings".Translate());

            offSetX += rect3.width;
            Rect rect5 = new Rect(offSetX + 3f, rect3.height / 4f - 6f, 21f, 28f);
            if (Widgets.ButtonImage(rect5, ContentFinder<Texture2D>.Get("UI/Buttons/Copy", true)))
            {
                ScheduleManager.CopyToClipboard();
                SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
                ScheduleManager.showPaste = true;
            }
            TooltipHandler.TipRegion(rect5, "BPC.CopySchedule".Translate());

            if (ScheduleManager.showPaste)
            {
                offSetX += rect3.width;
                Rect rect6 = new Rect(offSetX + 3f, rect3.height / 4f - 6f, 21f, 28f);
                if (Widgets.ButtonImage(rect6, ContentFinder<Texture2D>.Get("UI/Buttons/Paste", true)))
                {
                    ScheduleManager.PasteToActivePolicy();
                    SoundDefOf.Tick_Low.PlayOneShotOnCamera(null);
                }
                TooltipHandler.TipRegion(rect6, "BPC.PasteSchedule".Translate());
            }
            GUI.EndGroup();
        }

        private static void OpenSchedulePolicySelectMenu(List<ScheduleLink> links, List<Pawn> pawns)
        {
            List<FloatMenuOption> list = new List<FloatMenuOption>();

            foreach (Policy restrictPolicy in ScheduleManager.policies)
            {
                list.Add(
                    new FloatMenuOption(restrictPolicy.label,
                        delegate
                        {
                            ScheduleManager.LoadState(links, pawns, restrictPolicy);
                        },
                        MenuOptionPriority.Default, null, null, 0f, null));
            }
            Find.WindowStack.Add(new FloatMenu(list));
        }

        private static void DrawBPCButtons_WorkTab(Vector2 position, float X_ExtraSpace, float Y_ExtraSpace, List<Pawn> colonists)
        {
            Rect pos = new Rect(position.x + X_ExtraSpace, position.y + Y_ExtraSpace, 600f, 65f);
            float offSetX = 0f;

            GUI.BeginGroup(pos);

            Text.Font = GameFont.Tiny;
            Text.Anchor = TextAnchor.LowerCenter;
            Rect rect1 = new Rect(offSetX, -8f, 165f, Mathf.Round(pos.height / 3f));
            Widgets.Label(rect1, "BPC.CurrentWorkPolicy".Translate());

            Text.Font = GameFont.Small;
            Text.Anchor = TextAnchor.UpperLeft;
            Rect rect2 = new Rect( offSetX, Mathf.Round(pos.height / 4f) - 4f,
                rect1.width, Mathf.Round(pos.height / 4f) + 4f);

            if (Widgets.ButtonText(rect2, WorkManager.GetActivePolicy().label, true, false, true))
            {
                WorkManager.SaveCurrentState(colonists);
                OpenWorkPolicySelectMenu(WorkManager.links, colonists);
            }
            offSetX += rect1.width;
            Rect rect3 = new Rect(offSetX, 0f, 20f, Mathf.Round(pos.height / 2f));
            if (Widgets.ButtonText(rect3, "", true, false, true))
            {
                Find.WindowStack.Add(new Dialog_ManagePolicies(Find.CurrentMap));
            }
            Rect rect4 = new Rect(offSetX + 3f, rect3.height / 4f, 14f, 14f);
            GUI.DrawTexture(rect4, Resources.Textures.Settings);
            TooltipHandler.TipRegion(rect4, "BPC.Settings".Translate());

            offSetX += rect3.width;
            Rect rect5 = new Rect(offSetX + 3f, rect3.height / 4f - 6f, 21f, 28f);
            if (Widgets.ButtonImage(rect5, ContentFinder<Texture2D>.Get("UI/Buttons/Copy", true)))
            {
                WorkManager.CopyToClipboard();
                SoundDefOf.Tick_High.PlayOneShotOnCamera(null);
                WorkManager.showPaste = true;
            }
            TooltipHandler.TipRegion(rect5, "BPC.Copy".Translate());

            if (WorkManager.showPaste)
            {
                offSetX += rect3.width;
                Rect rect6 = new Rect(offSetX + 3f, rect3.height / 4f - 6f, 21f, 28f);
                if (Widgets.ButtonImage(rect6, ContentFinder<Texture2D>.Get("UI/Buttons/Paste", true)))
                {
                    WorkManager.PasteToActivePolicy();
                    SoundDefOf.Tick_Low.PlayOneShotOnCamera(null);
                }
                TooltipHandler.TipRegion(rect6, "BPC.Paste".Translate());
            }
            GUI.EndGroup();
        }

        internal static void OpenWorkPolicySelectMenu(
            List<WorkLink> links, List<Pawn> pawns)
        {
            List<FloatMenuOption> list = new List<FloatMenuOption>();

            foreach (Policy workPolicy in WorkManager.policies)
            {
                list.Add(
                    new FloatMenuOption(workPolicy.label,
                        delegate
                        {
                            WorkManager.LoadState(links, pawns, workPolicy);
                        },
                        MenuOptionPriority.Default, null, null, 0f, null));
            }
            Find.WindowStack.Add(new FloatMenu(list));
        }

        private static void DrawBPCButtons_AnimalTab(Vector2 position, float X_ExtraSpace, float Y_ExtraSpace)
        {
            Rect pos = new Rect(position.x + X_ExtraSpace, position.y + Y_ExtraSpace, 600f, 65f);
            float offSetX = 0f;

            GUI.BeginGroup(pos);
            Text.Font = GameFont.Tiny;
            Text.Anchor = TextAnchor.LowerCenter;
            Rect rect1 = new Rect(offSetX, -8f, 165f, Mathf.Round(pos.height / 3f));
            Widgets.Label(rect1, "BPC.CurrentAnimalPolicy".Translate());

            Text.Font = GameFont.Small;
            Text.Anchor = TextAnchor.UpperLeft;
            Rect rect2 = new Rect(offSetX, Mathf.Round(pos.height / 4f) - 4f, rect1.width, Mathf.Round(pos.height / 4f) + 4f);

            if (Widgets.ButtonText(rect2, AnimalManager.GetActivePolicy().label, true, false, true))
            {
                AnimalManager.SaveCurrentState(AnimalManager.Animals().ToList());
                OpenAnimalPolicySelectMenu(AnimalManager.links, AnimalManager.Animals().ToList());
            }
            offSetX += rect1.width;
            Rect rect3 = new Rect(offSetX, 0f, 20f, Mathf.Round(pos.height / 2f));

            if (Widgets.ButtonText(rect3, "", true, false, true))
            {
                Find.WindowStack.Add( new Dialog_ManagePolicies(Find.CurrentMap));
            }
            Rect rect4 = new Rect(offSetX + 3f, rect3.height / 4f, 14f, 14f);
            GUI.DrawTexture(rect4, Resources.Textures.Settings);
            TooltipHandler.TipRegion(rect4, "BPC.Settings".Translate());

            GUI.EndGroup();
        }

        private static void OpenAnimalPolicySelectMenu(List<AnimalLink> links, List<Pawn> pawns)
        {
            List<FloatMenuOption> list = new List<FloatMenuOption>();

            foreach (Policy animalPolicy in AnimalManager.policies)
            {
                list.Add(
                    new FloatMenuOption(animalPolicy.label,
                        delegate
                        {
                            AnimalManager.LoadState( links, pawns, animalPolicy);
                        },
                        MenuOptionPriority.Default, null, null, 0f, null));
            }
            Find.WindowStack.Add(new FloatMenu(list));
        }

        private static void DrawBPCButtons_MechTab(Vector2 position, float X_ExtraSpace, float Y_ExtraSpace)
        {
            Rect pos = new Rect(position.x + X_ExtraSpace, position.y + Y_ExtraSpace, 600f, 65f);
            float offSetX = 0f;

            GUI.BeginGroup(pos);
            Text.Font = GameFont.Tiny;
            Text.Anchor = TextAnchor.LowerCenter;
            Rect rect1 = new Rect(offSetX, -8f, 165f, Mathf.Round(pos.height / 3f));
            Widgets.Label(rect1, "BPC.CurrentMechPolicy".Translate());

            Text.Font = GameFont.Small;
            Text.Anchor = TextAnchor.UpperLeft;
            Rect rect2 = new Rect(offSetX, Mathf.Round(pos.height / 4f) - 4f, rect1.width, Mathf.Round(pos.height / 4f) + 4f);

            if (Widgets.ButtonText(rect2, MechManager.GetActivePolicy().label, true, false, true))
            {
                MechManager.SaveCurrentState(MechManager.Mechs().ToList());;
                OpenMechPolicySelectMenu(MechManager.links, MechManager.Mechs().ToList());
            }
            offSetX += rect1.width;
            Rect rect3 = new Rect(offSetX, 0f, 20f, Mathf.Round(pos.height / 2f));

            if (Widgets.ButtonText(rect3, "", true, false, true))
            {
                Find.WindowStack.Add(new Dialog_ManagePolicies(Find.CurrentMap));
            }
            Rect rect4 = new Rect(offSetX + 3f, rect3.height / 4f, 14f, 14f);
            GUI.DrawTexture(rect4, Resources.Textures.Settings);
            TooltipHandler.TipRegion(rect4, "BPC.Settings".Translate());

            GUI.EndGroup();
        }

        private static void OpenMechPolicySelectMenu( List<MechLink> links, List<Pawn> pawns)
        {
            List<FloatMenuOption> list = new List<FloatMenuOption>();

            foreach (Policy mechPolicy in MechManager.policies)
            {
                list.Add(
                    new FloatMenuOption(mechPolicy.label,
                        delegate
                        {
                            MechManager.LoadState(links, pawns, mechPolicy);
                        },
                        MenuOptionPriority.Default, null, null, 0f, null));
            }
            Find.WindowStack.Add(new FloatMenu(list));
        }

    }
}


text:
from django.core.mail import send_mail
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from contact.forms import ContactForm

def contact(request):
    # errors = []
    if request.method == 'POST':
        """

        Validation form to be replaced

        if not request.POST.get('subject', ''):
            errors.append('Enter a subject.')
        if not request.POST.get('message', ''):
            errors.append('Enter a message')
        if request.POST.get('email') and '@' not in request.POST['email']:
            errors.append('Enter a valid e-mail address.')
        if not errors:
            send_mail(
                request.POST['subject'],
                request.POST['message'],
                request.POST.get('email', 'noreply@example.com'),
                ['siteowner@example.com'],
            )
        """
        form = ContactForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            send_mail(
                cd['subject'],
                cd['message'],
                cd.get('email', 'noreply@example.com'),
                ['siteowner@example.com']
            )
            return HttpResponseRedirect('/contact/thanks')
    else:
        form = ContactForm(
            initial={'subject': 'I love your site!'}
        )

    return render(request, 'contact_form.html', {'form': form})

def thanks(request):
    return HttpResponse('Ty!')

redpajama_set_name: RedPajamaGithub


text:
import Component from '@ember/component';
import { setProperties, getProperties, computed, get, set } from '@ember/object';
import buildSaneRegExp from 'wherehows-web/utils/validators/regexp';

// A default static list of page lengths
const defaultPageLengths = [10, 50, 100];

export default Component.extend({
  tagName: 'table',
  classNames: ['nacho-table nacho-table--bordered'],
  tableHeaderComponent: 'dataset-table-header',
  tableBodyComponent: 'dataset-table-body',
  tableRowComponent: 'dataset-table-row',
  tableFooterComponent: 'dataset-table-footer',
  sortDirection: 'asc',
  sortColumnWithName: null,
  page: 1,
  pageLengths: defaultPageLengths,

  /**
   * Initially sets the number of rows to be displayed in the table
   * to the first item found in the pageLengths, default or runtime.
   * Will reset to first element on subsequent updates or set value
   */
  limit: computed('pageLengths', function() {
    // Defaulting operation in the event the pageLengths is set to an falsey
    // value
    return get(this, 'pageLengths.firstObject') || defaultPageLengths.firstObject;
  }),

  /**
   * Builds the regular expression filter based on the search term if provided, otherwise null
   * @type {ComputedProperty<null|RegExp>}
   */
  fieldFilter: computed('searchTerm', function() {
    const searchTerm = get(this, 'searchTerm');
    if (searchTerm) {
      return buildSaneRegExp(searchTerm, 'i');
    }

    return null;
  }),

  /**
   * Check if the searchTerm occurs anywhere in the field name
   * @type {DatasetTable.fields}
   */
  data: computed('fields', 'fieldFilter', function() {
    const { fieldFilter, fields = [] } = getProperties(this, ['fieldFilter', 'fields']);

    return fieldFilter ? fields.filter(field => fieldFilter.test(String(field[get(this, 'filterBy')]))) : fields;
  }),

  sortBy: computed('sortColumnWithName', 'sortDirection', function() {
    const { sortColumnWithName, sortDirection } = this.getProperties('sortColumnWithName', 'sortDirection');
    return `${sortColumnWithName}:${sortDirection}`;
  }).readOnly(),

  beginOffset: computed('page', 'limit', function() {
    return (get(this, 'page') - 1) * get(this, 'limit');
  }),

  endOffset: computed('beginOffset', function() {
    return get(this, 'beginOffset') + get(this, 'limit');
  }),

  actions: {
    sortDidChange(sortColumnWithName = null, sortDirection = 'asc') {
      if (!sortColumnWithName) {
        throw new Error(
          `Valid name not provided for table column sorting.
      Ensure that you have provided adequate arguments to sort change handler action.`
        );
      }

      return setProperties(this, {
        sortColumnWithName,
        sortDirection
      });
    },

    filterDidChange(searchTerm) {
      this.set('searchTerm', searchTerm);
      get(this, 'actions.pageDidChange').call(this);
    },

    pageDidChange(page = 1) {
      set(this, 'page', page);
    },

    limitDidChange(limit) {
      if (get(this, 'pageLengths').includes(limit)) {
        set(this, 'limit', limit);
      }
    }
  }
});


text:
author: Livid
date: 2009-05-16 20:19:48+00:00
title: Сборка QtiPlot под Windows
wordpress_id: 297
tags: qtiplot, Windows ,Windows
...

Это, конечно, оффтопик, но собирать qtiplot под windows проходится долго
и мучительно, а это иногда бывает нужно во враждебном windows-окружении.
"С нахрапу" qtiplot не собирается, и приличных гайдов я не видел. То,
что предсталено ниже есть продукт личных проб и ошибок.

<!--more-->

Введение
========

Итак, для сборки, помимо, собственно, исходников qtiplot, и MinGW
потребуются:

-   Qt версии 4.4.0 или выше (на мой взгляд, либо 4.4.3, либо 4.5.1,
    работает и так и эдак)
-   Qwt версии 5.2.0 (я предпочитаю сборку той же версии из SVN)
-   GSL (проще всего под Win найти версию 1.8, и она вполне подойдет для
    наших прозаических нужд)
-   muParser версии 1.28
-   zlib
-   опционально libpng
-   BOOST C++ Libraries версии 1.36.0 (хотя 1.37.0 тоже работает, как
    показал эксперимент)
-   Опционально [Python 2.5](http://www.python.org/),
    [SIP](http://www.riverbankcomputing.co.uk/software/sip/download),
    [PyQt](http://www.riverbankcomputing.co.uk/software/pyqt/download)

MinGW можно (и, даже, пожалуй, стоит) поставить при помощи инсталлятора
Qt. Это и удобнее и поставится нужная версия. Хотя если MinGW уже есть,
то лцчше использовать его.
Скачать библиотеки Qt можно здесь:
<http://www.qtsoftware.com/downloads>. Рекомендую ограничиться
библиотеками.

Перед сборкой следует убедиться, что пути с qmake и mingw32-make
находиться в PATH (по умолчанию qmake ставится в C:\\Qt\\\\bin,
mingw32-make в C:\\MinGW\\bin)

Переходим к сборке компонент.

MuParser
========

Сразу оговорюсь, все исходники у меня лежат в C:\\build\\.
Соответственно все команды даются с учетом этого факта. Подставьте свой
путь при необходимости.
Скачать muparser можно здесь:
<http://sourceforge.net/project/showfiles.php?group_id=137191&package_id=150725>
Полученный архив надо распаковать (я распаковал в C:\\build)
Дальше нужно открыть командную строку (Пуск-Выполнить-cmd), и там:

    cd C:\build\muparser\build
    mingw32-make -f makefile.mingw

Qwt
===

Взять исходники Qwt 5.2.0 можно здесь:
http://sourceforge.net/project/showfiles.php?group\_id=13693&package\_id=11488
Однако, они поставляются для сборки динамичкеской библиотеки, а qtiplot
требует статической линковки. Поэтому, распаковав qwt в C:\\build,
открываем C:\\build\\qwt-5.2.0\\qwtconfig.pri
И исправляем:

        # Qt 4
        win32 {
            # On Windows you can't mix release and debug libraries.
            # The designer is built in release mode. If you like to use it
            # you need a release version. For your own application development you
            # might need a debug version.
            # Enable debug_and_release + build_all if you want to build both.

            CONFIG           += release     # release/debug/debug_and_release
            #CONFIG           += release_and_release
            #CONFIG           += build_all
        }

на

        # Qt 4
        win32 {
            # On Windows you can't mix release and debug libraries.
            # The designer is built in release mode. If you like to use it
            # you need a release version. For your own application development you
            # might need a debug version.
            # Enable debug_and_release + build_all if you want to build both.

            CONFIG           += debug     # release/debug/debug_and_release
            #CONFIG           += release_and_release
            #CONFIG           += build_all
        }

и

    CONFIG           += QwtDll

на

    CONFIG           -= QwtDll

После этого можно собирать:

    cd С:\build\qwt-5.2.0
    qmake -recursive && mingw32-make

zlib
====

zlib можно просто скачать, но я предпочитаю собрать. Исходники берутся с
<http://zlib.net/>
Дальше все довольно тривиально:

    cd E:\build\zlib-1.2.3
    mingw32-make -f win32\Makefile.gcc

BOOST C++
=========

Берется отсюда: <http://www.boost.org/users/history/>
Желательно взять версию 1.36.0. Распаковываем, опять же, в C:\\build.
Помимо, собственно, boost, следует так же скачать BOOST JAM отсюда:
<http://www.boost.org/users/history/>
После этого можно перейти к сборке. Нам на самом деле нужно собрать
всего две библиотеки:

    cd E:\build\boost_1_36_0
    bjam --build-dir=..\boost-build --toolset=gcc --build-type=minimal --link=static --variant=release --runtime-link=static --with-date_time --with-thread stage

GSL
===

Проще всего -- скачать:
<http://gnuwin32.sourceforge.net/packages/gsl.htm>
Нас интересует только "Developer files" (gsl-1.8-lib.zip)

QtiPlot
=======

Я не стану останавливаться на сборке libpng, а так же установке Python,
SIP, PyQt, это опционально, тривиально, и в сети полно описаний. Поэтому
переходим сразу к qtiplot.
Для начала, я не стал собирать мануалы (для них нужен еще целый ворох
программ, я решил что они ни к чему) Поэтому из файла
C:\\build\\qtiplot\\qtiplot.pro сразу убирается строка

           manual

Далее, если мы не хотим Python, то в файле
С:\\build\\qtiplot\\qtiplot\\qtiplot.pro нужно заккоментировать строку

    SCRIPTING_LANGS += Python

(нужно добавить в начало строки решетку, да)

Если мы решаем, что нам лень собирать libpng, то следует так же
закомментировать строку

    CONFIG          += HAVE_LIBPNG

или засунуть libpng.a и заголовки в
C:\\build\\qtiplot\\3rdparty\\3rdparty\\libpng

Теперь нужно раскидать собранные ранее библиотеки по папкам в
C:\\build\\qtiplot\\3rdparty:
C:\\build\\muparser\\lib, C:\\build\\muparser\\include в папку
C:\\build\\qtiplot\\3rdparty\\muparser
C:\\build\\qwt-5.2\\lib C:\\build\\qwt-5.2\\src в папку
C:\\build\\qtiplot\\3rdparty\\qwt
gsl-1.8-lib.zip нужно распаковать в C:\\build\\qtiplot\\3rdparty\\gsl
C:\\build\\zlib-1.2.3\\libz.a в папку
C:\\build\\qtiplot\\3rdparty\\zlib

C:\\build\\boost\_1\_36\_0 нужно переименовать в
C:\\build\\qtiplot\\3rdparty\\boost\_1\_36\_0
C:\\build\\boost-build\\boost\\bin.v2\\libs\\date\_time\\build\\gcc-mingw-3.4.5\\release\\link-static\\threading-multi\\libboost\_date\_time-mgw34-mt-1\_36.lib
переименовать в
C:\\build\\qtiplot\\3rdparty\\boost\_1\_36\_0\\lib\\libboost\_date\_time-mgw34-mt.lib
C:\\build\\boost-build\\boost\\bin.v2\\libs\\thread\\build\\gcc-mingw-3.4.5\\release\\link-static\\threading-multi\\libboost\_thread-mgw34-mt-1\_36.lib
в
C:\\build\\qtiplot\\3rdparty\\boost\_1\_36\_0\\lib\\libboost\_thread-mgw34-mt.lib

Наконец, можно приступить к сборке.

    cd C:\build\qtiplot
    qmake qtiplot.pro && mingw32-make

Попытки скрипта сборки открыть python-скрипты в отсутствие python можно
игнорировать (нажатием на кнопочку cancel)

Полученный файл лежит в C:\\build\\qtiplot\\qtiplot\\qtiplot.exe
Замечания, исправления, предложения приветствуются.


text:
package jme3test.post;

import com.jme3.app.SimpleApplication;
import com.jme3.app.StatsView;
import com.jme3.font.BitmapText;
import com.jme3.light.DirectionalLight;
import com.jme3.material.Material;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Quaternion;
import com.jme3.math.Vector3f;
import com.jme3.post.FilterPostProcessor;
import com.jme3.post.filters.LightScatteringFilter;
import com.jme3.renderer.queue.RenderQueue.ShadowMode;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
import com.jme3.shadow.PssmShadowRenderer;
import com.jme3.util.SkyFactory;
import com.jme3.util.TangentBinormalGenerator;

public class TestLightScattering extends SimpleApplication {

    public static void main(String[] args) {
        TestLightScattering app = new TestLightScattering();

        app.start();
    }

   public void loadFPSText(){
        guiFont = assetManager.loadFont("Interface/Fonts/Default.fnt");
        fpsText = new BitmapText(guiFont, false);
        fpsText.setSize(guiFont.getCharSet().getRenderedSize());
        fpsText.setLocalTranslation(0, fpsText.getLineHeight(), 0);
        fpsText.setText("Frames per second");
        guiNode.attachChild(fpsText);
    }

    public void loadStatsView(){
        statsView = new StatsView("Statistics View", assetManager, renderer.getStatistics());
//         move it up so it appears above fps text
        statsView.setLocalTranslation(0, fpsText.getLineHeight(), 0);
        guiNode.attachChild(statsView);
    }

    @Override
    public void simpleInitApp() {
        // put the camera in a bad position
        cam.setLocation(new Vector3f(55.35316f, -0.27061665f, 27.092093f));
        cam.setRotation(new Quaternion(0.010414706f, 0.9874893f, 0.13880467f, -0.07409228f));
//        cam.setDirection(new Vector3f(0,-0.5f,1.0f));
//        cam.setLocation(new Vector3f(0, 300, -500));
        //cam.setFrustumFar(1000);
        flyCam.setMoveSpeed(10);
        Material mat = assetManager.loadMaterial("Textures/Terrain/Rocky/Rocky.j3m");
        Spatial scene = assetManager.loadModel("Models/Terrain/Terrain.mesh.xml");
        TangentBinormalGenerator.generate(((Geometry)((Node)scene).getChild(0)).getMesh());
        scene.setMaterial(mat);
        scene.setShadowMode(ShadowMode.CastAndReceive);
        scene.setLocalScale(400);
        scene.setLocalTranslation(0, -10, -120);

        rootNode.attachChild(scene);

        // load sky
        rootNode.attachChild(SkyFactory.createSky(assetManager, "Textures/Sky/Bright/FullskiesBlueClear03.dds", false));

        DirectionalLight sun = new DirectionalLight();
        Vector3f lightDir = new Vector3f(-0.12f, -0.3729129f, 0.74847335f);
        sun.setDirection(lightDir);
        sun.setColor(ColorRGBA.White.clone().multLocal(2));
        scene.addLight(sun);

        PssmShadowRenderer pssmRenderer = new PssmShadowRenderer(assetManager,1024,4);
        pssmRenderer.setDirection(lightDir);
        pssmRenderer.setShadowIntensity(0.55f);
     //   viewPort.addProcessor(pssmRenderer);

        FilterPostProcessor fpp = new FilterPostProcessor(assetManager);
//        SSAOFilter ssaoFilter= new SSAOFilter(viewPort, new SSAOConfig(0.36f,1.8f,0.84f,0.16f,false,true));
//        fpp.addFilter(ssaoFilter);

//           Material mat2 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
//        mat2.setTexture("ColorMap", assetManager.loadTexture("Interface/Logo/Monkey.jpg"));
//
//        Sphere lite=new Sphere(8, 8, 10.0f);
//        Geometry lightSphere=new Geometry("lightsphere", lite);
//        lightSphere.setMaterial(mat2);
        Vector3f lightPos = lightDir.multLocal(-3000);
//        lightSphere.setLocalTranslation(lightPos);
        // rootNode.attachChild(lightSphere);
        LightScatteringFilter filter = new LightScatteringFilter(lightPos);
        LightScatteringUI ui = new LightScatteringUI(inputManager, filter);
        fpp.addFilter(filter);
//fpp.setNumSamples(4);
        //fpp.addFilter(new RadialBlurFilter(0.3f,15.0f));
        //    SSAOUI ui=new SSAOUI(inputManager, ssaoFilter.getConfig());

        viewPort.addProcessor(fpp);
    }

    @Override
    public void simpleUpdate(float tpf) {
    }
}


text:
package eu.grmdev.wakshop.gui.controllers;

import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;

import eu.grmdev.wakshop.core.IWakshop;
import eu.grmdev.wakshop.core.Wakshop;
import eu.grmdev.wakshop.core.model.Workshop;
import eu.grmdev.wakshop.utils.Dialogs;
import eu.grmdev.wakshop.utils.Focusable;
import javafx.beans.Observable;
import javafx.beans.property.ReadOnlyObjectProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;

public class WorkshopCreateController extends BorderPane implements Focusable {
	@FXML
	private ChoiceBox<String> comboBox;
	@FXML
	private TextField tfSessionName, tfPort;
	@FXML
	private Button startBtn;
	private IWakshop wakshop;

	@Override
	public void initialize(URL location, ResourceBundle resources) {
		wakshop = Wakshop.getInstance();
		comboBox.setTooltip(new Tooltip("Select workshop to start"));
		comboBox.getSelectionModel().selectedItemProperty().addListener(e -> {
			comboBox_Selected(e);
		});
		tfSessionName.addEventHandler(KeyEvent.KEY_RELEASED, e -> {
			changeStartButtonState();
		});
		tfPort.addEventHandler(KeyEvent.KEY_RELEASED, e -> {
			changeStartButtonState();
		});
		tfPort.setText(wakshop.getConfigApi().getConfig().getDefaultPort() + "");
	}

	@Override
	public void onFocus(Object requestingObject) {
		List<String> workshops = wakshop.getWorkshopApi().getAllWorkshopsTitles();
		ObservableList<String> ws = FXCollections.observableArrayList(workshops);
		comboBox.setItems(ws);
	}

	private void comboBox_Selected(Observable e) {
		ReadOnlyObjectProperty<?> p = (ReadOnlyObjectProperty<?>) e;
		String v = (String) p.getValue();
		if (v != null && tfSessionName.getText().trim().length() == 0) {
			tfSessionName.setText(v);
		}
		System.out.println("Selected: " + v);
		changeStartButtonState();
	}

	private void changeStartButtonState() {
		try {
			String s = tfSessionName.getText();
			String p = tfPort.getText();
			boolean sessionCorrect = s != null && s.length() > 0;
			boolean portCorrect = p != null && p.length() > 0 && Integer.parseInt(p) > 0;
			boolean selectCorrect = comboBox.getSelectionModel().getSelectedIndex() >= 0;
			if (sessionCorrect && portCorrect && selectCorrect) {
				if (startBtn.isDisabled()) {
					startBtn.setDisable(false);
				}
			}
			else if (!startBtn.isDisabled()) {
				startBtn.setDisable(true);
			}
		}
		catch (NumberFormatException e) {
			if (!startBtn.isDisabled()) {
				startBtn.setDisable(true);
			}
		}
	}

	@FXML
	private synchronized void startButton_Click(ActionEvent e) {
		String item = comboBox.getSelectionModel().getSelectedItem();
		Workshop w = wakshop.getWorkshopApi().getWorkshop(item);
		System.out.println("Start Workshop");
		int port = Integer.parseInt(tfPort.getText());
		try {
			wakshop.startServer(port, w);
			System.out.println("After Connnection Establishment");
		}
		catch (Exception ex) {
			ex.printStackTrace();
			Dialogs.showExceptionDialog(ex, "Could not create server!");
		}
	}
}


text:
package org.jivesoftware.openfire.http;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.AsyncContext;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

public class SessionEventDispatcher
{
    private static final Logger Log = LoggerFactory.getLogger( SessionEventDispatcher.class );

    private static final Set<SessionListener> listeners = new CopyOnWriteArraySet<>();

    private SessionEventDispatcher()
    {
        // Not instantiable.
    }

    /**
     * Adds a {@link org.jivesoftware.openfire.http.SessionListener} to this session. The listener
     * will be notified of changes to the session.
     *
     * @param listener the listener which is being added to the session.
     */
    public static void addListener( SessionListener listener )
    {
        if ( listener == null )
        {
            throw new NullPointerException();
        }
        listeners.add( listener );
    }

    /**
     * Removes a {@link org.jivesoftware.openfire.http.SessionListener} from this session. The
     * listener will no longer be updated when an event occurs on the session.
     *
     * @param listener the session listener that is to be removed.
     */
    public static void removeListener( SessionListener listener )
    {
        listeners.remove( listener );
    }

    /**
     * Dispatches an event related to a particular BOSH session to all registered listeners.
     *
     * @param session The session that relates to the event (can be null when the event type is 'pre_session_created').
     * @param eventType The type of the event (cannot be null).
     * @param connection The connection where the event originated.
     * @param context The servlet context of the event
     */
    public static void dispatchEvent( HttpSession session, EventType eventType, HttpConnection connection, AsyncContext context )
    {
        for ( final SessionListener listener : listeners )
        {
            try
            {
                switch ( eventType )
                {
                    case connection_opened:
                        listener.connectionOpened( context, session, connection );
                        listener.connectionOpened( session, connection );
                        break;

                    case connection_closed:
                        listener.connectionClosed( context, session, connection );
                        listener.connectionClosed( session, connection );
                        break;

                    case pre_session_created:
                        listener.preSessionCreated( context );
                        break;

                    case post_session_created:
                        listener.postSessionCreated( context, session );
                        break;

                    case session_closed:
                        listener.sessionClosed( session );
                        break;

                    default:
                        throw new IllegalStateException( "An unexpected and unsupported event type was used: " + eventType );
                }
            }
            catch ( Exception e )
            {
                Log.warn( "An exception occurred while dispatching an event of type {}", eventType, e );
            }
        }
    }

    public enum EventType
    {
        connection_opened,
        connection_closed,
        pre_session_created,
        post_session_created,
        session_closed
    }
}


text:
<!DOCTYPE html>

	<title>Data Analysis</title>
	  <meta charset="utf-8">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

  <link rel="stylesheet" href="/resources/demos/style.css">

Data Analysis module

<form METHOD="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Username: <INPUT TYPE="text" NAME="username">

Subject: <INPUT TYPE="text" NAME="subword">

From: <input type="text" NAME="from_date" id="datepicker"> To: <input type="text" NAME="to_date" id="datepicker1">

	<?php echo $dateErr;?>

  	<input type="submit" NAME="select_w" value="Weekly">
  	<input type="submit" NAME="select_m" value="Monthly">
  	<input type="submit" NAME="select_y" value="Yearly">
</form>

<from>
</from>
<?php
include ("PHPconnectionDB.php");
	   //establish connection
$conn=connect();
createAdminView($conn);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
	if (!empty($_POST["from_date"]) and !empty($_POST["to_date"]) ) {
		$from_date=date("d-M-Y", strtotime($_POST["from_date"]));
		$to_date=date("d-M-Y", strtotime($_POST["to_date"]));
		if (strtotime($from_date)>strtotime($to_date)){
			$dateErr="From date must be less than To date reselect again!!!";
		}
	}elseif (!empty($_POST["from_date"]) and empty($_POST["to_date"]))  {
		$from_date=date("d-M-Y", strtotime($_POST["from_date"]));
		$to_date="";
	}elseif (empty($_POST["from_date"]) and !empty($_POST["to_date"])) {
		$from_date="";
		$to_date=date("d-M-Y", strtotime($_POST["to_date"]));
	}else{
		$from_date="";
		$to_date="";
	}
	if ("select_w")

}
function createAdminView($conn){
$sql="CREATE VIEW ADMIN_VIEW (OWNER_NAME,SUBJECTS,TIMING) AS
	SELECT(OWNER_NAME,SUBJECTS,TIMING)
	FROM IMAGES
	ORDER BY TIMING";
	$a = oci_parse($conn, $sql);
	$res=oci_execute($a);
	$r = oci_commit($conn);
}

?>


text:
package org.apache.calcite.interpreter;

/**
 * Relational expression that can be executed using an interpreter.
 */
public interface Node extends AutoCloseable {
  void run() throws InterruptedException;

  @Override default void close() {
  }
}


text:
![Imgur](https://i.imgur.com/DaEnlIF.jpg)

> San Francisco, CA
> Pacific Time
> Mac OSX

## Profile
> Computer Science Master's Student at University of San Francisco
> Photography/Art Lover (when I have time!)

## Skills
* Java
* HTML
* CSS
* JavaScript
* SQL
* Shell Scripting

## Contact
> [email](mailto:azywong@gmail.com)
> [linkedin](https://www.linkedin.com/in/allisonzywong/)


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

namespace JQDotNet.Elements
{
    internal class JFilter
    {
        public enum FilterTypes
        {
            GreaterThan,
            GreaterThanOrEqual,
            Equal,
            LessThan,
            LessThanOrEqual
        };
        public object Value { get; set; }
        public FilterTypes FilterType { get; set; }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: ant
 * Date: 25.04.2017
 * Time: 13:15
 */

namespace Kaula\TelegramBundle\Telegram\Event;

use RuntimeException;
use unreal4u\TelegramAPI\Telegram\Types\Document;
use unreal4u\TelegramAPI\Telegram\Types\Update;

class DocumentReceivedEvent extends AbstractMessageEvent
{
  const NAME = 'telegram.document.received';

  /**
   * DocumentReceivedEvent constructor.
   *
   * @param Update $update
   */
  public function __construct(Update $update)
  {
    if (is_null($update->message)) {
      throw new RuntimeException(
        'Message can\'t be null for the DocumentReceivedEvent.'
      );
    }
    if (empty($update->message->document)) {
      throw new RuntimeException(
        'Document of the Message can\'t be empty for the DocumentReceivedEvent.'
      );
    }

    $this->setMessage($update->message)
      ->setUpdate($update);
  }

  /**
   * Message is a general file, information about the file
   *
   * @return Document
   */
  public function getDocument(): Document
  {
    return $this->getMessage()->document;
  }

  /**
   * Optional. Caption for the document, photo or video, 0-200 characters
   *
   * @return string
   */
  public function getCaption()
  {
    return $this->getMessage()->caption;
  }

}


text:
from tralics_driver import driver
import tralics_driver
from lxml import etree
import os

'''
This is an example as how you might use the tralics driver.

It retrieves all the images with class="math" in a tree of HTML files and
passes the alt text(presumed to be LaTeX math strings) to the driver.

It creates a new HTML file in the current directory that contains a table
showing the LaTeX math snippet and the resulting MathML in each HTML source
file encountered.

Things to override:
ROOT: path to parent of html directories

functions:
    main
        change the method of locating the source HTML files  to suit your own situation.
        (I have the configuration set and record errors in a MongoDB database).
        Invoke the driver with your own options.

    get_documents
        return a list of directories containing HTML files for processing

    forget_errors
        erase errors encounter in previous run

    record_errors
        record errors encountered in this run
'''

ROOT = '/path/to/html/parent'
MATHJAX = "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=MML_HTMLorMML"

def get_documents():
    pass

def forget_errors(name):
    pass

def record_errors(error_list):
    pass

def get_mathstring(path):
    files = sorted([x for x in os.listdir(path) if x.endswith('.htm')])
    parser = etree.HTMLParser()
    for fname in files:
        tree = etree.parse(os.path.join(path, fname), parser=parser)
        for image in tree.xpath('//img[@class="math"]'):
            mtext = image.get('alt')
            yield (fname, mtext)

def write_html(title, math):
    page = etree.Element('html')
    doc = etree.ElementTree(page)
    head = etree.SubElement(page, 'head')
    mcss = etree.SubElement(head, 'script', type='text/x-mathjax-config')
    mcss.text = 'MathJax.Hub.Config({displayAlign: "left", displayIndent: "2em"});'
    etree.SubElement(head, 'script', src=MATHJAX, type='text/javascript')
    css = etree.SubElement(head, 'style', type='text/css')
    css.text = '''
        table {width:100%; border: 1px solid navy;font-family: sans-serif;}
        .filename {background-color: #d5e4bc; font-family: sans-serif;}
        .latex {background-color: #c1dcb7; font-family: serif;}
        .mathml {background-color: #bad6c8;}
      '''
    body = etree.SubElement(page, 'body')
    table = etree.SubElement(body, 'table')
    fcol = etree.SubElement(table, 'colgroup', attrib={'class':'filename'})
    etree.SubElement(fcol, 'col')
    lcol = etree.SubElement(table, 'colgroup', attrib={'class':'latex'})
    etree.SubElement(lcol, 'col')
    mcol = etree.SubElement(table, 'colgroup', attrib={'class':'mathml'})
    etree.SubElement(mcol, 'col')

    thead = etree.SubElement(table, 'thead')
    thead_row = etree.SubElement(thead, 'tr')
    for heading in ['Filename', 'LaTeX', 'MathML']:
        h = etree.SubElement(thead_row, 'th')
        h.text = heading
    tbody = etree.SubElement(table, 'tbody')
    lastname = ''
    for fname, mathstring, elemstring in math:
        try:
            elem = etree.fromstring(elemstring)
        except (etree.XMLSyntaxError, ValueError) as e:
            elem = etree.fromstring(tralics_driver.bad_elem.substitute(
                                    {'error_text': str(e),
                                     'expr': tralics_driver.escape(mathstring),
                                     'return_code': 6}))

        tr = etree.SubElement(tbody, 'tr')
        td1 = etree.SubElement(tr, 'td')
        td2 = etree.SubElement(tr, 'td')
        td3 = etree.SubElement(tr, 'td')
        if fname != lastname:
            td1.text = fname

        td2.text = mathstring
        if elem is not None:
            td3.append(elem)

        lastname = fname

    with open('%s_mathml.html' % title, 'wb') as f:
        doc.write(f, pretty_print=True, method='html')

def main():
    doc_dirs = get_documents()
    for doc_dir in doc_dirs:
        forget_errors(doc_dir)
        t = driver.TralicsDriver('/path/to/tralics')
        math = list()

        path = os.path.join(ROOT, doc_dir)
        for fname, mathstring in get_mathstring(path):
            elemstring = t.convert(fname, mathstring)
            math.append((fname, mathstring, elemstring))
        record_errors(t.errors)
        t.stop()
        write_html(doc_dir, math)

if __name__ == '__main__':
    main()
    print

'''
To replace the image elements with the mathml element:
try:
    math_elem = etree.fromstring(elemstring)
except etree.XMLSyntaxError as e:
    print e
else:
    image.getparent().replace(image, math_elem)
'''


text:
"""Command Line Interface
=========================
"""
from classproperty import classproperty
from sys import argv

def doc(obj):
    return obj.__doc__

def autodoc(obj):
    return obj.__autodoc__

def lines(*args):
    return "\n".join(args)

class CLI(object):
    """Helper class to implement a Command Line Interface."""
    _cmds = {}

    def __init__(self, cmds=None):
        self.add(cmds or {})

    @classproperty
    @classmethod
    def commands(cls):
        return cls._cmds.items()

    def __str__(self):
        """Return help / usage message."""
        return lines(
            self.desc,
            ''
            'Usage: run <command> [options]',
            '',
            'Commands:',
            '',
            autodoc(self),
            ''
            )

    @classproperty
    @classmethod
    def desc(cls):
        return doc(cls).split('\n')[0]

    @classproperty
    @classmethod
    def options(self):
        return ["{}\t{}".format(" ".join(i for i in c), doc(func))
            for c, func in sorted(self.commands)]

    def execute(self, app, cmd, arg):
        """Call `cmd` passing `arg`."""
        for c, func in self.commands:
            if cmd in c:
                return func(app or self, arg) or ''
        return self.unknown_option(cmd)

    def unknown_option(self, cmd):
        return lines(
            'Unknown option: %s' % cmd,
            'Try --help for more information.',
            )

    @classproperty
    @classmethod
    def __autodoc__(cls):
        """Return additional documentation to insert into Sphinx autodoc."""
        return "\n".join(cls.options)

    @classproperty
    @classmethod
    def cmd(cls):
        """Return the command (the first argument)."""
        return argv[1] if len(argv) > 1 else None

    @classproperty
    @classmethod
    def arg(cls):
        """Return the argument (that follows the cmd)."""
        return argv[2] if len(argv) > 2 else None

    @classmethod
    def add(cls, cmds):
        """Add to the list of commands."""
        cls._cmds.update(cmds)

    def __call__(self, app=None, default="--help"):
        """Run the application using the args passed from the command line.
        This is the main entry point to the application."""
        return self.execute(app, self.cmd or default, self.arg)


text:
@interface GTMCarbonEventTest : GTMTestCase {
 @private
  GTMCarbonEvent *event_;
}
@end

@interface GTMCarbonEventHandlerTest : GTMTestCase {
 @private
  GTMCarbonEventHandler *handler_;
}
@end

@interface GTMCarbonEventMonitorHandlerTest : GTMTestCase
@end

@interface GTMCarbonEventApplicationEventHandlerTest : GTMTestCase
@end

@interface GTMCarbonEventDispatcherHandlerTest : GTMTestCase {
 @private
  GTMUnitTestingBooleanRunLoopContext *hotKeyHit_;
}
@end

static const UInt32 kTestClass = 'foo ';
static const UInt32 kTestKind = 'bar ';
static const UInt32 kTestParameterName = 'baz ';
static const UInt32 kTestBadParameterName = 'bom ';
static const UInt32 kTestParameterValue = 'bam ';

@implementation GTMCarbonEventTest
- (void)setUp {
  event_ = [[GTMCarbonEvent eventWithClass:kTestClass kind:kTestKind] retain];
}

- (void)tearDown {
  [event_ release];
}

- (void)testCopy {
  GTMCarbonEvent *event2 = [[event_ copy] autorelease];
  STAssertNotNil(event2, nil);
}

- (void)testEventWithClassAndKind {
  STAssertEquals([event_ eventClass], kTestClass, nil);
  STAssertEquals([event_ eventKind], kTestKind, nil);
}

- (void)testEventWithEvent {
  GTMCarbonEvent *event2 = [GTMCarbonEvent eventWithEvent:[event_ event]];
  STAssertEquals([event2 event], [event_ event], nil);
}

- (void)testCurrentEvent {
  EventRef eventRef = GetCurrentEvent();
  GTMCarbonEvent *event = [GTMCarbonEvent currentEvent];
  STAssertEquals([event event], eventRef, nil);
}

- (void)testEventClass {
  [self testEventWithClassAndKind];
}

- (void)testEventKind {
  [self testEventWithClassAndKind];
}

- (void)testSetTime {
  EventTime eventTime = [event_ time];
  STAssertNotEquals(eventTime, kEventDurationNoWait, nil);
  STAssertNotEquals(eventTime, kEventDurationForever, nil);
  [event_ setTime:kEventDurationForever];
  EventTime testTime = [event_ time];
  STAssertEquals(testTime, kEventDurationForever, nil);
  [event_ setTime:eventTime];
  STAssertEquals([event_ time], eventTime, nil);
}

- (void)testTime {
  [self testSetTime];
}

- (void)testEvent {
  [self testEventWithEvent];
}

- (void)testSetParameterNamed {
  UInt32 theData = kTestParameterValue;
  [event_ setUInt32ParameterNamed:kTestParameterName data:&theData];
  theData = 0;
  STAssertEquals([event_ sizeOfParameterNamed:kTestParameterName
                                         type:typeUInt32],
                 sizeof(UInt32), nil);
  STAssertTrue([event_ getUInt32ParameterNamed:kTestParameterName
                                          data:&theData], nil);
  STAssertEquals(theData, kTestParameterValue, nil);
}

- (void)testGetParameterNamed {
  [self testSetParameterNamed];
  UInt32 theData = kTestParameterValue;
  STAssertFalse([event_ getUInt32ParameterNamed:kTestBadParameterName
                                           data:&theData], nil);
  STAssertFalse([event_ getUInt32ParameterNamed:kTestBadParameterName
                                           data:NULL], nil);

}

- (void)testSizeOfParameterNamed {
  [self testSetParameterNamed];
}

- (void)testHasParameterNamed {
  [self testSetParameterNamed];
}

- (OSStatus)gtm_eventHandler:(GTMCarbonEventHandler *)sender
               receivedEvent:(GTMCarbonEvent *)event
                     handler:(EventHandlerCallRef)handler {
  OSStatus status = eventNotHandledErr;
  if ([event eventClass] == kTestClass && [event eventKind] == kTestKind) {
    status = noErr;
  }
  return status;
}

- (void)testSendToTarget {
  EventTypeSpec types = { kTestClass, kTestKind };
  GTMCarbonEventDispatcherHandler *handler
    = [[GTMCarbonEventDispatcherHandler sharedEventDispatcherHandler]
       autorelease];
  [handler registerForEvents:&types count:1];
  OSStatus status = [event_ sendToTarget:handler options:0];
  STAssertErr(status, eventNotHandledErr, @"status: %ld", status);
  [handler setDelegate:self];
  status = [event_ sendToTarget:handler options:0];
  STAssertNoErr(status, @"status: %ld", status);
  [handler unregisterForEvents:&types count:1];
}

- (void)testPostToQueue {
  EventQueueRef eventQueue = GetMainEventQueue();
  [event_ postToMainQueue];
  OSStatus status = [event_ postToQueue:eventQueue
                               priority:kEventPriorityStandard];
  STAssertErr(status, eventAlreadyPostedErr, @"status: %ld", status);
  EventTypeSpec types = { kTestClass, kTestKind };
  status = FlushEventsMatchingListFromQueue(eventQueue, 1, &types);
  STAssertNoErr(status, @"status: %ld", status);

  eventQueue = GetCurrentEventQueue();
  [event_ postToCurrentQueue];
  status = [event_ postToQueue:eventQueue priority:kEventPriorityStandard];
  STAssertErr(status, eventAlreadyPostedErr, @"status: %ld", status);
  status = FlushEventsMatchingListFromQueue(eventQueue, 1, &types);
  STAssertNoErr(status, @"status: %ld", status);
}

- (void)testPostToMainQueue {
  [self testPostToQueue];
}

- (void)testPostToCurrentQueue {
  STAssertEquals(GetCurrentEventQueue(), GetMainEventQueue(), nil);
  [self testPostToMainQueue];
}

- (void)testDescription {
  NSString *descString
    = [NSString stringWithFormat:@"GTMCarbonEvent 'foo ' %d", kTestKind];
  STAssertEqualObjects([event_ description], descString, nil);
}
@end

@implementation GTMCarbonEventHandlerTest

- (void)setUp {
  handler_ = [[GTMCarbonEventHandler alloc] init];
}

- (void)tearDown {
  [handler_ release];
}

- (void)testEventTarget {
  STAssertNULL([handler_ eventTarget], nil);
}

- (void)testEventHandler {
  [GTMUnitTestDevLogDebug expectPattern:
   @"DebugAssert: GoogleToolboxForMac: event CantUseParams .*"];
  STAssertErr([handler_ handleEvent:nil handler:nil], eventNotHandledErr, nil);
}

- (void)testDelegate {
  [handler_ setDelegate:self];
  STAssertEqualObjects([handler_ delegate], self, nil);
  [handler_ setDelegate:nil];
  STAssertNil([handler_ delegate], nil);
}

- (void)testSetDelegate {
  [self testDelegate];
}

@end

@implementation GTMCarbonEventMonitorHandlerTest

- (void)testEventHandler {
  GTMCarbonEventMonitorHandler *monitor
    = [GTMCarbonEventMonitorHandler sharedEventMonitorHandler];
  STAssertEquals([monitor eventTarget], GetEventMonitorTarget(), nil);
}

@end

#if (MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5)
// Accidentally marked as !LP64 in the 10.5sdk, it's back in the 10.6 sdk.
// If you remove this decl, please remove it from GTMCarbonEvent.m as well.
extern EventTargetRef GetApplicationEventTarget(void);
#endif  // (MAC_OS_X_VERSION_MAX_ALLOWED == MAC_OS_X_VERSION_10_5)

@implementation GTMCarbonEventApplicationEventHandlerTest

- (void)testEventHandler {
  GTMCarbonEventApplicationEventHandler *handler
    = [GTMCarbonEventApplicationEventHandler sharedApplicationEventHandler];
  STAssertEquals([handler eventTarget], GetApplicationEventTarget(), nil);
}

@end

@implementation GTMCarbonEventDispatcherHandlerTest

- (void)setUp {
  hotKeyHit_ = [[GTMUnitTestingBooleanRunLoopContext alloc] init];
}

- (void)tearDown {
  [hotKeyHit_ release];
  hotKeyHit_ = nil;
}

- (void)testEventHandler {
  GTMCarbonEventDispatcherHandler *dispatcher
    = [GTMCarbonEventDispatcherHandler sharedEventDispatcherHandler];
  STAssertEquals([dispatcher eventTarget], GetEventDispatcherTarget(), nil);
}

- (void)hitHotKey:(GTMCarbonHotKey *)key {
  STAssertEqualObjects([key userInfo], self, nil);
  [hotKeyHit_ setShouldStop:YES];
}

- (void)hitExceptionalHotKey:(GTMCarbonHotKey *)key {
  STAssertEqualObjects([key userInfo], self, nil);
  [hotKeyHit_ setShouldStop:YES];
  [NSException raise:@"foo" format:@"bar"];
}

- (void)testRegisterHotKeyModifiersTargetActionWhenPressed {

  // This test can't be run if the screen saver is active because the security
  // agent blocks us from sending events via remote operations
  if (![GTMAppKitUnitTestingUtilities isScreenSaverActive]) {
    GTMCarbonEventDispatcherHandler *dispatcher
      = [GTMCarbonEventDispatcherHandler sharedEventDispatcherHandler];
    STAssertNotNil(dispatcher, @"Unable to acquire singleton");
    UInt32 keyMods = (NSShiftKeyMask | NSControlKeyMask
                      | NSAlternateKeyMask | NSCommandKeyMask);
    [GTMUnitTestDevLogDebug expectPattern:@"DebugAssert: GoogleToolboxForMac: "
     @"newKey CantCreateKey .*"];
    STAssertNil([dispatcher registerHotKey:0x5
                                 modifiers:keyMods
                                    target:nil
                                    action:nil
                                  userInfo:nil
                               whenPressed:YES],
                 @"Shouldn't have created hotkey");
    GTMCarbonHotKey *hotKey = [dispatcher registerHotKey:0x5
                                               modifiers:keyMods
                                                  target:self
                                                  action:@selector(hitHotKey:)
                                                userInfo:self
                                             whenPressed:YES];
    STAssertNotNil(hotKey, @"Unable to create hotkey");

    // Post the hotkey combo to the event queue. If everything is working
    // correctly hitHotKey: should get called, and hotKeyHit_ will be set for
    // us.  We run the event loop for a set amount of time waiting for this to
    // happen.
    [GTMAppKitUnitTestingUtilities postTypeCharacterEvent:'g' modifiers:keyMods];
    STAssertTrue([NSApp gtm_runUpToSixtySecondsWithContext:hotKeyHit_], nil);
    [dispatcher unregisterHotKey:hotKey];
  }
}

- (void)testRegisterHotKeyModifiersTargetActionWhenPressedException {

  // This test can't be run if the screen saver is active because the security
  // agent blocks us from sending events via remote operations
  if (![GTMAppKitUnitTestingUtilities isScreenSaverActive]) {
    GTMCarbonEventDispatcherHandler *dispatcher
      = [GTMCarbonEventDispatcherHandler sharedEventDispatcherHandler];
    STAssertNotNil(dispatcher, @"Unable to acquire singleton");
    UInt32 keyMods = (NSShiftKeyMask | NSControlKeyMask
                      | NSAlternateKeyMask | NSCommandKeyMask);
    GTMCarbonHotKey *hotKey
      = [dispatcher registerHotKey:0x5
                         modifiers:keyMods
                            target:self
                            action:@selector(hitExceptionalHotKey:)
                          userInfo:self
                       whenPressed:YES];
    STAssertNotNil(hotKey, @"Unable to create hotkey");

    // Post the hotkey combo to the event queue. If everything is working
    // correctly hitHotKey: should get called, and hotKeyHit_ will be set for
    // us.  We run the event loop for a set amount of time waiting for this to
    // happen.
    [GTMAppKitUnitTestingUtilities postTypeCharacterEvent:'g' modifiers:keyMods];
    [GTMUnitTestDevLog expectString:@"Exception fired in hotkey: foo (bar)"];
    STAssertTrue([NSApp gtm_runUpToSixtySecondsWithContext:hotKeyHit_], nil);
    [dispatcher unregisterHotKey:hotKey];
  }
}

- (void)testKeyModifiers {
  struct {
    NSUInteger cocoaKey_;
    UInt32 carbonKey_;
  } keyMap[] = {
    { NSAlphaShiftKeyMask, alphaLock},
    { NSShiftKeyMask, shiftKey},
    { NSControlKeyMask, controlKey},
    { NSAlternateKeyMask, optionKey},
    { NSCommandKeyMask, cmdKey},
  };
  size_t combos = pow(2, sizeof(keyMap) / sizeof(keyMap[0]));
  for (size_t i = 0; i < combos; i++) {
    NSUInteger cocoaMods = 0;
    UInt32 carbonMods = 0;
    for (size_t j = 0; j < 32 && j < sizeof(keyMap) / sizeof(keyMap[0]); j++) {
      if (i & 1 << j) {
        cocoaMods |= keyMap[j].cocoaKey_;
        carbonMods |= keyMap[j].carbonKey_;
      }
    }
    STAssertEquals(GTMCocoaToCarbonKeyModifiers(cocoaMods), carbonMods, nil);
    STAssertEquals(GTMCarbonToCocoaKeyModifiers(carbonMods), cocoaMods, nil);
  }
}

@end


text:
require("svm.jl")
require("adult.jl")


text:
--TEST--
Test ctype_print() function : usage variations - octal and hexadecimal values
--SKIPIF--
<?php require_once('skipif.inc'); ?>
--FILE--
<?php
/* Prototype  : bool ctype_print(mixed $c)
 * Description: Checks for printable character(s)
 * Source code: ext/ctype/ctype.c
 */

/*
 * Pass octal and hexadecimal values to ctype_print() to test behaviour
 */

echo "*** Testing ctype_print() : usage variations ***\n";

$orig = setlocale(LC_CTYPE, "C");

$octal_values = array(040, 041, 042, 043);
$hex_values = array (0x20, 0x21, 0x23, 0x24);

echo "\n-- Octal Values --\n";
$iterator = 1;
foreach($octal_values as $c) {
	echo "-- Iteration $iterator --\n";
	var_dump(ctype_print($c));
	$iterator++;
}

echo "\n-- Hexadecimal Values --\n";
$iterator = 1;
foreach($hex_values as $c) {
	echo "-- Iteration $iterator --\n";
	var_dump(ctype_print($c));
	$iterator++;
}
setlocale(LC_CTYPE, $orig);
?>
===DONE===
--EXPECTF--
*** Testing ctype_print() : usage variations ***

-- Octal Values --
-- Iteration 1 --
bool(true)
-- Iteration 2 --
bool(true)
-- Iteration 3 --
bool(true)
-- Iteration 4 --
bool(true)

-- Hexadecimal Values --
-- Iteration 1 --
bool(true)
-- Iteration 2 --
bool(true)
-- Iteration 3 --
bool(true)
-- Iteration 4 --
bool(true)
===DONE===


text:
/* */
"format cjs";
(function (factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery', 'sammy'], factory);
  } else {
    (window.Sammy = window.Sammy || {}).Exceptional = factory(window.jQuery, window.Sammy);
  }
}(function ($, Sammy) {

  // A plugin that posts errors to Exceptional.
  //
  // ### Arguments
  //
  // Sammy.Exceptional accepts an optional argument that is the Exceptional
  // implementation. It will default to the global `Exceptional` object.
  //
  // ### Requirements
  //
  // The sole requirement is a global Exceptional object with a handle
  // function. Contrast have published an implementation (see below).
  //
  // ### See Also
  //  * http://www.getexceptional.com/
  //  * https://github.com/contrast/exceptional-js
  Sammy.Exceptional = function(app, errorReporter) {
    errorReporter = errorReporter || window.Exceptional;
    app.bind('error', function(e, data) {
      if (data && data.error) {
        errorReporter.handle(data.error.message, window.location.href, '0');
      }
    });
  };

  return Sammy.Exceptional;

}));


text:
import React, { Component, PropTypes } from 'react';

import './SearchBox.css';

class SearchBox extends Component {
  static propTypes = {
    onChangeSearchText: PropTypes.func.isRequired
  }

  onChangeSearchText(e) {
    this.props.onChangeSearchText(e.target.value);
  }

  onFocusSearchText(e) {
    const input = e.target;
    input.select();
    input.selectionStart = 0;
    input.selectionEnd = input.value.length;
  }

  render() {
    return (
      <form className="searchbox">
        <label className="hidden" htmlFor="search">Search for emojis</label>
        <input
          className="searchbox-input"
          id="search"
          type="search"
          ref="search"
          autoFocus
          autoCapitalize="off"
          autoComplete="off"
          autoCorrect="off"
          value={this.props.searchText}
          onChange={this.onChangeSearchText.bind(this)}
          onFocus={this.onFocusSearchText.bind(this)}
          placeholder="Search for emojis"
        />
      </form>
    );
  }
}

export default SearchBox;


text:
<?php

namespace DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRResource;

use DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRResource;
use DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRSupply\FHIRSupplyDispense;
use DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRCodeableConcept;
use DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRIdentifier;
use DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRResourceReference;
use DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRSupplyStatus;
use DCarbone\PHPFHIRGenerated\DSTU1\PHPFHIRConstants;
use DCarbone\PHPFHIRGenerated\DSTU1\PHPFHIRContainedTypeInterface;
use DCarbone\PHPFHIRGenerated\DSTU1\PHPFHIRTypeInterface;

/**
 * A supply - a request for something, and provision of what is supplied.
 * If the element is present, it must have either a \@value, an \@id, or extensions
 *
 * Class FHIRSupply
 * @package \DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRResource
 */
class FHIRSupply extends FHIRResource implements PHPFHIRContainedTypeInterface
{
    // name of FHIR type this class describes
    const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_SUPPLY;
    const FIELD_DISPENSE = 'dispense';
    const FIELD_IDENTIFIER = 'identifier';
    const FIELD_KIND = 'kind';
    const FIELD_ORDERED_ITEM = 'orderedItem';
    const FIELD_PATIENT = 'patient';
    const FIELD_STATUS = 'status';
    const FIELD_STATUS_EXT = '_status';

    /** @var string */
    private $_xmlns = 'http://hl7.org/fhir';

    /**
     * A supply - a request for something, and provision of what is supplied.
     *
     * Indicates the details of the dispense event such as the days supply and quantity
     * of a supply dispensed.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRSupply\FHIRSupplyDispense[]
     */
    protected $dispense = [];

    /**
     * A technical identifier - identifies some entity uniquely and unambiguously.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Unique identifier for this supply request.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRIdentifier
     */
    protected $identifier = null;

    /**
     * A concept that may be defined by a formal reference to a terminology or ontology
     * or may be provided by text.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Category of supply, e.g. central, non-stock, etc. This is used to support work
     * flows associated with the supply process.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRCodeableConcept
     */
    protected $kind = null;

    /**
     * A reference from one resource to another.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * The item that is requested to be supplied.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRResourceReference
     */
    protected $orderedItem = null;

    /**
     * A reference from one resource to another.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A link to a resource representing the person whom the ordered item is for.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRResourceReference
     */
    protected $patient = null;

    /**
     * Status of the supply
     * If the element is present, it must have either a \@value, an \@id, or extensions
     *
     * Status of the supply request.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRSupplyStatus
     */
    protected $status = null;

    /**
     * Validation map for fields in type Supply
     * @var array
     */
    private static $_validationRules = [    ];

    /**
     * FHIRSupply Constructor
     * @param null|array $data
     */
    public function __construct($data = null)
    {
        if (null === $data || [] === $data) {
            return;
        }
        if (!is_array($data)) {
            throw new \InvalidArgumentException(sprintf(
                'FHIRSupply::_construct - $data expected to be null or array, %s seen',
                gettype($data)
            ));
        }
        parent::__construct($data);
        if (isset($data[self::FIELD_DISPENSE])) {
            if (is_array($data[self::FIELD_DISPENSE])) {
                foreach($data[self::FIELD_DISPENSE] as $v) {
                    if (null === $v) {
                        continue;
                    }
                    if ($v instanceof FHIRSupplyDispense) {
                        $this->addDispense($v);
                    } else {
                        $this->addDispense(new FHIRSupplyDispense($v));
                    }
                }
            } else if ($data[self::FIELD_DISPENSE] instanceof FHIRSupplyDispense) {
                $this->addDispense($data[self::FIELD_DISPENSE]);
            } else {
                $this->addDispense(new FHIRSupplyDispense($data[self::FIELD_DISPENSE]));
            }
        }
        if (isset($data[self::FIELD_IDENTIFIER])) {
            if ($data[self::FIELD_IDENTIFIER] instanceof FHIRIdentifier) {
                $this->setIdentifier($data[self::FIELD_IDENTIFIER]);
            } else {
                $this->setIdentifier(new FHIRIdentifier($data[self::FIELD_IDENTIFIER]));
            }
        }
        if (isset($data[self::FIELD_KIND])) {
            if ($data[self::FIELD_KIND] instanceof FHIRCodeableConcept) {
                $this->setKind($data[self::FIELD_KIND]);
            } else {
                $this->setKind(new FHIRCodeableConcept($data[self::FIELD_KIND]));
            }
        }
        if (isset($data[self::FIELD_ORDERED_ITEM])) {
            if ($data[self::FIELD_ORDERED_ITEM] instanceof FHIRResourceReference) {
                $this->setOrderedItem($data[self::FIELD_ORDERED_ITEM]);
            } else {
                $this->setOrderedItem(new FHIRResourceReference($data[self::FIELD_ORDERED_ITEM]));
            }
        }
        if (isset($data[self::FIELD_PATIENT])) {
            if ($data[self::FIELD_PATIENT] instanceof FHIRResourceReference) {
                $this->setPatient($data[self::FIELD_PATIENT]);
            } else {
                $this->setPatient(new FHIRResourceReference($data[self::FIELD_PATIENT]));
            }
        }
        if (isset($data[self::FIELD_STATUS]) || isset($data[self::FIELD_STATUS_EXT])) {
            if (isset($data[self::FIELD_STATUS])) {
                $value = $data[self::FIELD_STATUS];
            } else {
                $value = null;
            }
            if (isset($data[self::FIELD_STATUS_EXT]) && is_array($data[self::FIELD_STATUS_EXT])) {
                $ext = $data[self::FIELD_STATUS_EXT];
            } else {
                $ext = [];
            }
            if (null !== $value) {
                if ($value instanceof FHIRSupplyStatus) {
                    $this->setStatus($value);
                } else if (is_array($value)) {
                    $this->setStatus(new FHIRSupplyStatus(array_merge($ext, $value)));
                } else {
                    $this->setStatus(new FHIRSupplyStatus([FHIRSupplyStatus::FIELD_VALUE => $value] + $ext));
                }
            } else if ([] !== $ext) {
                $this->setStatus(new FHIRSupplyStatus($ext));
            }
        }
    }

    /**
     * @return string
     */
    public function _getFHIRTypeName()
    {
        return self::FHIR_TYPE_NAME;
    }

    /**
     * @return string
     */
    public function _getFHIRXMLElementDefinition()
    {
        $xmlns = $this->_getFHIRXMLNamespace();
        if (null !== $xmlns) {
            $xmlns = " xmlns=\"{$xmlns}\"";
        }
        return "<Supply{$xmlns}></Supply>";
    }
    /**
     * @return string
     */
    public function _getResourceType()
    {
        return static::FHIR_TYPE_NAME;
    }

    /**
     * A supply - a request for something, and provision of what is supplied.
     *
     * Indicates the details of the dispense event such as the days supply and quantity
     * of a supply dispensed.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRSupply\FHIRSupplyDispense[]
     */
    public function getDispense()
    {
        return $this->dispense;
    }

    /**
     * A supply - a request for something, and provision of what is supplied.
     *
     * Indicates the details of the dispense event such as the days supply and quantity
     * of a supply dispensed.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRSupply\FHIRSupplyDispense $dispense
     * @return static
     */
    public function addDispense(FHIRSupplyDispense $dispense = null)
    {
        $this->dispense[] = $dispense;
        return $this;
    }

    /**
     * A supply - a request for something, and provision of what is supplied.
     *
     * Indicates the details of the dispense event such as the days supply and quantity
     * of a supply dispensed.
     *
     * @param \DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRSupply\FHIRSupplyDispense[] $dispense
     * @return static
     */
    public function setDispense(array $dispense = [])
    {
        $this->dispense = [];
        if ([] === $dispense) {
            return $this;
        }
        foreach($dispense as $v) {
            if ($v instanceof FHIRSupplyDispense) {
                $this->addDispense($v);
            } else {
                $this->addDispense(new FHIRSupplyDispense($v));
            }
        }
        return $this;
    }

    /**
     * A technical identifier - identifies some entity uniquely and unambiguously.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Unique identifier for this supply request.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRIdentifier
     */
    public function getIdentifier()
    {
        return $this->identifier;
    }

    /**
     * A technical identifier - identifies some entity uniquely and unambiguously.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Unique identifier for this supply request.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRIdentifier $identifier
     * @return static
     */
    public function setIdentifier(FHIRIdentifier $identifier = null)
    {
        $this->identifier = $identifier;
        return $this;
    }

    /**
     * A concept that may be defined by a formal reference to a terminology or ontology
     * or may be provided by text.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Category of supply, e.g. central, non-stock, etc. This is used to support work
     * flows associated with the supply process.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRCodeableConcept
     */
    public function getKind()
    {
        return $this->kind;
    }

    /**
     * A concept that may be defined by a formal reference to a terminology or ontology
     * or may be provided by text.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Category of supply, e.g. central, non-stock, etc. This is used to support work
     * flows associated with the supply process.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRCodeableConcept $kind
     * @return static
     */
    public function setKind(FHIRCodeableConcept $kind = null)
    {
        $this->kind = $kind;
        return $this;
    }

    /**
     * A reference from one resource to another.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * The item that is requested to be supplied.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRResourceReference
     */
    public function getOrderedItem()
    {
        return $this->orderedItem;
    }

    /**
     * A reference from one resource to another.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * The item that is requested to be supplied.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRResourceReference $orderedItem
     * @return static
     */
    public function setOrderedItem(FHIRResourceReference $orderedItem = null)
    {
        $this->orderedItem = $orderedItem;
        return $this;
    }

    /**
     * A reference from one resource to another.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A link to a resource representing the person whom the ordered item is for.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRResourceReference
     */
    public function getPatient()
    {
        return $this->patient;
    }

    /**
     * A reference from one resource to another.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A link to a resource representing the person whom the ordered item is for.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRResourceReference $patient
     * @return static
     */
    public function setPatient(FHIRResourceReference $patient = null)
    {
        $this->patient = $patient;
        return $this;
    }

    /**
     * Status of the supply
     * If the element is present, it must have either a \@value, an \@id, or extensions
     *
     * Status of the supply request.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRSupplyStatus
     */
    public function getStatus()
    {
        return $this->status;
    }

    /**
     * Status of the supply
     * If the element is present, it must have either a \@value, an \@id, or extensions
     *
     * Status of the supply request.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRSupplyStatus $status
     * @return static
     */
    public function setStatus(FHIRSupplyStatus $status = null)
    {
        $this->status = $status;
        return $this;
    }

    /**
     * Returns the validation rules that this type's fields must comply with to be considered "valid"
     * The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]]
     *
     * @return array
     */
    public function _getValidationRules()
    {
        return self::$_validationRules;
    }

    /**
     * Validates that this type conforms to the specifications set forth for it by FHIR.  An empty array must be seen as
     * passing.
     *
     * @return array
     */
    public function _getValidationErrors()
    {
        $errs = parent::_getValidationErrors();
        $validationRules = $this->_getValidationRules();
        if ([] !== ($vs = $this->getDispense())) {
            foreach($vs as $i => $v) {
                if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                    $errs[sprintf('%s.%d', self::FIELD_DISPENSE, $i)] = $fieldErrs;
                }
            }
        }
        if (null !== ($v = $this->getIdentifier())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_IDENTIFIER] = $fieldErrs;
            }
        }
        if (null !== ($v = $this->getKind())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_KIND] = $fieldErrs;
            }
        }
        if (null !== ($v = $this->getOrderedItem())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_ORDERED_ITEM] = $fieldErrs;
            }
        }
        if (null !== ($v = $this->getPatient())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_PATIENT] = $fieldErrs;
            }
        }
        if (null !== ($v = $this->getStatus())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_STATUS] = $fieldErrs;
            }
        }
        if (isset($validationRules[self::FIELD_DISPENSE])) {
            $v = $this->getDispense();
            foreach($validationRules[self::FIELD_DISPENSE] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUPPLY, self::FIELD_DISPENSE, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_DISPENSE])) {
                        $errs[self::FIELD_DISPENSE] = [];
                    }
                    $errs[self::FIELD_DISPENSE][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_IDENTIFIER])) {
            $v = $this->getIdentifier();
            foreach($validationRules[self::FIELD_IDENTIFIER] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUPPLY, self::FIELD_IDENTIFIER, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_IDENTIFIER])) {
                        $errs[self::FIELD_IDENTIFIER] = [];
                    }
                    $errs[self::FIELD_IDENTIFIER][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_KIND])) {
            $v = $this->getKind();
            foreach($validationRules[self::FIELD_KIND] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUPPLY, self::FIELD_KIND, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_KIND])) {
                        $errs[self::FIELD_KIND] = [];
                    }
                    $errs[self::FIELD_KIND][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_ORDERED_ITEM])) {
            $v = $this->getOrderedItem();
            foreach($validationRules[self::FIELD_ORDERED_ITEM] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUPPLY, self::FIELD_ORDERED_ITEM, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_ORDERED_ITEM])) {
                        $errs[self::FIELD_ORDERED_ITEM] = [];
                    }
                    $errs[self::FIELD_ORDERED_ITEM][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_PATIENT])) {
            $v = $this->getPatient();
            foreach($validationRules[self::FIELD_PATIENT] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUPPLY, self::FIELD_PATIENT, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_PATIENT])) {
                        $errs[self::FIELD_PATIENT] = [];
                    }
                    $errs[self::FIELD_PATIENT][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_STATUS])) {
            $v = $this->getStatus();
            foreach($validationRules[self::FIELD_STATUS] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_SUPPLY, self::FIELD_STATUS, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_STATUS])) {
                        $errs[self::FIELD_STATUS] = [];
                    }
                    $errs[self::FIELD_STATUS][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_CONTAINED])) {
            $v = $this->getContained();
            foreach($validationRules[self::FIELD_CONTAINED] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_CONTAINED, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_CONTAINED])) {
                        $errs[self::FIELD_CONTAINED] = [];
                    }
                    $errs[self::FIELD_CONTAINED][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_LANGUAGE])) {
            $v = $this->getLanguage();
            foreach($validationRules[self::FIELD_LANGUAGE] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_LANGUAGE, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_LANGUAGE])) {
                        $errs[self::FIELD_LANGUAGE] = [];
                    }
                    $errs[self::FIELD_LANGUAGE][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_TEXT])) {
            $v = $this->getText();
            foreach($validationRules[self::FIELD_TEXT] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_RESOURCE, self::FIELD_TEXT, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_TEXT])) {
                        $errs[self::FIELD_TEXT] = [];
                    }
                    $errs[self::FIELD_TEXT][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_MODIFIER_EXTENSION])) {
            $v = $this->getModifierExtension();
            foreach($validationRules[self::FIELD_MODIFIER_EXTENSION] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BACKBONE_ELEMENT, self::FIELD_MODIFIER_EXTENSION, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_MODIFIER_EXTENSION])) {
                        $errs[self::FIELD_MODIFIER_EXTENSION] = [];
                    }
                    $errs[self::FIELD_MODIFIER_EXTENSION][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_EXTENSION])) {
            $v = $this->getExtension();
            foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_EXTENSION, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_EXTENSION])) {
                        $errs[self::FIELD_EXTENSION] = [];
                    }
                    $errs[self::FIELD_EXTENSION][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_ID])) {
            $v = $this->getId();
            foreach($validationRules[self::FIELD_ID] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_ID, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_ID])) {
                        $errs[self::FIELD_ID] = [];
                    }
                    $errs[self::FIELD_ID][$rule] = $err;
                }
            }
        }
        return $errs;
    }

    /**
     * @param \SimpleXMLElement|string|null $sxe
     * @param null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRResource\FHIRSupply $type
     * @param null|int $libxmlOpts
     * @return null|\DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRResource\FHIRSupply
     */
    public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872)
    {
        if (null === $sxe) {
            return null;
        }
        if (is_string($sxe)) {
            libxml_use_internal_errors(true);
            $sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false);
            if ($sxe === false) {
                throw new \DomainException(sprintf('FHIRSupply::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors()))));
            }
            libxml_use_internal_errors(false);
        }
        if (!($sxe instanceof \SimpleXMLElement)) {
            throw new \InvalidArgumentException(sprintf('FHIRSupply::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe)));
        }
        if (null === $type) {
            $type = new FHIRSupply;
        } elseif (!is_object($type) || !($type instanceof FHIRSupply)) {
            throw new \RuntimeException(sprintf(
                'FHIRSupply::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\DSTU1\FHIRElement\FHIRBackboneElement\FHIRResource\FHIRSupply or null, %s seen.',
                is_object($type) ? get_class($type) : gettype($type)
            ));
        }
        FHIRResource::xmlUnserialize($sxe, $type);
        $xmlNamespaces = $sxe->getDocNamespaces(false, false);
        if ([] !== $xmlNamespaces) {
            $ns = reset($xmlNamespaces);
            if (false !== $ns && '' !== $ns) {
                $type->_xmlns = $ns;
            }
        }
        $attributes = $sxe->attributes();
        $children = $sxe->children();
        if (isset($children->dispense)) {
            foreach($children->dispense as $child) {
                $type->addDispense(FHIRSupplyDispense::xmlUnserialize($child));
            }
        }
        if (isset($children->identifier)) {
            $type->setIdentifier(FHIRIdentifier::xmlUnserialize($children->identifier));
        }
        if (isset($children->kind)) {
            $type->setKind(FHIRCodeableConcept::xmlUnserialize($children->kind));
        }
        if (isset($children->orderedItem)) {
            $type->setOrderedItem(FHIRResourceReference::xmlUnserialize($children->orderedItem));
        }
        if (isset($children->patient)) {
            $type->setPatient(FHIRResourceReference::xmlUnserialize($children->patient));
        }
        if (isset($children->status)) {
            $type->setStatus(FHIRSupplyStatus::xmlUnserialize($children->status));
        }
        return $type;
    }

    /**
     * @param null|\SimpleXMLElement $sxe
     * @param null|int $libxmlOpts
     * @return \SimpleXMLElement
     */
    public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872)
    {
        if (null === $sxe) {
            $sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false);
        }
        parent::xmlSerialize($sxe);
        if ([] !== ($vs = $this->getDispense())) {
            foreach($vs as $v) {
                if (null === $v) {
                    continue;
                }
                $v->xmlSerialize($sxe->addChild(self::FIELD_DISPENSE, null, $v->_getFHIRXMLNamespace()));
            }
        }
        if (null !== ($v = $this->getIdentifier())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_IDENTIFIER, null, $v->_getFHIRXMLNamespace()));
        }
        if (null !== ($v = $this->getKind())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_KIND, null, $v->_getFHIRXMLNamespace()));
        }
        if (null !== ($v = $this->getOrderedItem())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_ORDERED_ITEM, null, $v->_getFHIRXMLNamespace()));
        }
        if (null !== ($v = $this->getPatient())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_PATIENT, null, $v->_getFHIRXMLNamespace()));
        }
        if (null !== ($v = $this->getStatus())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_STATUS, null, $v->_getFHIRXMLNamespace()));
        }
        return $sxe;
    }

    /**
     * @return array
     */
    public function jsonSerialize()
    {
        $a = parent::jsonSerialize();
        if ([] !== ($vs = $this->getDispense())) {
            $a[self::FIELD_DISPENSE] = [];
            foreach($vs as $v) {
                if (null === $v) {
                    continue;
                }
                $a[self::FIELD_DISPENSE][] = $v;
            }
        }
        if (null !== ($v = $this->getIdentifier())) {
            $a[self::FIELD_IDENTIFIER] = $v;
        }
        if (null !== ($v = $this->getKind())) {
            $a[self::FIELD_KIND] = $v;
        }
        if (null !== ($v = $this->getOrderedItem())) {
            $a[self::FIELD_ORDERED_ITEM] = $v;
        }
        if (null !== ($v = $this->getPatient())) {
            $a[self::FIELD_PATIENT] = $v;
        }
        if (null !== ($v = $this->getStatus())) {
            $a[self::FIELD_STATUS] = $v->getValue();
            $enc = $v->jsonSerialize();
            $cnt = count($enc);
            if (0 < $cnt && (1 !== $cnt || (1 === $cnt && !array_key_exists(FHIRSupplyStatus::FIELD_VALUE, $enc)))) {
                unset($enc[FHIRSupplyStatus::FIELD_VALUE]);
                $a[self::FIELD_STATUS_EXT] = $enc;
            }
        }
        if ([] !== ($vs = $this->_getFHIRComments())) {
            $a[PHPFHIRConstants::JSON_FIELD_FHIR_COMMENTS] = $vs;
        }
        return [PHPFHIRConstants::JSON_FIELD_RESOURCE_TYPE => $this->_getResourceType()] + $a;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return self::FHIR_TYPE_NAME;
    }
}