text:
typedef void(^UIAlertControllerEasyCoderBlock) (UIAlertController * ins);

@interface UIAlertController (TFEasyCoder)

+( UIAlertController *)easyCoder:(UIAlertControllerEasyCoderBlock)block;
-(UIAlertController *)easyCoder:(UIAlertControllerEasyCoderBlock)block;

-(UIAlertController  *(^)(UIAlertAction *  preferredAction))set_preferredAction;
-(UIAlertController  *(^)(NSString *  title))set_title;
-(UIAlertController  *(^)(NSString *  message))set_message;

//superclass pros UIViewController
-(UIAlertController  *(^)(UITabBarItem *  tabBarItem))set_tabBarItem;
-(UIAlertController  *(^)(BOOL  hidesBottomBarWhenPushed))set_hidesBottomBarWhenPushed;
-(UIAlertController  *(^)(id<UIViewControllerTransitioningDelegate>    transitioningDelegate))set_transitioningDelegate;
-(UIAlertController  *(^)(UIView *  view))set_view;
//TF_EC_CHAIN_PROP_INT(UIAlertController ,NSString *,title)
-(UIAlertController  *(^)(BOOL  definesPresentationContext))set_definesPresentationContext;
-(UIAlertController  *(^)(BOOL  providesPresentationContextTransitionStyle))set_providesPresentationContextTransitionStyle;
-(UIAlertController  *(^)(long long  modalTransitionStyle))set_modalTransitionStyle;
-(UIAlertController  *(^)(long long  modalPresentationStyle))set_modalPresentationStyle;
-(UIAlertController  *(^)(BOOL  modalPresentationCapturesStatusBarAppearance))set_modalPresentationCapturesStatusBarAppearance;
-(UIAlertController  *(^)(BOOL  wantsFullScreenLayout))set_wantsFullScreenLayout;
-(UIAlertController  *(^)(unsigned long long  edgesForExtendedLayout))set_edgesForExtendedLayout;
-(UIAlertController  *(^)(BOOL  extendedLayoutIncludesOpaqueBars))set_extendedLayoutIncludesOpaqueBars;
-(UIAlertController  *(^)(BOOL  automaticallyAdjustsScrollViewInsets))set_automaticallyAdjustsScrollViewInsets;
-(UIAlertController  *(^)(CGSize  preferredContentSize))set_preferredContentSize;
-(UIAlertController  *(^)(CGSize  contentSizeForViewInPopover))set_contentSizeForViewInPopover;
-(UIAlertController  *(^)(BOOL  modalInPopover))set_modalInPopover;
//superclass pros UIResponder
-(UIAlertController  *(^)(NSUserActivity *  userActivity))set_userActivity;
//superclass pros NSObject
-(UIAlertController  *(^)(NSArray *  accessibilityElements))set_accessibilityElements;
-(UIAlertController  *(^)(NSArray *  accessibilityCustomActions))set_accessibilityCustomActions;
-(UIAlertController  *(^)(BOOL  isAccessibilityElement))set_isAccessibilityElement;
-(UIAlertController  *(^)(NSString *  accessibilityLabel))set_accessibilityLabel;
-(UIAlertController  *(^)(NSString *  accessibilityHint))set_accessibilityHint;
-(UIAlertController  *(^)(NSString *  accessibilityValue))set_accessibilityValue;
-(UIAlertController  *(^)(unsigned long long  accessibilityTraits))set_accessibilityTraits;
-(UIAlertController  *(^)(UIBezierPath *  accessibilityPath))set_accessibilityPath;
-(UIAlertController  *(^)(CGPoint  accessibilityActivationPoint))set_accessibilityActivationPoint;
-(UIAlertController  *(^)(NSString *  accessibilityLanguage))set_accessibilityLanguage;
-(UIAlertController  *(^)(BOOL  accessibilityElementsHidden))set_accessibilityElementsHidden;
-(UIAlertController  *(^)(BOOL  accessibilityViewIsModal))set_accessibilityViewIsModal;
-(UIAlertController  *(^)(BOOL  shouldGroupAccessibilityChildren))set_shouldGroupAccessibilityChildren;
-(UIAlertController  *(^)(long long  accessibilityNavigationStyle))set_accessibilityNavigationStyle;

-(UIAlertController *(^)(id value,NSString *key))set_ValueKey;

@end


text:
title: "&TextEdit"
layout: notes-list
---

redpajama_set_name: RedPajamaGithub


text:
  <title>Manipulate the DOM</title>

 Here is some text, add a class "done" to the parent div

remove the #release-1 div

Change this text to finish release 2

 add CSS to this div

  <template id="hidden">

 Congrats! You finished the challenge.

  </template>


text:
#include "phd.h"
#include "drift_tool.h"

#include <wx/gbsizer.h>
#include <wx/valnum.h>

enum Phase
{
    PHASE_ADJUST_AZ,
    PHASE_ADJUST_ALT,
};

enum Mode
{
    MODE_IDLE,
    MODE_DRIFT,
    MODE_ADJUST,
};

enum CtrlIds
{
    ID_SLEW = 10001,
    ID_SAVE,
    ID_DRIFT,
    ID_ADJUST,
    ID_PHASE,
    ID_TIMER,
};

struct DriftToolWin : public wxFrame
{
    DriftToolWin();
    ~DriftToolWin();

    void UpdatePhaseState();
    void UpdateModeState();

    Phase m_phase;
    Mode m_mode;
    bool m_drifting;
    bool m_need_end_dec_drift;
    bool m_save_lock_pos_is_sticky;
    bool m_save_use_subframes;
    GraphLogClientWindow::GRAPH_MODE m_save_graph_mode;
    int m_save_graph_length;
    int m_save_graph_height;

    bool m_can_slew;
    bool m_slewing;
    PHD_Point m_siteLatLong;

    wxStaticBitmap *m_bmp;
    wxBitmap *m_azArrowBmp;
    wxBitmap *m_altArrowBmp;
    wxStaticText *m_instructions;
    wxTextCtrl *m_raCurrent;
    wxTextCtrl *m_decCurrent;
    wxSpinCtrl *m_raSlew;
    wxSpinCtrl *m_decSlew;
    wxButton *m_slew;
    wxButton *m_saveCoords;
    wxStaticText *m_notesLabel;
    wxTextCtrl *m_notes;
    wxButton *m_drift;
    wxButton *m_adjust;
    wxButton *m_phaseBtn;
    wxStatusBar *m_statusBar;
    wxTimer *m_timer;

    void EnableSlew(bool enable);

    void OnSlew(wxCommandEvent& evt);
    void OnSaveCoords(wxCommandEvent& evt);
    void OnNotesText(wxCommandEvent& evt);
    void OnDrift(wxCommandEvent& evt);
    void OnAdjust(wxCommandEvent& evt);
    void OnPhase(wxCommandEvent& evt);
    void OnAppStateNotify(wxCommandEvent& evt);
    void OnClose(wxCloseEvent& evt);
    void OnTimer(wxTimerEvent& evt);

    void UpdateScopeCoordinates(void);

    DECLARE_EVENT_TABLE()
};

BEGIN_EVENT_TABLE(DriftToolWin, wxFrame)
    EVT_BUTTON(ID_SLEW, DriftToolWin::OnSlew)
    EVT_BUTTON(ID_SAVE, DriftToolWin::OnSaveCoords)
    EVT_BUTTON(ID_DRIFT, DriftToolWin::OnDrift)
    EVT_BUTTON(ID_ADJUST, DriftToolWin::OnAdjust)
    EVT_BUTTON(ID_PHASE, DriftToolWin::OnPhase)
    EVT_COMMAND(wxID_ANY, APPSTATE_NOTIFY_EVENT, DriftToolWin::OnAppStateNotify)
    EVT_CLOSE(DriftToolWin::OnClose)
    EVT_TIMER(ID_TIMER, DriftToolWin::OnTimer)
END_EVENT_TABLE()

DriftToolWin::DriftToolWin()
    : wxFrame(pFrame, wxID_ANY, _("Drift Align"), wxDefaultPosition, wxDefaultSize,
              wxCAPTION|wxCLOSE_BOX|wxMINIMIZE_BOX|wxSYSTEM_MENU|wxTAB_TRAVERSAL|wxFRAME_FLOAT_ON_PARENT|wxFRAME_NO_TASKBAR),
        m_need_end_dec_drift(false),
        m_slewing(false)
{
    SetBackgroundColour(wxColor(0xcccccc));

    SetSizeHints(wxDefaultSize, wxDefaultSize);

    // a vertical sizer holding everything
    wxBoxSizer *topSizer = new wxBoxSizer(wxVERTICAL);

    // a horizontal box sizer for the bitmap and the instructions
    wxBoxSizer *instrSizer = new wxBoxSizer(wxHORIZONTAL);

#   include "icons/AzArrow.xpm"
    m_azArrowBmp = new wxBitmap(AzArrow);
#   include "icons/AltArrow.xpm"
    m_altArrowBmp = new wxBitmap(AltArrow);

    m_bmp = new wxStaticBitmap(this, wxID_ANY, *m_azArrowBmp, wxDefaultPosition, wxSize(80, 100));
    instrSizer->Add(m_bmp, 0, wxALIGN_CENTER_VERTICAL|wxFIXED_MINSIZE, 5);

    m_instructions = new wxStaticText(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(300,90), wxALIGN_LEFT|wxST_NO_AUTORESIZE);
#ifdef __WXOSX__
    m_instructions->SetFont(*wxSMALL_FONT);
#endif
    m_instructions->Wrap(-1);
    instrSizer->Add(m_instructions, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

    topSizer->Add(instrSizer);

    // static box sizer holding the scope pointing controls
    wxStaticBoxSizer *sbSizer = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, _("Scope Pointing")), wxVERTICAL);

    // a grid box sizer for laying out scope pointing the controls
    wxGridBagSizer *gbSizer = new wxGridBagSizer(0, 0);
    gbSizer->SetFlexibleDirection(wxBOTH);
    gbSizer->SetNonFlexibleGrowMode(wxFLEX_GROWMODE_SPECIFIED);

    wxStaticText *txt;

    txt = new wxStaticText(this, wxID_ANY, _("Meridian Offset (deg)"), wxDefaultPosition, wxDefaultSize, 0);
    txt->Wrap(-1);
    gbSizer->Add(txt, wxGBPosition(0, 1), wxGBSpan(1, 1), wxALL, 5);

    txt = new wxStaticText(this, wxID_ANY, _("Declination (deg)"), wxDefaultPosition, wxDefaultSize, 0);
    txt->Wrap(-1);
    gbSizer->Add(txt, wxGBPosition(0, 2), wxGBSpan(1, 1), wxALL, 5);

    txt = new wxStaticText(this, wxID_ANY, _("Current"), wxDefaultPosition, wxDefaultSize, 0);
    txt->Wrap(-1);
    gbSizer->Add(txt, wxGBPosition(1, 0), wxGBSpan(1, 1), wxALL, 5);

    m_raCurrent = new wxTextCtrl(this, wxID_ANY, _T("--"), wxDefaultPosition, wxDefaultSize, wxTE_READONLY);
    gbSizer->Add(m_raCurrent, wxGBPosition(1, 1), wxGBSpan(1, 1), wxEXPAND | wxALL, 5);

    m_decCurrent = new wxTextCtrl(this, wxID_ANY, _T("--"), wxDefaultPosition, wxDefaultSize, wxTE_READONLY);
    gbSizer->Add(m_decCurrent, wxGBPosition(1, 2), wxGBSpan(1, 1), wxEXPAND | wxALL, 5);

    txt = new wxStaticText(this, wxID_ANY, _("Slew To"), wxDefaultPosition, wxDefaultSize, 0);
    txt->Wrap(-1);
    gbSizer->Add(txt, wxGBPosition(2, 0), wxGBSpan(1, 1), wxALL, 5);

    m_raSlew = new wxSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, -90, 90);
    gbSizer->Add(m_raSlew, wxGBPosition(2, 1), wxGBSpan(1, 1), wxEXPAND | wxALL, 5);

    m_decSlew = new wxSpinCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, -90, 90);
    gbSizer->Add(m_decSlew, wxGBPosition(2, 2), wxGBSpan(1, 1), wxEXPAND | wxALL, 5);

    m_slew = new wxButton(this, ID_SLEW, _("Slew"), wxDefaultPosition, wxDefaultSize, 0);
    m_slew->SetToolTip(_("Click to slew to given coordinates."));
    gbSizer->Add(m_slew, wxGBPosition(2, 3), wxGBSpan(1, 1), wxALL, 5);

    wxString label = _("Save");
    wxSize sz(GetTextExtent(label));
    sz.SetHeight(-1);
    sz.IncBy(16, 0);
    m_saveCoords = new wxButton(this, ID_SAVE, label, wxDefaultPosition, sz, 0);
    m_saveCoords->SetToolTip(_("Click to save these coordinates as the default location for this axis adjustment."));
    gbSizer->Add(m_saveCoords, wxGBPosition(2, 4), wxGBSpan(1, 1), wxTOP | wxBOTTOM | wxRIGHT, 5);

    // add grid bag sizer to static sizer
    sbSizer->Add(gbSizer, 1, wxALIGN_CENTER, 5);

    // add static sizer to top-level sizer
    topSizer->Add(sbSizer, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5);

    // add some padding below the static sizer
    topSizer->Add(0, 3, 0, wxEXPAND, 3);

    m_notesLabel = new wxStaticText(this, wxID_ANY, _("Altitude adjustment notes"), wxDefaultPosition, wxDefaultSize, 0);
    m_notesLabel->Wrap(-1);
    topSizer->Add(m_notesLabel, 0, wxEXPAND|wxTOP|wxLEFT, 8);

    m_notes = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxSize(-1, 54), wxTE_MULTILINE);
    pFrame->RegisterTextCtrl(m_notes);
    topSizer->Add(m_notes, 0, wxEXPAND | wxLEFT | wxRIGHT | wxBOTTOM, 5);
    m_notes->Bind(wxEVT_COMMAND_TEXT_UPDATED, &DriftToolWin::OnNotesText, this);

    // horizontal sizer for the buttons
    wxBoxSizer *hSizer = new wxBoxSizer(wxHORIZONTAL);

    // proportional pad on left of Drift button
    hSizer->Add(0, 0, 2, wxEXPAND, 5);

    m_drift = new wxButton(this, ID_DRIFT, _("Drift"), wxDefaultPosition, wxDefaultSize, 0);
    hSizer->Add(m_drift, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    // proportional pad on right of Drift button
    hSizer->Add(0, 0, 1, wxEXPAND, 5);

    m_adjust = new wxButton(this, ID_ADJUST, _("Adjust"), wxDefaultPosition, wxDefaultSize, 0);
    hSizer->Add(m_adjust, 0, wxALIGN_CENTER_VERTICAL|wxALL, 5);

    // proportional pad on right of Align button
    hSizer->Add(0, 0, 2, wxEXPAND, 5);

    m_phaseBtn = new wxButton(this, ID_PHASE, wxT("???"), wxDefaultPosition, wxDefaultSize, 0);
    hSizer->Add(m_phaseBtn, 0, wxALL|wxALIGN_CENTER_VERTICAL, 5);

    // add button sizer to top level sizer
    topSizer->Add(hSizer, 1, wxEXPAND|wxALL, 5);

    SetSizer(topSizer);

    m_statusBar = CreateStatusBar(1, wxST_SIZEGRIP, wxID_ANY);

    Layout();
    topSizer->Fit(this);

    int xpos = pConfig->Global.GetInt("/DriftTool/pos.x", -1);
    int ypos = pConfig->Global.GetInt("/DriftTool/pos.y", -1);
    MyFrame::PlaceWindowOnScreen(this, xpos, ypos);

    // can mount slew?
    m_can_slew = pPointingSource && pPointingSource->CanSlew();

    // get site lat/long from scope
    double lat, lon;
    m_siteLatLong.Invalidate();
    if (pPointingSource && !pPointingSource->GetSiteLatLong(&lat, &lon))
    {
        m_siteLatLong.SetXY(lat, lon);
    }

    m_timer = NULL;
    if (m_can_slew || (pPointingSource && pPointingSource->CanReportPosition()))
    {
        enum { SCOPE_POS_POLL_MS = 1500 };
        m_timer = new wxTimer(this, ID_TIMER);
        m_timer->Start(SCOPE_POS_POLL_MS, false /* continuous */);
    }

    // make sure graph window is showing
    if (!pFrame->pGraphLog->IsShown())
    {
        wxCommandEvent evt;
        evt.SetInt(1); // "Checked"
        pFrame->OnGraph(evt);
    }

    // graph must be showing RA/Dec
    m_save_graph_mode = pFrame->pGraphLog->SetMode(GraphLogClientWindow::MODE_RADEC);

    // resize graph scale
    m_save_graph_length = pFrame->pGraphLog->GetLength();
    pFrame->pGraphLog->SetLength(pConfig->Global.GetInt("/DriftTool/GraphLength", GraphLogWindow::DefaultMaxLength));
    m_save_graph_height = pFrame->pGraphLog->GetHeight();
    pFrame->pGraphLog->SetHeight(pConfig->Global.GetInt("/DriftTool/GraphHeight", GraphLogWindow::DefaultMaxHeight));
    pFrame->pGraphLog->Refresh();

    // we do not want sticky lock position enabled
    m_save_lock_pos_is_sticky = pFrame->pGuider->LockPosIsSticky();
    pFrame->pGuider->SetLockPosIsSticky(false);
    pFrame->tools_menu->FindItem(EEGG_STICKY_LOCK)->Check(false);

    m_save_use_subframes = pCamera->UseSubframes;

    m_phase = PHASE_ADJUST_AZ;
    m_mode = MODE_IDLE;
    UpdatePhaseState();
    UpdateModeState();
}

DriftToolWin::~DriftToolWin()
{
    delete m_timer;
    delete m_azArrowBmp;
    delete m_altArrowBmp;
    pFrame->pDriftTool = NULL;
}

void DriftToolWin::EnableSlew(bool enable)
{
    m_raSlew->Enable(enable);
    m_decSlew->Enable(enable);
    m_slew->Enable(enable && !m_slewing);
    m_saveCoords->Enable(enable);
}

static void LoadRADec(Phase phase, double *ra, double *dec)
{
    if (phase == PHASE_ADJUST_AZ)
    {
        *ra = pConfig->Global.GetDouble("/DriftTool/Az/SlewRAOfs", 0.0);
        *dec = pConfig->Global.GetDouble("/DriftTool/Az/SlewDec", 0.0);
    }
    else
    {
        *ra = pConfig->Global.GetDouble("/DriftTool/Alt/SlewRAOfs", -65.0);
        *dec = pConfig->Global.GetDouble("/DriftTool/Alt/SlewDec", 0.0);
    }
}

static void SaveRADec(Phase phase, double ra, double dec)
{
    if (phase == PHASE_ADJUST_AZ)
    {
        pConfig->Global.SetDouble("/DriftTool/Az/SlewRAOfs", ra);
        pConfig->Global.SetDouble("/DriftTool/Az/SlewDec", dec);
    }
    else
    {
        pConfig->Global.SetDouble("/DriftTool/Alt/SlewRAOfs", ra);
        pConfig->Global.SetDouble("/DriftTool/Alt/SlewDec", dec);
    }
}

void DriftToolWin::UpdatePhaseState()
{
    double ra, dec;
    LoadRADec(m_phase, &ra, &dec);
    m_raSlew->SetValue((int) floor(ra));
    m_decSlew->SetValue((int) floor(dec));

    if (m_phase == PHASE_ADJUST_AZ)
    {
        SetTitle(_("Drift Align - Azimuth Adjustment"));
        m_bmp->SetBitmap(*m_azArrowBmp);
        m_instructions->SetLabel(
            _("Slew to near the Meridian and the Equator.\n"
              "Press Drift to measure drift.\n"
              "Press Adjust and adjust your mount's azimuth.\n"
              "Repeat Drift/Adjust until alignment is complete.\n"
              "Then, click Altitude to begin Altitude adjustment."));
        m_notesLabel->SetLabel(_("Azimuth adjustment notes"));
        m_notes->SetValue(pConfig->Profile.GetString("/DriftTool/Az/Notes", wxEmptyString));
        m_phaseBtn->SetLabel(_("> Altitude"));
    }
    else
    {
        SetTitle(_("Drift Align - Altitude Adjustment"));
        m_bmp->SetBitmap(*m_altArrowBmp);
        m_instructions->SetLabel(
            _("Slew to a location near the Equator and the Eastern or Western horizon.\n"
              "Press Drift to measure drift.\n"
              "Press Adjust and adjust your mount's altitude.\n"
              "Repeat Drift/Adjust until alignment is complete.\n"
              "Click Azimuth to repeat Azimuth adjustment."));
        m_notesLabel->SetLabel(_("Altitude adjustment notes"));
        m_notes->SetValue(pConfig->Profile.GetString("/DriftTool/Alt/Notes", wxEmptyString));
        m_phaseBtn->SetLabel(_("< Azimuth"));
    }
}

void DriftToolWin::UpdateModeState()
{
    wxCommandEvent dummy;
    wxString idleStatus;

repeat:

    if (m_mode == MODE_DRIFT)
    {
        m_drift->Enable(false);
        m_adjust->Enable(true);
        EnableSlew(false);

        // restore subframes setting
        pCamera->UseSubframes = m_save_use_subframes;

        if (!m_drifting)
        {
            if (!pCamera->Connected ||
                !pMount || !pMount->IsConnected())
            {
                idleStatus = _("Please connect a camera and a mount");
                m_mode = MODE_IDLE;
                goto repeat;
            }

            if (!pMount->IsCalibrated())
            {
                idleStatus = _("Please calibrate before starting drift alignment");
                m_mode = MODE_IDLE;
                goto repeat;
            }

            if (!pFrame->CaptureActive)
            {
                // loop exposures
                SetStatusText(_("Start Looping..."));
                pFrame->OnLoopExposure(dummy);
                return;
            }

            switch (pFrame->pGuider->GetState())
            {
            case STATE_UNINITIALIZED:
            case STATE_CALIBRATED:
            case STATE_SELECTING:
                SetStatusText(_("Auto-selecting a star"));
                pFrame->OnAutoStar(dummy);
                return;
            case STATE_CALIBRATING_PRIMARY:
            case STATE_CALIBRATING_SECONDARY:
                if (!pMount->IsCalibrated())
                    SetStatusText(_("Waiting for calibration to complete..."));
                return;
            case STATE_SELECTED:
                SetStatusText(_("Start guiding..."));
                pFrame->OnGuide(dummy);
                return;
            case STATE_GUIDING:
                // turn of dec guiding
                if (!m_need_end_dec_drift)
                {
                    pMount->StartDecDrift();
                    m_need_end_dec_drift = true;
                }
                // clear graph data
                SetStatusText(_("Drifting... click Adjust when done drifting"));
                pFrame->pGraphLog->OnButtonClear(dummy);
                pFrame->pGraphLog->EnableTrendLines(true);
                m_drifting = true;
                return;
            case STATE_STOP:
                return;
            }
        }
    }
    else if (m_mode == MODE_ADJUST)
    {
        m_drift->Enable(true);
        m_adjust->Enable(false);
        m_drifting = false;
        EnableSlew(m_can_slew);
        SetStatusText(m_phase == PHASE_ADJUST_AZ ? _("Adjust azimuth, click Drift when done") :
            _("Adjust altitude, click Drift when done"));

        // use full frames for adjust phase
        pCamera->UseSubframes = false;

        if (pFrame->pGuider->IsGuiding())
        {
            // stop guiding but continue looping
            pFrame->OnLoopExposure(dummy);

            // Set the lock position to the where the star has drifted to. This will be the center of the polar align circle.
            pFrame->pGuider->SetLockPosition(pFrame->pGuider->CurrentPosition());
            pFrame->pGraphLog->Refresh();  // polar align circle is updated in graph window's OnPaint handler
        }
    }
    else // MODE_IDLE
    {
        m_drift->Enable(true);
        m_adjust->Enable(true);
        m_drifting = false;
        EnableSlew(m_can_slew);
        SetStatusText(idleStatus);

        // restore subframes setting
        pCamera->UseSubframes = m_save_use_subframes;

        if (pFrame->pGuider->IsGuiding())
        {
            // stop guiding but continue looping
            pFrame->OnLoopExposure(dummy);
        }
    }
}

void DriftToolWin::OnSlew(wxCommandEvent& evt)
{
    double raSlew = (double) m_raSlew->GetValue();
    double decSlew = (double) m_decSlew->GetValue();

    double cur_ra, cur_dec, cur_st;
    if (pPointingSource->GetCoordinates(&cur_ra, &cur_dec, &cur_st))
    {
        Debug.AddLine("Drift tool: slew failed to get scope coordinates");
        return;
    }

    wxBusyCursor busy;

    double slew_ra = cur_st + (raSlew * 24.0 / 360.0);
    if (slew_ra >= 24.0)
        slew_ra -= 24.0;
    else if (slew_ra < 0.0)
        slew_ra += 24.0;
    Debug.AddLine(wxString::Format("Drift tool slew from ra %.2f, dec %.1f to ra %.2f, dec %.1f", cur_ra, cur_dec, slew_ra, decSlew));
    m_slewing = true;
    m_slew->Enable(false);
    GetStatusBar()->PushStatusText(_("Slewing ..."));
    if (pPointingSource->SlewToCoordinates(slew_ra, decSlew))
    {
        GetStatusBar()->PopStatusText();
        m_slewing = false;
        m_slew->Enable(true);
        Debug.AddLine("Drift tool: slew failed");
    }
    SaveRADec(m_phase, raSlew, decSlew);
}

void DriftToolWin::OnSaveCoords(wxCommandEvent& evt)
{
    double raSlew = (double) m_raSlew->GetValue();
    double decSlew = (double) m_decSlew->GetValue();

    SaveRADec(m_phase, raSlew, decSlew);
    SetStatusText(_("Coordinates saved."));
}

void DriftToolWin::OnNotesText(wxCommandEvent& evt)
{
    if (m_phase == PHASE_ADJUST_AZ)
    {
        pConfig->Profile.SetString("/DriftTool/Az/Notes", m_notes->GetValue());
    }
    else
    {
        pConfig->Profile.SetString("/DriftTool/Alt/Notes", m_notes->GetValue());
    }
}

void DriftToolWin::OnDrift(wxCommandEvent& evt)
{
    m_mode = MODE_DRIFT;
    UpdateModeState();
}

void DriftToolWin::OnAdjust(wxCommandEvent& evt)
{
    m_mode = MODE_ADJUST;
    UpdateModeState();
}

void DriftToolWin::OnPhase(wxCommandEvent& evt)
{
    if (m_phase == PHASE_ADJUST_ALT)
        m_phase = PHASE_ADJUST_AZ;
    else
        m_phase = PHASE_ADJUST_ALT;

    UpdatePhaseState();

    if (m_mode != MODE_IDLE)
    {
        m_mode = MODE_IDLE;
        UpdateModeState();
    }
}

void DriftToolWin::OnAppStateNotify(wxCommandEvent& evt)
{
    UpdateModeState();
}

void DriftToolWin::OnClose(wxCloseEvent& evt)
{
    Debug.AddLine("Close DriftTool");

    if (m_need_end_dec_drift)
    {
        pMount->EndDecDrift();
        pFrame->pGraphLog->EnableTrendLines(false);
        m_need_end_dec_drift = false;
    }

    // restore graph mode
    pFrame->pGraphLog->SetMode(m_save_graph_mode);

    // restore graph scale
    pConfig->Global.SetInt("/DriftTool/GraphLength", pFrame->pGraphLog->GetLength());
    pFrame->pGraphLog->SetLength(m_save_graph_length);
    pConfig->Global.SetInt("/DriftTool/GraphHeight", pFrame->pGraphLog->GetHeight());
    pFrame->pGraphLog->SetHeight(m_save_graph_height);
    pFrame->pGraphLog->Refresh();

    // turn sticky lock position back on if we disabled it
    if (m_save_lock_pos_is_sticky)
    {
        pFrame->pGuider->SetLockPosIsSticky(true);
        pFrame->tools_menu->FindItem(EEGG_STICKY_LOCK)->Check(true);
    }

    // restore subframes setting
    pCamera->UseSubframes = m_save_use_subframes;

    // save the window position
    int x, y;
    GetPosition(&x, &y);
    pConfig->Global.SetInt("/DriftTool/pos.x", x);
    pConfig->Global.SetInt("/DriftTool/pos.y", y);

    // restore polar align circle correction factor
    pFrame->pGuider->SetPolarAlignCircleCorrection(1.0);

    Destroy();
}

void DriftToolWin::UpdateScopeCoordinates(void)
{
    if (!pMount)
        return;

    double ra_hrs, dec_deg, st_hrs;
    if (pPointingSource->GetCoordinates(&ra_hrs, &dec_deg, &st_hrs))
        return; // error
    double ra_ofs_deg = (ra_hrs - st_hrs) * (360.0 / 24.0);
    if (ra_ofs_deg > 180.0)
        ra_ofs_deg -= 360.0;
    if (ra_ofs_deg <= -180.0)
        ra_ofs_deg += 360.0;

    m_raCurrent->SetValue(wxString::Format("%+.f", ra_ofs_deg));
    m_decCurrent->SetValue(wxString::Format("%+.f", dec_deg));

    // update polar align circle radius
    if (m_siteLatLong.IsValid())
    {
        double correction;

        if (m_phase == PHASE_ADJUST_AZ)
        {
            // azimuth correction from "Star Offset Positioning for Polar Axis Alignment", Frank Barrett, 2/19/2010
            double dec_r = radians(dec_deg);
            if (fabs(dec_r) < Mount::DEC_COMP_LIMIT)
            {
                double alt_r = radians(90.0 - m_siteLatLong.X + dec_deg);
                correction = cos(alt_r) / cos(dec_r);
            }
            else
            {
                correction = 1.0;
            }
        }
        else
        {
            // altitude correction:
            //     convert scope coordinates (RA = a, Dec = d) to cartesian coords:
            //     x = cos a cos d
            //     y = sin a cos d
            //     z = sin d
            // altitude adjustment is rotation about x-axis, so correction factor is radius of
            // circle of projection of scope vector onto the plane of the meridian (y-z plane)
            //     r^2 = y^2 + z^2
            // substitute y and z above and use a = 90 - h   (h = hour angle)
            //
            //  -ag
            //
            double ha_r = radians(ra_ofs_deg);
            double cos_dec = cos(radians(dec_deg));
            double cos_ha = cos(ha_r);
            correction = sqrt(1. + cos_dec * cos_dec * (cos_ha * cos_ha - 1.));

            // drift rate for the altitude measurement is assumed to be measured at the horizon,
            // but rate decreases as we move away from the horizon - Measuring Polar Axis Alignment
            // Error, Frank Barrett 2nd Edition 2 / 19 / 2010, Equation (2)
            if (fabs(ra_ofs_deg) > 15.)
            {
                correction /= fabs(sin(ha_r));
            }
            else
            {
                correction = 1.0;
            }
        }

        pFrame->pGuider->SetPolarAlignCircleCorrection(correction);
    }
}

void DriftToolWin::OnTimer(wxTimerEvent& evt)
{
    UpdateScopeCoordinates();

    if (m_slewing)
    {
        if (!pPointingSource || !pPointingSource->Slewing())
        {
            m_slew->Enable(true);
            m_slewing = false;
            GetStatusBar()->PopStatusText(); // clear "slewing" message
        }
    }
}

wxWindow *DriftTool::CreateDriftToolWindow()
{
    // confirm that image scale is specified

    if (pFrame->GetCameraPixelScale() == 1.0)
    {
        bool confirmed = ConfirmDialog::Confirm(_(
            "The Drift Align tool is most effective when PHD2 knows your guide\n"
            "scope focal length and camera pixel size.\n"
            "\n"
            "Enter your guide scope focal length on the Global tab in the Brain.\n"
            "Enter your camera pixel size on the Camera tab in the Brain.\n"
            "\n"
            "Would you like to run the drift tool anyway?"),
                "/drift_tool_without_pixscale");

        if (!confirmed)
        {
            return 0;
        }
    }

    return new DriftToolWin();
}


text:
namespace base {

// Allocates memory via system allocators. Alas, they take a _signed_ size for
// allocation.
void* AllocateViaCFAllocatorSystemDefault(ssize_t size);
void* AllocateViaCFAllocatorMalloc(ssize_t size);
void* AllocateViaCFAllocatorMallocZone(ssize_t size);

#if !defined(ARCH_CPU_64_BITS)
// See process_util_unittest_mac.mm for an explanation of why this function
// isn't implemented for the 64-bit environment.

// Allocates a huge Objective C object.
void* AllocatePsychoticallyBigObjCObject();

#endif  // !ARCH_CPU_64_BITS

}  // namespace base

#endif  // BASE_PROCESS_UTIL_UNITTEST_MAC_H_


text:
layout: sidebar-right
title: "Move it! Sports equipment now on offer from six Suffolk Libraries"
date: 2018-06-21
author: james-powell
category: news
excerpt: 'Suffolk Libraries is doing its bit to make Suffolk the most active county, with six libraries now offering a range of sports equipment for customers to borrow.'
featured-image: /images/featured/featured-move-it.jpg
featured-alt: "Young people using our sports equipment"
breadcrumb: news
---

![Young people using our sports equipment](/images/featured/featured-move-it.jpg)

Suffolk Libraries is doing its bit to make Suffolk the most active county, with six libraries now offering a range of sports equipment for customers to borrow.

The Move It pilot project will offer people the chance to borrow sports and outdoor game equipment from Bury St Edmunds, Haverhill, Stowmarket, Saxmundham, Gainsborough and Newmarket libraries. The equipment on offer varies but includes dumbbells, play parachutes, swingball, badminton, bowling, football, cricket, basketball, tennis, yoga and rounders equipment.

The equipment can be borrowed by library customers aged over 16. It can be borrowed for up to three weeks and, like other library loans, will incur overdue charges to encourage borrowers to bring it back so others can use it.

The Move It equipment has been provided by Suffolk Libraries' New Chapters Mental Health and Wellbeing service to encourage library customers to be more active and try something new.

Sarah Lungley, mental health and wellbeing coordinator, said: "Suffolk Libraries are proud to support the Most Active County initiative to help get people moving more and to improve their wellbeing. Our libraries are places people come for a huge range of services and information so we hope that some of our customers will take some of this equipment home and enjoy some new activities with their friends and family."

Councillor James Reeder, Suffolk County Council's Cabinet Member for Health, said: "I'm pleased to see the library taking the initiative to provide a sports equipment loan scheme. Libraries are at the heart of local communities so they are ideally placed to support local people.

"I hope this project will encourage more people and families to be active together as well as help to reduce the financial barriers to playing sport and, in doing so, contribute to our ambition of becoming the most active county in England."


text:
<#
.EXAMPLE
    This example shows how to ensure the SQL Server service
    on TestServer\DSC is running under a virtual account.
    Force will cause this account to be set every time the
    configuration is evaluated. Specifying RestartService will
    cause the service to be restarted.
#>

Configuration Example
{
    param(
        [Parameter(Mandatory = $true)]
        [PSCredential]
        $ServiceAcccountCredential
    )

    Import-DscResource -ModuleName xSqlServer

    Node localhost {
        xSQLServerServiceAccount SetServiceAcccount_User
        {
            SQLServer = 'TestServer'
            SQLInstanceName = 'DSC'
            ServiceType = 'DatabaseEngine'
            ServiceAccount = $ServiceAcccountCredential
            RestartService = $true
            Force = $true
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<job id="properties-job" xmlns="http://xmlns.jcp.org/xml/ns/javaee" version="1.0">
    <properties>
        <property name="outputCsvFilePath" value="#{jobParameters['csvFilePath']}"/>
        <property name="outputArchiveCsvFilePath" value="#{jobParameters['archiveCsvFilePath']}"/>
    </properties>

    <step id="write-csv" next="decision">
        <properties>
            <property name="writeStepStatus" value="#{jobParameters['writeStepStatus']}"/>
        </properties>
        <chunk item-count="4">
            <reader ref="languagesItemReader"/>
            <processor ref="languagesItemProcessor"/>
            <writer ref="propertiesCsvItemWriter"/>
        </chunk>
    </step>

    <decision id="decision" ref="csvDecider">
        <next on="DECISION-SUCCESS" to="archive"/>
        <fail on="*" exit-status="DECISION-FAILED-END"/>
    </decision>

    <step id="archive">
        <batchlet ref="propertiesCsvArchiveBatchlet"/>
    </step>
</job>


text:
'use strict';

var chai            = require('chai'),
    mochaAsPromised = require('mocha-as-promised');

chai.use(require('chai-as-promised'));
mochaAsPromised();


text:
qc::response message alert
===========

part of [Connection Response API](../response_api.md)

Usage
-----
`qc::response message alert message`

Description
-----------
Sets the alert element of the message object in the [connection response](../connection-response.md) with the given message.

Examples
--------
```tcl

% qc::response message alert "Incorrect username or password."
message {alert {value {Incorrect username or password.}}}

```

----------------------------------
*[Qcode Software Limited] [qcode]*

[qcode]: http://www.qcode.co.uk "Qcode Software"


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Morelet, Annales de la Société des Sciences Naturelles et d'Archéologie de Toulon et du Var 47(2): 93 (1995)

#### Original name
Wardomyces aggregatus Malloch, 1970

### Remarks
null


text:
package juice.core.util.io;

import juice.core.util.Assert;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author Ricky Fung
 */
public abstract class StreamUtils {

    public static final int BUFFER_SIZE = 4096;

    public static int copy(InputStream in, OutputStream out) throws IOException {
        Assert.notNull(in, "No InputStream specified");
        Assert.notNull(out, "No OutputStream specified");
        int byteCount = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        int bytesRead = -1;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
            byteCount += bytesRead;
        }
        out.flush();
        return byteCount;
    }

    public static void closeQuietly(InputStream input){
        closeQuietly((Closeable)input);
    }

    public static void closeQuietly(OutputStream output){
        closeQuietly((Closeable)output);
    }

    public static void closeQuietly(Closeable closeable) {
        try {
            if(closeable != null) {
                closeable.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void closeQuietly(Closeable... closeables){
        for (Closeable closeable : closeables){
            closeQuietly(closeable);
        }
    }

}


text:
import { HttpRequestParameters } from "../../../Primitives/Http";
import { IOperation, OperationResultType } from "../OperationAbstractions";
import { CompareExchangeValue } from "./CompareExchangeValue";
import { throwError } from "../../../Exceptions";
import { CompareExchangeResultClass } from "../../../Types";
import { IDocumentStore } from "../../IDocumentStore";
import { DocumentConventions } from "../../Conventions/DocumentConventions";
import { HttpCache } from "../../../Http/HttpCache";
import { RavenCommand } from "../../../Http/RavenCommand";
import { ServerNode } from "../../../Http/ServerNode";
import { CompareExchangeValueResultParser, GetCompareExchangeValuesResponse } from "./CompareExchangeValueResultParser";
import * as stream from "readable-stream";
import { StringBuilder } from "../../../Utility/StringBuilder";
import { TypeUtil } from "../../../Utility/TypeUtil";

export interface GetCompareExchangeValuesParameters<T> {
    keys?: string[];

    startWith?: string;
    start?: number;
    pageSize?: number;

    materializeMetadata?: boolean;

    clazz?: CompareExchangeResultClass<T>;
}

export class GetCompareExchangeValuesOperation<T> implements IOperation<{ [key: string]: CompareExchangeValue<T> }> {

    private readonly _clazz: CompareExchangeResultClass<T>;
    private readonly _keys: string[];

    private readonly _startWith: string;
    private readonly _start: number;
    private readonly _pageSize: number;

    private readonly _materializeMetadata: boolean;

    public get keys(): string[] {
        return this._keys;
    }

    public get startWith(): string {
        return this._startWith;
    }

    public get start(): number {
        return this._start;
    }

    public get pageSize(): number {
        return this._pageSize;
    }

    public get clazz(): CompareExchangeResultClass<T> {
        return this._clazz;
    }

    public constructor(parameters: GetCompareExchangeValuesParameters<T>) {
        this._clazz = parameters.clazz;
        this._materializeMetadata = parameters.materializeMetadata || true;

        if (parameters.keys) {
            if (!parameters.keys.length) {
                throwError("InvalidArgumentException", "Keys cannot be an empty array.");
            }

            this._keys = parameters.keys;
        } else if (!TypeUtil.isNullOrUndefined(parameters.startWith)) {
            this._startWith = parameters.startWith;
            this._start = parameters.start;
            this._pageSize = parameters.pageSize;
        } else {
            throwError("InvalidArgumentException", "Please specify at least keys or startWith parameter");
        }
    }

    public getCommand(store: IDocumentStore, conventions: DocumentConventions, cache: HttpCache)
        : RavenCommand<{ [key: string]: CompareExchangeValue<T> }> {
        return new GetCompareExchangeValuesCommand(this, this._materializeMetadata, conventions);
    }

    public get resultType(): OperationResultType {
        return "CommandResult";
    }
}

export class GetCompareExchangeValuesCommand<T> extends RavenCommand<{ [key: string]: CompareExchangeValue<T> }> {
    private _operation: GetCompareExchangeValuesOperation<T>;
    private readonly _materializeMetadata: boolean;
    private readonly _conventions: DocumentConventions;

    public constructor(operation: GetCompareExchangeValuesOperation<T>, materializeMetadata: boolean, conventions: DocumentConventions) {
        super();
        this._operation = operation;
        this._materializeMetadata = materializeMetadata;
        this._conventions = conventions;
    }

    public get isReadRequest(): boolean {
        return true;
    }

    public createRequest(node: ServerNode): HttpRequestParameters {
        const pathBuilder = new StringBuilder(node.url);

        pathBuilder.append("/databases/")
            .append(node.database)
            .append("/cmpxchg?");

        if (this._operation.keys) {
            for (const key of this._operation.keys) {
                pathBuilder.append("&key=").append(encodeURIComponent(key));
            }
        } else {
            if (this._operation.startWith) {
                pathBuilder.append("&startsWith=")
                    .append(encodeURIComponent(this._operation.startWith));
            }

            if (this._operation.start) {
                pathBuilder.append("&start=")
                    .append(this._operation.start);
            }

            if (this._operation.pageSize) {
                pathBuilder.append("&pageSize=")
                    .append(this._operation.pageSize);
            }
        }

        const uri = pathBuilder.toString();

        return { uri };
    }

    public async setResponseAsync(bodyStream: stream.Stream, fromCache: boolean): Promise<string> {
        let body: string = null;

        if (!bodyStream) {
            this.result = {};
            return body;
        }

        const results = await this._pipeline<GetCompareExchangeValuesResponse>()
            .collectBody(b => body = b)
            .parseJsonAsync()
            .jsonKeysTransform("GetCompareExchangeValue", this._conventions)
            .process(bodyStream);

        this.result = CompareExchangeValueResultParser.getValues<T>(
            results, this._materializeMetadata, this._conventions, this._operation.clazz);

        return body;
    }
}


text:
.class public Landroid/net/http/X509TrustManagerExtensions;
.super Ljava/lang/Object;
.source "X509TrustManagerExtensions.java"

# instance fields
.field mDelegate:Lcom/android/org/conscrypt/TrustManagerImpl;

# direct methods
.method public constructor <init>(Ljavax/net/ssl/X509TrustManager;)V
    .locals 3
    .param p1, "tm"    # Ljavax/net/ssl/X509TrustManager;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/lang/IllegalArgumentException;
        }
    .end annotation

    .prologue
    .line 47
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 48
    instance-of v0, p1, Lcom/android/org/conscrypt/TrustManagerImpl;

    if-eqz v0, :cond_0

    .line 49
    check-cast p1, Lcom/android/org/conscrypt/TrustManagerImpl;

    .end local p1    # "tm":Ljavax/net/ssl/X509TrustManager;
    iput-object p1, p0, Landroid/net/http/X509TrustManagerExtensions;->mDelegate:Lcom/android/org/conscrypt/TrustManagerImpl;

    .line 54
    return-void

    .line 51
    .restart local p1    # "tm":Ljavax/net/ssl/X509TrustManager;
    :cond_0
    new-instance v0, Ljava/lang/IllegalArgumentException;

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v2, "tm is an instance of "

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {p1}, Ljava/lang/Object;->getClass()Ljava/lang/Class;

    move-result-object v2

    invoke-virtual {v2}, Ljava/lang/Class;->getName()Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string v2, " which is not a supported type of X509TrustManager"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-direct {v0, v1}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v0
.end method

# virtual methods
.method public checkServerTrusted([Ljava/security/cert/X509Certificate;Ljava/lang/String;Ljava/lang/String;)Ljava/util/List;
    .locals 1
    .param p1, "chain"    # [Ljava/security/cert/X509Certificate;
    .param p2, "authType"    # Ljava/lang/String;
    .param p3, "host"    # Ljava/lang/String;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "([",
            "Ljava/security/cert/X509Certificate;",
            "Ljava/lang/String;",
            "Ljava/lang/String;",
            ")",
            "Ljava/util/List",
            "<",
            "Ljava/security/cert/X509Certificate;",
            ">;"
        }
    .end annotation

    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/security/cert/CertificateException;
        }
    .end annotation

    .prologue
    .line 68
    iget-object v0, p0, Landroid/net/http/X509TrustManagerExtensions;->mDelegate:Lcom/android/org/conscrypt/TrustManagerImpl;

    invoke-virtual {v0, p1, p2, p3}, Lcom/android/org/conscrypt/TrustManagerImpl;->checkServerTrusted([Ljava/security/cert/X509Certificate;Ljava/lang/String;Ljava/lang/String;)Ljava/util/List;

    move-result-object v0

    return-object v0
.end method

.method public isUserAddedCertificate(Ljava/security/cert/X509Certificate;)Z
    .locals 1
    .param p1, "cert"    # Ljava/security/cert/X509Certificate;

    .prologue
    .line 82
    iget-object v0, p0, Landroid/net/http/X509TrustManagerExtensions;->mDelegate:Lcom/android/org/conscrypt/TrustManagerImpl;

    invoke-virtual {v0, p1}, Lcom/android/org/conscrypt/TrustManagerImpl;->isUserAddedCertificate(Ljava/security/cert/X509Certificate;)Z

    move-result v0

    return v0
.end method


text:
docker_id=$1
docker_repo=$2

curl -sf "https://registry.hub.docker.com/v2/repositories/${docker_id}/${docker_repo}/tags/" | \
jq -r '."results"[]["name"]'


text:
<?xml version="1.0" encoding="UTF-8"?>
<ApexPage xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>28.0</apiVersion>
    <label>Monitoring Updates</label>
</ApexPage>


text:
package trello

type Attachment struct {
	client    *Client
	Id        string `json:"id"`
	Bytes     int    `json:"bytes"`
	Date      string `json:"date"`
	EdgeColor string `json:"edgeColor"`
	IdMember  string `json:"idMember"`
	IsUpload  bool   `json:"isUpload"`
	MimeType  string `json:"mimeType"`
	Name      string `json:"name"`
	Previews  []struct {
		Width  int    `json:"width"`
		Height int    `json:"height"`
		Url    string `json:"url"`
		Bytes  int    `json:"bytes"`
		Id     string `json:"_id"`
		Scaled bool   `json:"scaled"`
	} `json:"previews"`
	Url string `json:"url"`
}


text: echo "Getting some work done ..."


text:
import Em from 'ember';
var computed = Em.computed;
var alias = Em.computed.alias;

var PaginationFooterController = Em.Controller.extend({
	item: computed('content.@each.item', function () {
		var vals = this.get('content').mapBy('item');
		var sum = vals.reduce(function (total, val) {
			return total + val;
		}, 0);
		return sum;
	})
});

export default PaginationFooterController;


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.vale.migeoavisador.MainActivity">

    <TextView
        android:id="@+id/mensajismo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"/>

    <TextView
        android:id="@+id/nacts"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="0"/>

    <TextView android:textSize="14sp" android:id="@+id/latitud" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Latitud"/>
    <TextView android:id="@+id/coordenadas_latitud" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:layout_alignRight="@id/latitud"/>
    <TextView android:textSize="14sp" android:id="@+id/longuitud" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Longuitud"/>
    <TextView android:id="@+id/coordenadas_longuitud" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:layout_alignRight="@id/longuitud"/>
    <TextView android:textSize="14sp" android:id="@+id/altura" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Longuitud"/>
    <TextView android:id="@+id/coordenadas_altura" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:layout_alignRight="@id/longuitud"/>
    <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="ACTUALIZA_POS" android:onClick="actualizaBoton"/>
    <TextView android:id="@+id/log" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>


text:
A promise library that violates everything you know about promises.

## Things You Can Do

 *Create promises where the resolver can reset the promise to resolve/reject again.
 *Create deferreds that can be reset to resolve/reject again. Again

## Why on earth would you do this?

  *Create a promise that always resolves with an open connection (reset the promise on conn.close or conn.err)
  *Pipeline dynamic dependencies through normal promise symantics

## Usage

Install via NPM

    $ npm install recant

## Example- Promise

```javascript
var recant = require('recant') ;
var promise = recant.promise(function(resolve,reject,notify,reset){

	var connPromise = connection.open() ;
	connPromise.then(function(conn){
		resolve(conn) ;
		conn.on('close',reset) ;
	}).then(null,function(err){
		reject(err) ;
	})

})
```
## Example- Deferred

```javascript
var recant = require('recant') ;
var deferred = recant.defer() ;
var promise = deferred.promise ;

deferred.resolve(val); // as of now, all promise.then calls will resolve with a value
deferred.reset() ; // now, all promise.then calls ( against the same promise ) will be pending until resolved or rejected again
deferred.reject(err) ; // now, all promise.then calls will be rejected as the state has changed
```


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CompositionContextExportDescriptorProvider.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Implements the composition context export descriptor provider class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Composition.Mef.ExportProviders
{
    using System;
    using System.Collections.Generic;
    using System.Composition.Hosting.Core;

    using Kephas.Composition.Mef.Hosting;
    using Kephas.Diagnostics.Contracts;

    /// <summary>
    /// A composition context export descriptor provider.
    /// </summary>
    public class CompositionContextExportDescriptorProvider : ExportDescriptorProvider, IExportProvider
    {
        /// <summary>
        /// The composition container.
        /// </summary>
        private readonly ICompositionContext compositionContainer;

        /// <summary>
        /// Initializes a new instance of the <see cref="CompositionContextExportDescriptorProvider"/>
        /// class.
        /// </summary>
        /// <param name="compositionContainer">The composition container.</param>
        public CompositionContextExportDescriptorProvider(ICompositionContext compositionContainer)
        {
            Requires.NotNull(compositionContainer, nameof(compositionContainer));
            this.compositionContainer = compositionContainer;
        }

        /// <summary>
        /// Promise export descriptors for composition context.
        /// </summary>
        /// <param name="contract">The export key required by another component.</param><param name="descriptorAccessor">Accesses the other export descriptors present in the composition.</param>
        /// <returns>
        /// Promises for new export descriptors.
        /// </returns>
        /// <remarks>
        /// A provider will only be queried once for each unique export key.
        ///             The descriptor accessor can only be queried immediately if the descriptor being promised is an adapter, such as
        ///             <see cref="T:System.Lazy`1"/>; otherwise, dependencies should only be queried within execution of the function provided
        ///             to the <see cref="T:System.Composition.Hosting.Core.ExportDescriptorPromise"/>. The actual descriptors provided should not close over or reference any
        ///             aspect of the dependency/promise structure, as this should be able to be GC'ed.
        /// </remarks>
        public override IEnumerable<ExportDescriptorPromise> GetExportDescriptors(CompositionContract contract, DependencyAccessor descriptorAccessor)
        {
            if (contract.ContractType != typeof(ICompositionContext))
            {
                return ExportDescriptorProvider.NoExportDescriptors;
            }

            return new[]
                {
                    new ExportDescriptorPromise(
                        contract,
                        contract.ContractType.Name,
                        true,
                        ExportDescriptorProvider.NoDependencies,
                        dependencies => ExportDescriptor.Create(
                            (c, o) =>
                                {
                                    var instance = SystemCompositionContextBase.TryGetCompositionContext(c, createNewIfMissing: false) ?? this.compositionContainer;
                                    return instance;
                                },
                        ExportDescriptorProvider.NoMetadata))
               };
        }
    }
}


text:
<?php

namespace Magento\Config\Model\Config\Structure;

interface ElementInterface
{
    /**
     * Set element data
     *
     * @param array $data
     * @param string $scope
     * @return void
     */
    public function setData(array $data, $scope);

    /**
     * Retrieve element configuration
     *
     * @return array
     */
    public function getData();

    /**
     * Retrieve element id
     *
     * @return string
     */
    public function getId();

    /**
     * Retrieve element label
     *
     * @return string
     */
    public function getLabel();

    /**
     * Check whether element is visible
     *
     * @return bool
     */
    public function isVisible();

    /**
     * Retrieve arbitrary element attribute
     *
     * @param string $key
     * @return mixed
     */
    public function getAttribute($key);
}


text:
package charts;

import java.awt.Dimension;
import java.awt.Graphics2D;

public interface Drawable {

    public Dimension getDimension(Graphics2D graphics);

    public void draw(Graphics2D graphics);

}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.plugin.raptor.legacy;

import io.airlift.slice.XxHash64;
import io.prestosql.spi.Page;
import io.prestosql.spi.PrestoException;
import io.prestosql.spi.block.Block;
import io.prestosql.spi.connector.BucketFunction;
import io.prestosql.spi.type.Type;
import io.prestosql.spi.type.VarcharType;

import java.util.List;

import static com.google.common.base.Preconditions.checkArgument;
import static io.prestosql.spi.StandardErrorCode.NOT_SUPPORTED;
import static io.prestosql.spi.type.BigintType.BIGINT;
import static io.prestosql.spi.type.IntegerType.INTEGER;

public class RaptorBucketFunction
        implements BucketFunction
{
    private final HashFunction[] functions;
    private final int bucketCount;

    public RaptorBucketFunction(int bucketCount, List<Type> types)
    {
        checkArgument(bucketCount > 0, "bucketCount must be at least one");
        this.bucketCount = bucketCount;
        this.functions = types.stream()
                .map(RaptorBucketFunction::getHashFunction)
                .toArray(HashFunction[]::new);
    }

    @SuppressWarnings("NumericCastThatLosesPrecision")
    @Override
    public int getBucket(Page page, int position)
    {
        long hash = 0;
        for (int i = 0; i < page.getChannelCount(); i++) {
            Block block = page.getBlock(i);
            long value = functions[i].hash(block, position);
            hash = (hash * 31) + value;
        }
        int value = (int) (hash & Integer.MAX_VALUE);
        return value % bucketCount;
    }

    public static void validateBucketType(Type type)
    {
        getHashFunction(type);
    }

    private static HashFunction getHashFunction(Type type)
    {
        if (type.equals(BIGINT)) {
            return bigintHashFunction();
        }
        if (type.equals(INTEGER)) {
            return intHashFunction();
        }
        if (type instanceof VarcharType) {
            return varcharHashFunction();
        }
        throw new PrestoException(NOT_SUPPORTED, "Bucketing is supported for bigint, integer and varchar, not " + type.getDisplayName());
    }

    private static HashFunction bigintHashFunction()
    {
        return (block, position) -> XxHash64.hash(BIGINT.getLong(block, position));
    }

    private static HashFunction intHashFunction()
    {
        return (block, position) -> XxHash64.hash(INTEGER.getLong(block, position));
    }

    private static HashFunction varcharHashFunction()
    {
        return (block, position) -> XxHash64.hash(block.getSlice(position, 0, block.getSliceLength(position)));
    }

    private interface HashFunction
    {
        long hash(Block block, int position);
    }
}


text:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using System.Web;
using Humanizer;

namespace EmberJS.WebAPI
{
    public class EmberJsonMediaTypeFormatter : JsonMediaTypeFormatter
    {
        private int _maxDepth = 256;
        private JsonSerializerSettings _jsonSerializerSettings;
        public EmberJsonMediaTypeFormatter()
        {
            _jsonSerializerSettings = CreateDefaultSerializerSettings();
        }
        public override System.Threading.Tasks.Task WriteToStreamAsync(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext)
        {
            var root = GetRootFieldName(type, value);
            var obj = new ExpandoObject() as IDictionary<string, Object>;
            obj[root] = value;
            return base.WriteToStreamAsync(type, obj as object, writeStream, content, transportContext);
        }

        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return Task.FromResult(ReadFromStream(type, readStream, content, formatterLogger)); ;
        }

        private object ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var root = GetRootFieldName(type);
            var contentHeaders = content == null ? null : content.Headers;

            // If content length is 0 then return default value for this type
            if (contentHeaders != null && contentHeaders.ContentLength == 0)
                return GetDefaultValueForType(type);

            // Get the character encoding for the content
            var effectiveEncoding = SelectCharacterEncoding(contentHeaders);

            try
            {
                using (var reader = (new StreamReader(readStream, effectiveEncoding)))
                {
                    var json = reader.ReadToEnd();
                    var serializer = new EmberJsonSerializer();
                    var deserialized = serializer.Deserialize(json, root);
                    return deserialized.ToObject(type);
                }
            }
            catch (Exception e)
            {
                if (formatterLogger == null)
                {
                    throw;
                }
                formatterLogger.LogError(String.Empty, e);
                return GetDefaultValueForType(type);
            }
        }

        private string GetRootFieldName(Type type, dynamic value = null)
        {
            //get element type if array
            var isCollection = false;
            if (value != null && (value is IEnumerable || type.IsArray))
            {
                type = this.GetElementTypeFromCollection(value);
                isCollection = true;
            }

            var attrs = type.CustomAttributes.Where(x => x.AttributeType == typeof(Newtonsoft.Json.JsonObjectAttribute));

            if (attrs.Any())
            {
                var titles = attrs.First().NamedArguments.Where(arg => arg.MemberName == "Title")
                    .Select(arg => arg.TypedValue.Value.ToString()).ToList();

                if (titles.Any())
                {
                    if (isCollection)
                    {
                        return titles.First().Camelize().Pluralize();
                    }
                    return titles.First().Camelize();
                }
            }

            return isCollection ? type.Name.Camelize().Pluralize() : type.Name.Camelize();
        }

        private Type GetElementTypeFromCollection(dynamic collection)
        {
            var type = collection.GetType();
            // For arrays
            var elementType = type.GetElementType();
            if (elementType != null)
            {
                return elementType;
            }

            // For other collections
            var elementTypes = type.GetGenericArguments();
            if (elementTypes.Length > 0)
            {
                return elementTypes[0];
            }

            return type;
        }
    }
}


text:
import { EventEmitter, OnInit } from '@angular/core';
import { MediaEventsComponent } from '../media-events/media-events.component';
export declare class VideoAngularaComponent extends MediaEventsComponent implements OnInit {
    /**
     * The alt string to display when the video is not able to display.
     * @type {string}
     */
    alt: string;
    /**
     * Whether or not the video plays upon ready (default: {@code false}).
     * @type {boolean}
     */
    autoplay: boolean;
    /**
     * Whether or not the video has (default) controls (default: {@code false}).
     * @type {boolean}
     */
    controls: boolean;
    /**
     * The type of cross origin requests allowed (default: {@code null}).
     * @type {'anonymous'|'use-credentials'|null}
     */
    crossOrigin: 'anonymous' | 'use-credentials' | null;
    /**
     * The height of the video (default: {@code 0}).
     * @type {number}
     */
    height: number;
    /**
     * Whether or not the video is to loop (go back to the start automatically) after it is
     * finished playing (default: {@code false})
     * @type {boolean}
     */
    loop: boolean;
    /**
     * Whether or not the video is muted (default: {@code false}).
     * @type {boolean}
     */
    muted: boolean;
    /**
     * The type of preload for the video (default: {@code 'auto'}
     * @type {'none'|'metadata'|'auto'|''}
     */
    preload: 'none' | 'metadata' | 'auto' | '';
    /**
     * The URL to the poster frame for the video (default: {@code ''})
     * @type {string}
     */
    poster: string;
    /**
     * The source URL for the video (default: {@code ''})
     * @type {string}
     */
    src: string;
    /**
     * The source object for the video (default: {@code null})
     * @type {object}
     */
    srcObject: object;
    /**
     * Whether or not the video is streaming (default: {@code false}).
     * @type {boolean}
     */
    streaming: boolean;
    /**
     * The width of the video in pixels (default: {@code 0}).
     * @type {number}
     */
    width: number;
    ngModelChange: EventEmitter<{}>;
    videoObj: any;
    onChange: (_) => void;
    onTouched: () => void;
    private videoEl;
    ngOnInit(): void;
    writeValue(value: any): void;
    ngModel: object;
    video: HTMLVideoElement;
    value: any;
    registerOnChange(fn: any): void;
    registerOnTouched(fn: any): void;
    private constructVideoElementAttributes();
}


text:
class Customer < ActiveRecord::Base
	belongs_to :company
	belongs_to :user
end


text:
package com.vatril.fluffy.bot.fluffyaction;

import com.vatril.fluffy.bot.FluffyBot;

public class FluffyTemporaryAction extends FluffyActionListener {

	public FluffyTemporaryAction(FluffyBot fluffyBot, String prefix) {
		super(fluffyBot, prefix);
	}

	protected void remove(){
		getFluffyBot().removeTemporaryListener(this);
	}

}


text:
<?php

/**
 * 面试接口.
 */
namespace business\interviewService\service;
use business\common\BaseService;
use business\interFaces\interviewInterFace\IInterviewService;
use business\interviewService\model\Interview;
use business\interviewService\model\InterviewQuestionsPhoto;
use common\helper\Helper;
use yii\base\Exception;
use Yii;

class InterviewService  extends BaseService implements IInterviewService
{

    /**
     * 添加面试信息.
     * @param $data
     * @return mixed
     */
    public function addInterview($data)
    {

        $tran = Yii::$app->db->beginTransaction();
        try{
            //开启事物因为要操作多张表.
            //1.添加面试信息.
            $interview = new Interview();
            $data['Interview']['student_id'] = Yii::$app->session->get('student')['id'];
            $id = $interview->addInterview($data['Interview']);
            //2.添加面试题图片.
            //判断是否有上传面试题图片.
            if (!empty($data['InterviewQuestionsPhoto'])) {

                $session = Yii::$app->session->get('student');

                //组装数据.
                $data['InterviewQuestionsPhoto']['student_id'] = $session['id'];
                $data['InterviewQuestionsPhoto']['interview_id'] = $id;

                foreach ($data['InterviewQuestionsPhoto']['url'] as $K => $v) {

                    $interviewPhoto = new InterviewQuestionsPhoto();

                    //组装数据.
                    $arr = [
                        'url'          => $v,
                        'student_id'   => Yii::$app->session->get('student')['id'],
                        'interview_id' => $id,
                    ];

                    $interviewPhoto->addIntervicePhoto($arr);
                }
            }
            //3添加录音文件.

            //提交事物.
            $tran->commit();

            return true;

        } catch(Exception $e) {

            Yii::error($e->getMessage());
            //回滚事物.
            $tran->rollBack();
            return false;
        }
    }

    /**
     * 查询数据.
     * @return mixed
     */
    public function getInterviewAll($pageNow, $keyword= null)
    {
        try{
            $interview = new Interview();
            $res = $interview->getInterviewAll($pageNow, $keyword);

            foreach ($res as $k => $v) {
                $res[$k]['grade'] = $v['grade'] / $v['count'];
                $res[$k]['interview_time'] = date('Y-m-d',$v['grade']);
                $res[$k]['company_type'] = Helper::changeCompanyType($v['company_type']);
            }

            return $res;
        } catch (Exception $e) {
            Yii::error($e->getMessage());
            return false;
        }
    }

    /**
     * 获取分页总条数.
     * @return mixed
     */
    public function getInterviewCount($keyword = null)
    {
        try{
            $interview = new Interview();
            return $interview->getInterviewCount($keyword);
        }catch (Exception $e){
            Yii::error($e->getMessage());
            return false;
        }
    }

    /**
     * 根据id来查询.
     * @param $id
     * @return mixed
     */
    public function getInterviewById($id)
    {
        try{
            $interview = new Interview();
            $res = $interview->getInterviewById($id);

            //查询图片.
            $iq = new InterviewQuestionsPhoto();
            $arr = $iq->getPhotoById($id);

            foreach ($arr as $k => $v) {
                $arr[$k]['url'] = Yii::$app->params['upload_message']['visit_url'].$v['url'].'!small';
                $arr[$k]['path'] = Yii::$app->params['upload_message']['visit_url'].$v['url'];
            }

            if (!empty($res['sound_recording_file'])) {
                $res['sound_recording_file'] = Yii::$app->params['upload_message']['visit_url'].$res['sound_recording_file'];
            }

            //将查询出来的图片添加到数数组中.
            $res['photo'] = $arr;

            $res['company_type'] = Helper::changeCompanyType($res['company_type']);

            $res['interview_time'] = date('Y-m-d', $res['interview_time']);

            $res['is_written_examination'] = Helper::changeInterview($res['is_written_examination']);

            return $res;
        }catch (Exception $e){
            Yii::error($e->getMessage());
            return false;
        }
    }

    /**
     * 根据学科来查询面试信息.
     * @param $subject
     * @return mixed
     */
    public function getListBySubject($subject, $keyword, $pageNow)
    {
        try{
            $interviewArr = new Interview();
            $arr = $interviewArr->getListBySubject($subject, $keyword, $pageNow);
            return $arr;
        }catch (Exception $e){
            Yii::error($e->getMessage());
            return false;
        }
    }

    /**
     * 获取学科面试的总条数.
     * @param $subject
     * @return mixed
     */
    public function getInterviewCountBySubject($subject, $keyword)
    {
        try{
            $interview = new Interview();
            $res = $interview->getInterviewCountBySubject($subject, $keyword);
            return $res;
        }catch (Exception $e){
            Yii::error($e->getMessage());
            return false;
        }
    }
}


text:
<component name="libraryTable">
  <library name="Maven: io.dropwizard:dropwizard-configuration:0.9.1">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/io/dropwizard/dropwizard-configuration/0.9.1/dropwizard-configuration-0.9.1.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/io/dropwizard/dropwizard-configuration/0.9.1/dropwizard-configuration-0.9.1-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/io/dropwizard/dropwizard-configuration/0.9.1/dropwizard-configuration-0.9.1-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
package com.horstmeier.java.tftp.proxyserver;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;

/**
 * Created by jens on 17.08.13.
 */
public class EntityInputStream extends InputStream {

    private final HttpGet _httpGet;
    private final Logger log = Logger.getLogger(ProxyFileMapper.class);
    private InputStream _baseStream;

    public EntityInputStream(String address) throws IOException {
        DefaultHttpClient client = new DefaultHttpClient();
        _httpGet = new HttpGet(address);

        HttpResponse response = client.execute(_httpGet);
        try {
            log.info("Response : " + response.getStatusLine());
            HttpEntity entity = response.getEntity();
            _baseStream = entity.getContent();
        } catch (Exception e) {
            _baseStream = null;
        }
    }

    @Override
    public int read() throws IOException {
        if (_baseStream == null)
            throw new IOException("Failed to read from server");
        return _baseStream.read();
    }

    @Override
    protected void finalize() throws Throwable {
        if (_baseStream != null) {
            _baseStream.close();
        }
        if (_httpGet != null) {
            _httpGet.releaseConnection();
        }
        super.finalize();
    }
}


text:
**NOTE**: in these examples, `x` is always "whatever precedes this element". It can be another element, or nothing at all. It is the placeholder for whatever comes before this element. `z` is always "whatever comes after this element". It can also be another element, or nothing at all (in which case it will be a complete state rather than a transition to anything). `y` (and `a`, `b`, ...) represents an element(s) that is(are) the target of the modifier.

### Optional (`xy?z`)

`x` transitions to a state, which can transition to `z` immediately, or if `y` is next, will transition to another state which will transition to `z` immediately.

Example: /ab?c/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: '1' }))
    .withState('1', new State()
        .withTransition('b', { next: '2' })
        .withTransition('c', { next: DONE }))
    .withState('2', new State()
        .withTransition('c', { next: DONE }));
```

This indicates that an Optional generates a State with 2 transitions, one for the target element, and one for the element following the Optional.

```javascript
class Optional {
    ...
    transform(stateMachine, currentStateId, getNextElement) {
        // get next id and next element
        let [sm, nextId] = stateMachine.nextStateId();
        const nextElement = getNextElement();
        // get current state, create next state
        let currentState = sm.states.get(currentStateId) || new State();
        const nextState = new State();
        if (typeof this.element === 'string') {
            // add transition from this state to next state via this.element, add next state
            sm = sm
                .withState(currentStateId, currentState = currentState
                    .withTransition(this.element, { next: nextId }));
        } else {
            // transform state machine according to this.element for the current state, add next state
            sm = this.element.transform(sm, currentStateId, getNextElement);
        }
        // add next state
        sm = sm.withState(nextId, nextState);
        // apply next element's transform to both the current state and the next state
        sm = nextElement.transform(sm, currentStateId, getNextElement);
        return nextElement.transform(sm, nextId, getNextElement);
    }
    ...
}
```

### Kleene star (`xy*z`)

`x` transitions to a state, which can transition to `z` immediately, or if `y` is next, will loop back to the current state.

Example: /ab*c/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: '1' }))
    .withState('1', new State()
        .withTransition('b', { next: '1' })
        .withTransition('c', { next: DONE }));
```

### Kleene plus (`xy+z`)

`x` transitions to a state, which can only transition to the next state via `y`, after which it can transition to `z` immediately, or if there are more `y`'s, will loop back to the second state.

Example: /ab+c/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: '1' }))
    .withState('1', new State()
        .withTransition('b', { next: '2' }))
    .withState('2', new State()
        .withTransition('b', { next: '2' })
        .withTransition('c', { next: DONE }));
```

### Fixed boundary (`xy{a}z`)

`x` transitions to a state, which can only transition to further states `a` times, all via `y`, after which it transitions to `z`.

Example: /ab{3}c/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: '1' }))
    .withState('1', new State()
        .withTransition('b', { next: '2' }))
    .withState('2', new State()
        .withTransition('b', { next: '3' }))
    .withState('3', new State()
        .withTransition('b', { next: '4' }))
    .withState('4', new State()
        .withTransition('c', { next: DONE }));
```

### Bounded minimum (`xy{a,}z`)

`x` transitions to a state, which can only transition to further states `a` times, all via `y`, after which it can loop back via `y`, or transition to `z`.

Example: /ab{3,}c/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: '1' }))
    .withState('1', new State()
        .withTransition('b', { next: '2' }))
    .withState('2', new State()
        .withTransition('b', { next: '3' }))
    .withState('3', new State()
        .withTransition('b', { next: '4' }))
    .withState('4', new State()
        .withTransition('b', { next: '4' })
        .withTransition('c', { next: DONE }));
```

### Fixed range (`xy{a,b}z`)

`x` transitions to a state, which can only transition to further states `a` times, all via `y`, after which there are `b-a` more states which can all transition directly to `z` or to the next state via `y`.

Example: /ab{2,4}c/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: '1' }))
    .withState('1', new State()
        .withTransition('b', { next: '2' }))
    .withState('2', new State()
        .withTransition('b', { next: '3' }))
    .withState('3', new State()
        .withTransition('b', { next: '4' })
        .withTransition('c', { next: DONE }))
    .withState('4', new State()
        .withTransition('b', { next: '5' })
        .withTransition('c', { next: DONE }))
    .withState('5', new State()
        .withTransition('c', { next: DONE }));
```

### Enumerated sequence (`x(y|a|...n...b)z`)

`x` transitions to a state, which can transition to one of `n` states via the first transition of one of `n` choice subsequences. Upon transitioning to one of the subsequences, that subsequence must be completed, then transition to `z`.

Example: /a(bc|def|gh)i/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: '1' }))
    .withState('1', new State()
        .withTransition('b', { next: '2' })
        .withTransition('d', { next: '3' })
        .withTransition('g', { next: '5' }))
    .withState('2', new State()
        .withTransition('c', { next: '6' }))
    .withState('3', new State()
        .withTransition('e', { next: '4' }))
    .withState('4', new State()
        .withTransition('f', { next: '6' }))
    .withState('5', new State()
        .withTransition('h', { next: '6' }))
    .withState('6', new State()
        .withTransition('i', { next: DONE }))
```

### Normal sequence (`x(y)z`)

`x` transitions to a state, which transitions via `y`, which completes, then transitions to `z`.

Example: /a(bc)d/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: '1' }))
    .withState('1', new State()
        .withTransition('b', { next: '2' }))
    .withState('2', new State()
        .withTransition('c', { next: '3' }))
    .withState('3', new State()
        .withTransition('d', { next: DONE }))
```

### Character class (`x[y]z`)

`x` transitions to a state, which transitions to the next state via only one of the characters in `y`, which then transitions to `z`.

Example: /a[bc]d/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: '1' }))
    .withState('1', new State()
        .withTransition('b', { next: '2' })
        .withTransition('c', { next: '2' }))
    .withState('2', new State()
        .withTransition('d', { next: DONE }));
```

### Inverted character class (`x[^y]z`)

`x` transitions to a state, which transitions to the next state via any character *except* one of the characters in `y`, which then transitions to `z`.

Example: /a[^bc]d/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: '1' }))
    .withState('1', new State()
        .withTransition('b', { next: FAIL })
        .withTransition('c', { next: FAIL })
        .withDefaultTransition({ next: '2' }))
    .withState('2', new State()
        .withTransition('d', { next: DONE }));
```

### Wildcard (`x.z`)

`x` transitions to a state, which transitions to the next state via *any* character, which then transitions to `z`.

Example: /a.b/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: '1' }))
    .withState('1', new State()
        .withDefaultTransition({ next: '2' }))
    .withState('2', new State()
        .withTransition('b', { next: DONE }));
```

### Start of string (`^yz`)

The start state transitions to the next state only via `y`, which then transitions to `z`. The significance here is that the preceding state must be the start state, and cannot be any other state, i.e. `y` must be the start of the input.

Example: /^a/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: DONE }));
```

## End of string (`xy$`)

`x` transitions to a state, which transitions to the next state via `y`, which must transition to the DONE state. The significance here is that the next state must be the DONE state, and cannot be any other state, i.e. `y` must be the end of the input.

Example: /a$/

```javascript
const stateMachine = new StateMachine('start')
    .withState('start', new State()
        .withTransition('a', { next: DONE }));
```

**NOTE**: The above two state machines are exactly the same even though the regexes imply different semantics. The issue is that there is no information saying anything about what happens after the regex (in the first case) or before the regex (in the second case). Thinking about it pragmatically, these regexes will serve the purpose of splitting up a source code input string into tokens, which means that they might start at any point in the input string. The difference here is that during the generation process, these two elements will cause the generated states to be placed at the start and finish of the full state machine, because a lexer takes several regexes and combines them into one state machine. The rest of the regexes branch off of a common "base" state because they do not specify the start character, and they will branch back to that "base" state because they do not specify the end character. This will become more clear once we reach the actual lexer logic.


text:
/**
 * @file   AccelerationStructure.cpp
 * @author Sebastian Maisch <sebastian.maisch@googlemail.com>
 * @date   2020.11.21
 *
 * @brief  Implementation of the acceleration structure class.
 */

#include "gfx/vk/rt/AccelerationStructure.h"
#include "gfx/vk/buffers/DeviceBuffer.h"
#include "gfx/vk/LogicalDevice.h"
#include "gfx/vk/wrappers/CommandBuffer.h"
#include "gfx/vk/wrappers/DescriptorSet.h"

namespace vkfw_core::gfx::rt {

    AccelerationStructure::AccelerationStructure(vkfw_core::gfx::LogicalDevice* device, std::string_view name,
                                                 vk::AccelerationStructureTypeKHR type,
                                                 vk::BuildAccelerationStructureFlagsKHR flags)
        : VulkanObjectPrivateWrapper{device->GetHandle(), name, vk::UniqueAccelerationStructureKHR{}}
        , m_device{device}
        , m_type{type}
        , m_flags{flags}
        , m_buildBarrier{device}
    {
    }

    AccelerationStructure::AccelerationStructure(AccelerationStructure&& rhs) noexcept = default;

    AccelerationStructure& AccelerationStructure::operator=(AccelerationStructure&& rhs) noexcept = default;

    AccelerationStructure::~AccelerationStructure() {}

    void AccelerationStructure::AddGeometry(const vk::AccelerationStructureGeometryKHR& geometry,
                                            const vk::AccelerationStructureBuildRangeInfoKHR& buildRange)
    {
        m_geometries.emplace_back(geometry);
        m_buildRanges.emplace_back(buildRange);
    }

    void AccelerationStructure::BuildAccelerationStructure(CommandBuffer& cmdBuffer)
    {
        vk::AccelerationStructureBuildGeometryInfoKHR asBuildInfo{ m_type, m_flags, vk::BuildAccelerationStructureModeKHR::eBuild,
            nullptr, nullptr, static_cast<std::uint32_t>(m_geometries.size()), m_geometries.data() };

        std::vector<std::uint32_t> asPrimitiveCounts;
        asPrimitiveCounts.reserve(m_geometries.size());
        for (const auto& buildRange : m_buildRanges) {
            asPrimitiveCounts.push_back(buildRange.primitiveCount);
        }

        m_memoryRequirements = m_device->GetHandle().getAccelerationStructureBuildSizesKHR(
            vk::AccelerationStructureBuildTypeKHR::eDevice, asBuildInfo, asPrimitiveCounts);

        CreateAccelerationStructure(m_buildBarrier);

        m_scratchBuffer = CreateAccelerationStructureScratchBuffer();

        asBuildInfo.dstAccelerationStructure = GetHandle();
        asBuildInfo.scratchData = m_device->CalculateASScratchBufferBufferAlignment(
            m_scratchBuffer
                ->GetDeviceAddress(vk::AccessFlagBits2KHR::eAccelerationStructureRead
                                       | vk::AccessFlagBits2KHR::eAccelerationStructureWrite,
                                   vk::PipelineStageFlagBits2KHR::eAccelerationStructureBuild, m_buildBarrier)
                .deviceAddress);
        m_buildBarrier.Record(cmdBuffer);

        cmdBuffer.GetHandle().buildAccelerationStructuresKHR(asBuildInfo, m_buildRanges.data());
    }

    void AccelerationStructure::FinalizeBuild() { m_scratchBuffer = nullptr; }

    vk::DeviceAddress AccelerationStructure::GetAddressHandle(vk::AccessFlags2KHR access,
                                                              vk::PipelineStageFlags2KHR pipelineStages,
                                                              PipelineBarrier& barrier) const
    {
        m_buffer->AccessBarrier(false, access, pipelineStages, barrier);
        return m_handle;
    }

    void AccelerationStructure::CreateAccelerationStructure(PipelineBarrier& barrier)
    {
        m_buffer = std::make_unique<vkfw_core::gfx::DeviceBuffer>(
            m_device, fmt::format("ASBuffer:{}", GetName()),
            vk::BufferUsageFlagBits::eAccelerationStructureStorageKHR | vk::BufferUsageFlagBits::eShaderDeviceAddress);
        m_buffer->InitializeBuffer(m_memoryRequirements.accelerationStructureSize);

        vk::AccelerationStructureCreateInfoKHR asCreateInfo{
            {},
            m_buffer->GetBuffer(false, vk::AccessFlagBits2KHR::eAccelerationStructureWrite,
                                vk::PipelineStageFlagBits2KHR::eAccelerationStructureBuild, barrier),
            0,
            m_memoryRequirements.accelerationStructureSize,
            m_type};

        SetHandle(m_device->GetHandle(), m_device->GetHandle().createAccelerationStructureKHRUnique(asCreateInfo));

        vk::AccelerationStructureDeviceAddressInfoKHR asDeviceAddressInfo{GetHandle()};
        m_handle = m_device->GetHandle().getAccelerationStructureAddressKHR(asDeviceAddressInfo);
    }

    void AccelerationStructure::AccessBarrier(vk::AccessFlags2KHR access, vk::PipelineStageFlags2KHR pipelineStages,
                                              PipelineBarrier& barrier) const
    {
        m_buffer->AccessBarrier(false, access, pipelineStages, barrier);
    }

    std::unique_ptr<vkfw_core::gfx::DeviceBuffer> AccelerationStructure::CreateAccelerationStructureScratchBuffer() const
    {
        std::unique_ptr<vkfw_core::gfx::DeviceBuffer> scratchBuffer = std::make_unique<vkfw_core::gfx::DeviceBuffer>(
            m_device, fmt::format("ASScratchBuffer:{}", GetName()),
            vk::BufferUsageFlagBits::eStorageBuffer | vk::BufferUsageFlagBits::eShaderDeviceAddress);
        scratchBuffer->InitializeBuffer(
            m_device->CalculateASScratchBufferBufferAlignment(m_memoryRequirements.buildScratchSize));

        return scratchBuffer;
    }

}


text:
#ifndef DiMemoryTrace_h__
#define DiMemoryTrace_h__

#include "MiscDefines.h"

namespace Demi
{
    class DI_MISC_API DiMemoryTrace
    {
    public:

        DiMemoryTrace();

        ~DiMemoryTrace();

    public:
        struct AllocInfo
        {
            uint32    uiIndex;
            uint32    uiSize;
        };

        typedef DiMap<uint64, AllocInfo> AllocInfoList;
        typedef AllocInfoList::iterator  AllocInfoListIter;

        static DiMemoryTrace& GetInstance()
        {
            static DiMemoryTrace sMemoryTrace;
            return sMemoryTrace;
        }

    public:

        void             Alloc(void* pMemory, size_t stSize, const char* pszFileName, uint32 uiLine);

        void             Free(void* pMemory);

    private:
        uint64           AddresToHash(void* pMemory);

        void             Init();

        void             Close();

        void             WriteAllocInfo(long ptr, size_t stSize, const char* pszFileName, uint32 uiLine);

        void             WriteFreeInfo(long ptr, uint32 uiAllocIndex);

        void             SaveMemoryLeak();

    private:
        uint32           mAllocIndex;

        AllocInfoList    mAllocInfoList;

        DiOfstream       mMemoryLeakFile;

        DiOfstream       mMemoryTraceFile;
    };

    inline uint64 DiMemoryTrace::AddresToHash(void* pMemory)
    {
        return (uint64)(reinterpret_cast<size_t>(pMemory));
    }

}

#endif


text:
package com.dremio.exec.store.hive.exec;

import java.io.IOException;

import com.dremio.exec.catalog.StoragePluginId;
import com.dremio.exec.store.StoragePluginResolver;
import com.dremio.exec.store.SupportsPF4JStoragePlugin;
import com.dremio.exec.store.hive.HiveCommonUtilities;
import com.dremio.exec.store.hive.StoragePluginCreator;
import com.dremio.exec.store.hive.proxy.HiveProxiedOrcScanFilter;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.ResolvableDeserializer;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

/**
 * Helper class for deserializing an OrcScanFilter that delegates to a OrcScanFilter
 * that is in a separate classloader.
 */
public class HiveProxyingOrcScanFilterDeserializer extends StdDeserializer<HiveProxyingOrcScanFilter> {

  public HiveProxyingOrcScanFilterDeserializer() {
    this(null);
  }

  public HiveProxyingOrcScanFilterDeserializer(Class<?> clazz) {
    super(clazz);
  }

  @Override
  public HiveProxyingOrcScanFilter deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    // TODO: Optimize performance as described in https://dremio.atlassian.net/browse/DX-17732
    final JsonNode node = jsonParser.getCodec().readTree(jsonParser);

    final StoragePluginId pluginId = HiveCommonUtilities.deserialize(jsonParser, deserializationContext,
      node.get(HiveProxyingOrcScanFilter.JSON_PROP_PLUGINID), StoragePluginId.class);

    // get subscan class type from plugin.
    final StoragePluginResolver storagePluginResolver = (StoragePluginResolver) deserializationContext
      .findInjectableValue(StoragePluginResolver.class.getName(), null, null);
    final SupportsPF4JStoragePlugin pf4JStoragePlugin = storagePluginResolver.getSource(pluginId);
    final StoragePluginCreator.PF4JStoragePlugin plugin = pf4JStoragePlugin.getPF4JStoragePlugin();
    final Class<? extends HiveProxiedOrcScanFilter> scanClazz = plugin.getOrcScanFilterClass();

    final JavaType scanType = deserializationContext.getTypeFactory().constructType(scanClazz);
    final BeanDescription description = deserializationContext.getConfig().introspect(scanType);
    final JsonDeserializer<Object> orcScanFilterDeserializer = deserializationContext.getFactory().createBeanDeserializer(
      deserializationContext, scanType, description);

    if (orcScanFilterDeserializer instanceof ResolvableDeserializer) {
      ((ResolvableDeserializer) orcScanFilterDeserializer).resolve(deserializationContext);
    }

    final JsonParser movedParser = jsonParser.getCodec().treeAsTokens(node.get(HiveProxyingOrcScanFilter.JSON_PROP_WRAPPEDHIVEORCSCANFILTER));
    deserializationContext.getConfig().initialize(movedParser);

    if (movedParser.getCurrentToken() == null) {
      movedParser.nextToken();
    }

    final HiveProxiedOrcScanFilter orcScanFilter = (HiveProxiedOrcScanFilter) orcScanFilterDeserializer.deserialize(movedParser, deserializationContext);
    return new HiveProxyingOrcScanFilter(pluginId, orcScanFilter);
  }
}


text:
@interface NSArrayExtensionsTest : XCTestCase {
  NSArray * sample;
}

@end

@implementation NSArrayExtensionsTest

- (void)setUp {
  [super setUp];
  sample = @[@1, @2, @3, @4];
}

- (void)tearDown {
  [super tearDown];
}

#pragma mark map

- (void)testMap {
  NSArray * result = [sample ce_map:^(NSNumber *item) {
    return [item stringValue];
  }];
  XCTAssertTrue([[result objectAtIndex:0] isEqualToString:@"1"], @"");
  XCTAssertTrue([[result objectAtIndex:1] isEqualToString:@"2"], @"");
}

- (void)testSelect {
  NSArray * result = [sample ce_select:^(NSNumber *item) {
    return (BOOL) ([item intValue] == 1);
  }];
  XCTAssertTrue(result.count == (NSUInteger)1, @"");
  XCTAssertTrue([[result objectAtIndex:0] intValue] == 1, @"");
}

- (void)testReject {
  NSArray * result = [sample ce_reject:^(NSNumber *item) {
    return (BOOL) ([item intValue] % 2 == 0);
  }];
  XCTAssertTrue(result.count == (NSUInteger)2, @"");
  XCTAssertTrue([[result objectAtIndex:0] intValue] == 1, @"");
  XCTAssertTrue([[result objectAtIndex:1] intValue] == 3, @"");
}

@end


text:
namespace Humanizer.Localisation.Formatters
{
    internal class FrenchFormatter : DefaultFormatter
    {
        private const string DualPostfix = "_Dual";

        public FrenchFormatter(string localeCode)
            : base(localeCode)
        {
        }

        protected override string GetResourceKey(string resourceKey, int number)
        {
            if (number == 2 && (resourceKey == "DateHumanize_MultipleDaysAgo" || resourceKey == "DateHumanize_MultipleDaysFromNow"))
            {
                return resourceKey + DualPostfix;
            }

            if (number == 0 && resourceKey.StartsWith("TimeSpanHumanize_Multiple"))
            {
                return resourceKey + "_Singular";
            }

            return resourceKey;
        }
    }
}


text:
package com.authlete.jaxrs.server.ad.dto;

/**
 * A class representing a request to
 * /api/authenticate/async API of
 * Authlete CIBA authentication device simulator.
 *
 * @see Authlete CIBA authentication
 *      device simulator
 *
 * @see
 *      /api/authenticate/async API
 *
 * @author Hideki Ikeda
 */
public class AsyncAuthenticationRequest extends BaseAuthenticationRequest<AsyncAuthenticationRequest>
{
    private static final long serialVersionUID = 1L;

    private String state;

    /**
     * Get the value of {@code state} request parameter.
     *
     * @return
     *         The value of {@code state} request parameter
     */
    public String getState()
    {
        return state;
    }

    /**
     * Set the value of {@code state} request parameter.
     *
     *

     * Arbitrary data can be set to this request parameter and the data will be
     * sent to the callback endpoint with the result of end-user authentication
     * and authorization.
     *

     *
     * @param state
     *         Arbitrary data that will be sent to the callback endpoint with the
     *         result of end-user authentication and authorization.
     *
     * @return
     *         {@code this} object.
     */
    public AsyncAuthenticationRequest setState(String state)
    {
        this.state = state;

        return this;
    }
}


text:
package network::fortinet::fortiadc::snmp::plugin;

use strict;
use warnings;
use base qw(centreon::plugins::script_snmp);

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $self->{modes} = {
        'cpu'                  => 'network::fortinet::fortiadc::snmp::mode::cpu',
        'hardware'             => 'network::fortinet::fortiadc::snmp::mode::hardware',
        'interfaces'           => 'network::fortinet::fortiadc::snmp::mode::interfaces',
        'list-interfaces'      => 'snmp_standard::mode::listinterfaces',
        'list-virtual-servers' => 'network::fortinet::fortiadc::snmp::mode::listvirtualservers',
        'memory'               => 'network::fortinet::fortiadc::snmp::mode::memory',
        'security'             => 'network::fortinet::fortiadc::snmp::mode::security',
        'uptime'               => 'network::fortinet::fortiadc::snmp::mode::uptime',
        'virtual-servers'      => 'network::fortinet::fortiadc::snmp::mode::virtualservers'
    };

    return $self;
}

1;

__END__

=head1 PLUGIN DESCRIPTION

Check Fortinet FortiADC in SNMP.

=cut


text:
package jp.sourceforge.ea2ddl.dao.exentity;

/**
 * The entity of t_glossary.
 * <p>
 * You can implement your original methods here.
 * This class remains when re-generating.
 * </p>
 * @author DBFlute(AutoGenerator)
 */
public class TGlossary extends jp.sourceforge.ea2ddl.dao.bsentity.BsTGlossary {

    /** Serial version UID. (Default) */
    private static final long serialVersionUID = 1L;
}


text:
namespace TfsWorkbench.NotePadUI.Models
{
    public interface ISelectable
    {
        bool IsSelected { get; set; }
    }
}


text:
<?php

/**
 * @see Zend_Feed_Writer_Extension_RendererAbstract
 */
// require_once 'Zend/Feed/Writer/Extension/RendererAbstract.php';

/**
 * @category   Zend
 * @package    Zend_Feed_Writer
 * @copyright  Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Feed_Writer_Extension_DublinCore_Renderer_Feed
    extends Zend_Feed_Writer_Extension_RendererAbstract
{

    /**
     * Set to TRUE if a rendering method actually renders something. This
     * is used to prevent premature appending of a XML namespace declaration
     * until an element which requires it is actually appended.
     *
     * @var bool
     */
    protected $_called = false;

    /**
     * Render feed
     *
     * @return void
     */
    public function render()
    {
        if (strtolower($this->getType()) == 'atom') {
            return;
        }
        $this->_setAuthors($this->_dom, $this->_base);
        if ($this->_called) {
            $this->_appendNamespaces();
        }
    }

    /**
     * Append namespaces to feed element
     *
     * @return void
     */
    protected function _appendNamespaces()
    {
        $this->getRootElement()->setAttribute('xmlns:dc',
            'http://purl.org/dc/elements/1.1/');
    }

    /**
     * Set feed authors
     *
     * @param  DOMDocument $dom
     * @param  DOMElement $root
     * @return void
     */
    protected function _setAuthors(DOMDocument $dom, DOMElement $root)
    {
        $authors = $this->getDataContainer()->getAuthors();
        if (!$authors || empty($authors)) {
            return;
        }
        foreach ($authors as $data) {
            $author = $this->_dom->createElement('dc:creator');
            if (array_key_exists('name', $data)) {
                $text = $dom->createTextNode($data['name']);
                $author->appendChild($text);
                $root->appendChild($author);
            }
        }
        $this->_called = true;
    }
}