text:
Imports DevExpress.XtraEditors
Imports System.Reflection
Imports System.Collections.Generic
Imports DevExpress.XtraGrid.Views.Grid
Imports EIDSS.model.Resources

Public Class AggregateHelper
    Private m_MonthList As DataTable
    Private m_QuarterList As DataTable
    Private m_WeekList As DataTable
    Private ReadOnly m_MinYear As Integer = 1900
    Private ReadOnly m_Owner As BaseForm
    Private cbYear As ComboBoxEdit
    Private cbQuarter As LookUpEdit
    Private cbMonth As LookUpEdit
    Private datDay As DateEdit
    Private cbWeek As LookUpEdit
    Private cbCountry As LookUpEdit
    Private cbRegion As LookUpEdit
    Private cbRayon As LookUpEdit
    Private cbSettlement As LookUpEdit
    Private eventManager As DataEventManager
    Private Sub InitDataEventManager(ByVal owner As BaseForm)
        'Dim fi As FieldInfo = owner.GetType().GetField("eventManager", BindingFlags.Public Or BindingFlags.Instance)
        'eventManager = CType(fi.GetValue(owner), DataEventManager)
        eventManager = owner.eventManager
    End Sub
    Public Sub New(ByVal owner As BaseForm, ByVal acbYear As ComboBoxEdit, ByVal acbQuarter As LookUpEdit, _
                        ByVal acbMonth As LookUpEdit, ByVal adatDay As DateEdit, ByVal acbWeek As LookUpEdit, _
                        ByVal acbCountry As LookUpEdit, ByVal acbRegion As LookUpEdit, _
                        ByVal acbRayon As LookUpEdit, ByVal acbSettlement As LookUpEdit)
        m_Owner = owner
        InitDataEventManager(owner)
        Init(acbYear, acbQuarter, acbMonth, adatDay, acbWeek, acbCountry, acbRegion, acbRayon, acbSettlement)
    End Sub
    Public Sub New(ByVal owner As BaseForm, ByVal aMinYear As Integer, ByVal acbYear As ComboBoxEdit, ByVal acbQuarter As LookUpEdit, _
                        ByVal acbMonth As LookUpEdit, ByVal adatDay As DateEdit, ByVal acbWeek As LookUpEdit, _
                        ByVal acbCountry As LookUpEdit, ByVal acbRegion As LookUpEdit, _
                        ByVal acbRayon As LookUpEdit, ByVal acbSettlement As LookUpEdit)
        If aMinYear > 0 AndAlso aMinYear <= DateTime.Today.Year Then
            m_MinYear = aMinYear
        End If
        m_Owner = owner
        InitDataEventManager(owner)
        Init(acbYear, acbQuarter, acbMonth, adatDay, acbWeek, acbCountry, acbRegion, acbRayon, acbSettlement)
    End Sub
    Private Sub Init(ByVal acbYear As ComboBoxEdit, ByVal acbQuarter As LookUpEdit, _
                        ByVal acbMonth As LookUpEdit, ByVal adatDay As DateEdit, ByVal acbWeek As LookUpEdit, _
                        ByVal acbCountry As LookUpEdit, ByVal acbRegion As LookUpEdit, _
                        ByVal acbRayon As LookUpEdit, ByVal acbSettlement As LookUpEdit)
        cbYear = acbYear
        cbQuarter = acbQuarter
        cbMonth = acbMonth
        datDay = adatDay
        cbWeek = acbWeek
        cbCountry = acbCountry
        cbRegion = acbRegion
        cbRayon = acbRayon
        cbSettlement = acbSettlement
        m_WeekList = CreatePeriodTable()
        m_MonthList = CreatePeriodTable()
        m_QuarterList = CreatePeriodTable()
    End Sub
    Public Sub BindPeriodFileds()
        eventManager.RemoveDataHandler(AggregateHeader_DB.TableAggregateHeader + ".YearForAggr")
        eventManager.RemoveDataHandler(AggregateHeader_DB.TableAggregateHeader + ".QuarterForAggr")
        eventManager.RemoveDataHandler(AggregateHeader_DB.TableAggregateHeader + ".MonthForAggr")
        eventManager.RemoveDataHandler(AggregateHeader_DB.TableAggregateHeader + ".WeekForAggr")
        eventManager.RemoveDataHandler(AggregateHeader_DB.TableAggregateHeader + ".DayForAggr")
        cbYear.DataBindings.Clear()
        cbYear.DataBindings.Add("EditValue", baseDataset, AggregateHeader_DB.TableAggregateHeader + ".YearForAggr", True, DataSourceUpdateMode.OnPropertyChanged)
        Core.LookupBinder.AddBinding(cbQuarter, baseDataset, AggregateHeader_DB.TableAggregateHeader + ".QuarterForAggr", False)
        Core.LookupBinder.AddBinding(cbMonth, baseDataset, AggregateHeader_DB.TableAggregateHeader + ".MonthForAggr", False)
        Core.LookupBinder.AddBinding(cbWeek, baseDataset, AggregateHeader_DB.TableAggregateHeader + ".WeekForAggr", False)
        Core.LookupBinder.BindDateEdit(datDay, baseDataset, AggregateHeader_DB.TableAggregateHeader + ".DayForAggr")

        eventManager.AttachDataHandler(AggregateHeader_DB.TableAggregateHeader + ".YearForAggr", AddressOf Year_Changed)
        eventManager.AttachDataHandler(AggregateHeader_DB.TableAggregateHeader + ".QuarterForAggr", AddressOf Quarter_Changed)
        eventManager.AttachDataHandler(AggregateHeader_DB.TableAggregateHeader + ".MonthForAggr", AddressOf Month_Changed)
        eventManager.AttachDataHandler(AggregateHeader_DB.TableAggregateHeader + ".WeekForAggr", AddressOf Week_Changed)
        eventManager.AttachDataHandler(AggregateHeader_DB.TableAggregateHeader + ".DayForAggr", AddressOf Day_Changed)
    End Sub
    Public Sub BindAreaFields()
        eventManager.RemoveDataHandler(AggregateHeader_DB.TableAggregateHeader + ".idfsCountry")
        eventManager.RemoveDataHandler(AggregateHeader_DB.TableAggregateHeader + ".idfsRegion")
        eventManager.RemoveDataHandler(AggregateHeader_DB.TableAggregateHeader + ".idfsRayon")
        eventManager.RemoveDataHandler(AggregateHeader_DB.TableAggregateHeader + ".idfsSettlement")
        Dim isHumanAggregateCase As Boolean = (CaseType = AggregateCaseType.AggregateCase)
        Core.LookupBinder.BindCountryLookup(cbCountry, baseDataset, AggregateHeader_DB.TableAggregateHeader + ".idfsCountry")
        Core.LookupBinder.BindRegionLookup(cbRegion, baseDataset, AggregateHeader_DB.TableAggregateHeader + ".idfsRegion", isHumanAggregateCase)
        Core.LookupBinder.BindRayonLookup(cbRayon, baseDataset, AggregateHeader_DB.TableAggregateHeader + ".idfsRayon", isHumanAggregateCase)
        Core.LookupBinder.BindSettlementLookup(cbSettlement, baseDataset, AggregateHeader_DB.TableAggregateHeader + ".idfsSettlement", isHumanAggregateCase)

        eventManager.AttachDataHandler(AggregateHeader_DB.TableAggregateHeader + ".idfsCountry", AddressOf Country_Changed)
        eventManager.AttachDataHandler(AggregateHeader_DB.TableAggregateHeader + ".idfsRegion", AddressOf Region_Changed)
        eventManager.AttachDataHandler(AggregateHeader_DB.TableAggregateHeader + ".idfsRayon", AddressOf Rayon_Changed)
        eventManager.AttachDataHandler(AggregateHeader_DB.TableAggregateHeader + ".idfsSettlement", AddressOf Settlement_Changed)
    End Sub
    Private Sub Year_Changed(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs)
        SetQuarter()
        SetMonth()
        SetWeek()
        If CurrentYear > 0 AndAlso CurrentTimeInterval = StatisticPeriodType.Year Then
            e.Row("datStartDate") = New DateTime(CurrentYear, 1, 1)
            e.Row("datFinishDate") = New DateTime(CurrentYear, 12, 31)
            m_CurrentTimeUnit = CurrentYear
        End If
        eventManager.Cascade(AggregateHeader_DB.TableAggregateHeader + ".QuarterForAggr")
        eventManager.Cascade(AggregateHeader_DB.TableAggregateHeader + ".MonthForAggr")
        eventManager.Cascade(AggregateHeader_DB.TableAggregateHeader + ".WeekForAggr")
        eventManager.Cascade(AggregateHeader_DB.TableAggregateHeader + ".DayForAggr")
    End Sub
    Private Sub Quarter_Changed(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs)
        If CurrentTimeInterval = StatisticPeriodType.Quarter AndAlso CurrentQuarter > 0 Then
            Dim r As DataRow = FindQuarter(CurrentQuarter)
            e.Row("datStartDate") = r("StartDay")
            e.Row("datFinishDate") = r("FinishDay")
            m_CurrentTimeUnit = CurrentQuarter
        End If

    End Sub
    Private Sub Month_Changed(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs)
        SetDay()
        If CurrentTimeInterval = StatisticPeriodType.Day Then
            If CurrentMonth > 0 Then
                Dim r As DataRow = FindMonth(CurrentMonth)
                datDay.Properties.MinValue = CDate(r("StartDay"))
                datDay.Properties.MaxValue = CDate(r("FinishDay"))
                If Not Utils.IsEmpty(CurrentDay) Then
                    Dim newDay As Date = CDate(CurrentDay)
                    If newDay.CompareTo(r("StartDay")) < 0 OrElse newDay.CompareTo(r("FinishDay")) > 0 Then
                        CurrentDay = DBNull.Value
                    End If
                End If
            Else
                datDay.Properties.MinValue = Date.MinValue
                datDay.Properties.MaxValue = Date.MaxValue
                CurrentDay = DBNull.Value
            End If
            If Date.Today.CompareTo(datDay.Properties.MinValue) < 0 OrElse Date.Today.CompareTo(datDay.Properties.MaxValue) > 0 Then
                datDay.Properties.ShowToday = False
            Else
                datDay.Properties.ShowToday = True
            End If
        End If
        If CurrentTimeInterval = StatisticPeriodType.Month AndAlso CurrentMonth > 0 Then
            Dim r As DataRow = FindMonth(CurrentMonth)
            e.Row("datStartDate") = r("StartDay")
            e.Row("datFinishDate") = r("FinishDay")
            m_CurrentTimeUnit = CurrentMonth
        End If
        e.Row.EndEdit()
    End Sub
    Private Sub Week_Changed(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs)
        If CurrentTimeInterval = StatisticPeriodType.Week AndAlso CurrentWeek > 0 Then
            Dim r As DataRow = FindWeek(CurrentWeek)
            e.Row("datStartDate") = r("StartDay")
            e.Row("datFinishDate") = r("FinishDay")
            m_CurrentTimeUnit = CurrentWeek
        End If

    End Sub
    Private Sub Day_Changed(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs)
        If CurrentTimeInterval = StatisticPeriodType.Day AndAlso Not Utils.IsEmpty(CurrentDay) Then
            e.Row("datStartDate") = CurrentDay
            e.Row("datFinishDate") = CurrentDay
            m_CurrentTimeUnit = CurrentDay
            If CurrentMonth <> CDate(CurrentDay).Month Then
                CurrentMonth = CDate(CurrentDay).Month
            End If
            If CurrentYear <> CDate(CurrentDay).Year Then
                CurrentYear = CDate(CurrentDay).Year
            End If
        End If

    End Sub
    Private Sub Country_Changed(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs)
        If e.Row("idfsCountry") Is DBNull.Value Then
            e.Row("idfsCountry") = model.Core.EidssSiteContext.Instance.CountryID
        End If
        If cbCountry.Visible AndAlso Not cbRegion.Visible Then
            e.Row("idfsAdministrativeUnit") = e.Row("idfsCountry")
        End If
        If (Not Utils.IsEmpty(e.Row("idfsRegion"))) AndAlso _
            CType(cbRegion.Properties.DataSource, DataView).Table.Select(String.Format("idfsCountry = {0} and idfsRegion = {1}", e.Row("idfsCountry"), e.Row("idfsRegion"))).Length = 0 Then
            e.Row("idfsRegion") = DBNull.Value
            e.Row.EndEdit()
        End If
        Core.LookupBinder.FilterRegion(cbRegion, e.Row("idfsCountry"))
        cbRegion.Enabled = CType(cbRegion.Properties.DataSource, DataView).Count>0
        If CurrentAdminLevel = StatisticAreaType.Country Then
            CurrentAdminUnit = e.Row("idfsCountry")
        Else
            eventManager.Cascade(AggregateHeader_DB.TableAggregateHeader + ".idfsRegion")
        End If
    End Sub

    Private Sub Region_Changed(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs)
        Dim tmpRegion As Long = -1
        If Not Utils.IsEmpty(e.Row("idfsRegion")) Then
            tmpRegion = CLng(e.Row("idfsRegion"))
        End If
        If Not Utils.IsEmpty(e.Row("idfsRayon")) AndAlso _
            CType(cbRayon.Properties.DataSource, DataView).Table.Select(String.Format("idfsRegion = {0} and idfsRayon = {1}", tmpRegion, e.Row("idfsRayon"))).Length = 0 Then
            e.Row("idfsRayon") = DBNull.Value
            e.Row.EndEdit()
        End If
        Core.LookupBinder.FilterRayon(cbRayon, tmpRegion)
        If CurrentAdminLevel = StatisticAreaType.Region Then
            CurrentAdminUnit = e.Row("idfsRegion")
        Else
            eventManager.Cascade(AggregateHeader_DB.TableAggregateHeader + ".idfsRayon")
        End If

    End Sub

    Private Sub Rayon_Changed(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs)
        Dim tmpRayon As Long = -1
        If Not Utils.IsEmpty(e.Row("idfsRayon")) Then
            tmpRayon = CLng(e.Row("idfsRayon"))
        End If
        If Not Utils.IsEmpty(e.Row("idfsSettlement")) AndAlso _
            CType(cbSettlement.Properties.DataSource, DataView).Table.Select(String.Format("idfsRayon = {0} and idfsSettlement = {1}", tmpRayon, e.Row("idfsSettlement"))).Length = 0 Then
            e.Row("idfsSettlement") = DBNull.Value
        End If
        Core.LookupBinder.FilterSettlement(cbSettlement, tmpRayon)
        If CurrentAdminLevel = StatisticAreaType.Rayon Then
            CurrentAdminUnit = e.Row("idfsRayon")
        Else
            eventManager.Cascade(AggregateHeader_DB.TableAggregateHeader + ".idfsSettlement")
        End If

    End Sub
    Private Sub Settlement_Changed(ByVal sender As Object, ByVal e As DataFieldChangeEventArgs)
        If CurrentAdminLevel = StatisticAreaType.Settlement Then
            CurrentAdminUnit = e.Row("idfsSettlement")
        End If
    End Sub

    Private ReadOnly Property baseDataset() As DataSet
        Get
            Return m_Owner.baseDataSet
        End Get
    End Property

    Private Shared Sub AddMonthRow(ByVal monthTable As DataTable, ByVal year As Integer, ByVal monthNum As Integer, ByVal monthName As String)
        Dim d As Date = New DateTime(year, monthNum, 1)
        Dim m As DataRow = monthTable.NewRow
        m("PeriodName") = EidssMessages.Get(monthName)
        m("StartDay") = d
        m("PeriodNumber") = d.Month
        m("PeriodID") = year.ToString() + "_" + d.Month.ToString()
        d = d.AddMonths(1)
        m("FinishDay") = d.AddDays(-1)
        monthTable.Rows.Add(m)
    End Sub

    Private Shared Function CreatePeriodTable() As DataTable
        Dim dt As New DataTable
        dt.Columns.Add(New DataColumn("PeriodNumber", GetType(Integer)))
        dt.Columns.Add(New DataColumn("StartDay", GetType(DateTime)))
        dt.Columns.Add(New DataColumn("FinishDay", GetType(DateTime)))
        dt.Columns.Add(New DataColumn("PeriodName", GetType(String)))
        dt.Columns.Add(New DataColumn("PeriodID", GetType(String)))
        dt.PrimaryKey = New DataColumn() {dt.Columns("PeriodNumber")}
        Return dt
    End Function

    Private Sub BindPeriodTable(ByVal cb As LookUpEdit, ByVal dt As DataTable)
        cb.Properties.Columns.Clear()
        cb.Properties.Columns.AddRange(New DevExpress.XtraEditors.Controls.LookUpColumnInfo() { _
            New DevExpress.XtraEditors.Controls.LookUpColumnInfo("PeriodNumber", EidssMessages.Get("colPeriodNumber", "Period Number"), 50, DevExpress.Utils.FormatType.None, "", True, DevExpress.Utils.HorzAlignment.Near), _
            New DevExpress.XtraEditors.Controls.LookUpColumnInfo("PeriodName", EidssMessages.Get("colPeriodName", "Period Name"), 200, DevExpress.Utils.FormatType.None, "", True, DevExpress.Utils.HorzAlignment.Near)} _
        )
        cb.Properties.DataSource = New DataView(dt)
        cb.Properties.DisplayMember = "PeriodName"
        cb.Properties.ValueMember = "PeriodNumber"
    End Sub

    Public Sub FillMonthList(ByVal year As Integer)
        FillMonthList(m_MonthList, year)
        BindPeriodTable(cbMonth, m_MonthList)
    End Sub

    Public Shared Sub FillMonthList(ByVal monthTable As DataTable, ByVal year As Integer)
        If monthTable Is Nothing Then
            monthTable = CreatePeriodTable()
        Else
            monthTable.Clear()
        End If
        AddMonthRow(monthTable, year, 1, "January")
        AddMonthRow(monthTable, year, 2, "February")
        AddMonthRow(monthTable, year, 3, "March")
        AddMonthRow(monthTable, year, 4, "April")
        AddMonthRow(monthTable, year, 5, "May")
        AddMonthRow(monthTable, year, 6, "June")
        AddMonthRow(monthTable, year, 7, "July")
        AddMonthRow(monthTable, year, 8, "August")
        AddMonthRow(monthTable, year, 9, "September")
        AddMonthRow(monthTable, year, 10, "October")
        AddMonthRow(monthTable, year, 11, "November")
        AddMonthRow(monthTable, year, 12, "December")
    End Sub
    Public Sub FillQuarterList(ByVal year As Integer)
        m_QuarterList.Clear()
        Dim d As Date = New DateTime(year, 1, 1)
        For i As Integer = 1 To 4
            Dim q As DataRow = m_QuarterList.NewRow
            q("StartDay") = d
            q("PeriodNumber") = i
            q("PeriodID") = year.ToString() + "_" + i.ToString()
            d = d.AddMonths(3)
            q("FinishDay") = d.AddDays(-1)
            q("PeriodName") = q("StartDay").ToString.Substring(0, 10) + "-" + q("FinishDay").ToString.Substring(0, 10)
            m_QuarterList.Rows.Add(q)
        Next
        BindPeriodTable(cbQuarter, m_QuarterList)

    End Sub

    Public Sub FillWeekList(ByVal year As Integer)
        m_WeekList.Clear()
        Dim d As Date = New DateTime(year, 1, 1)
        While d.DayOfWeek <> DayOfWeek.Monday
            d = d.AddDays(1)
        End While
        Dim weekNum As Integer = 1
        While d.Year = year
            Dim weekRow As DataRow = m_WeekList.NewRow
            weekRow("PeriodNumber") = weekNum
            weekRow("StartDay") = d
            weekRow("PeriodID") = year.ToString() + "_" + weekNum.ToString()
            d = d.AddDays(7)
            weekRow("FinishDay") = d.AddDays(-1)
            weekRow("PeriodName") = String.Format("{0:d} - {1:d}", weekRow("StartDay"), weekRow("FinishDay"))
            m_WeekList.Rows.Add(weekRow)
            weekNum = weekNum + 1
        End While
        BindPeriodTable(cbWeek, m_WeekList)
    End Sub

    Public Sub FillYearList()
        cbYear.Properties.Items.Clear()
        For i As Integer = Date.Today.Year To m_MinYear Step -1 'Date.MinValue.Year Step -1
            cbYear.Properties.Items.Add(i)
        Next
    End Sub

    Public Function FindQuarter(ByVal quarter As Integer) As DataRow
        Return m_QuarterList.Rows.Find(quarter)
    End Function
    Public Function FindMonth(ByVal month As Integer) As DataRow
        Return m_MonthList.Rows.Find(month)
    End Function
    Public Function FindWeek(ByVal week As Integer) As DataRow
        Return m_WeekList.Rows.Find(week)
    End Function

    Public Sub SetYear()
        FillYearList()
        SetQuarter()
        SetMonth()
        SetWeek()
    End Sub

    Public Sub SetQuarter()
        If CurrentYear > 0 Then
            FillQuarterList(CurrentYear)
        Else
            cbQuarter.EditValue = DBNull.Value
            cbQuarter.Properties.DataSource = Nothing
        End If
    End Sub

    Public Sub SetMonth()
        If CurrentYear > 0 Then
            FillMonthList(CurrentYear)
        Else
            cbMonth.EditValue = DBNull.Value
            cbMonth.Properties.DataSource = Nothing
        End If
        SetDay()
    End Sub

    Public Sub SetWeek()
        If CurrentYear > 0 Then
            FillWeekList(CurrentYear)
        Else
            cbWeek.EditValue = DBNull.Value
            cbWeek.Properties.DataSource = Nothing
        End If
    End Sub

    Public Sub SetDay()
        If CurrentMonth >= 0 AndAlso PeriodType = StatisticPeriodType.Day Then
            datDay.Enabled = True
            datDay.EditValue = DBNull.Value
        Else
            datDay.EditValue = DBNull.Value
            datDay.Enabled = False
        End If
    End Sub

    Private Function CurrentRow() As DataRow
        If baseDataset.Tables.Count > 0 AndAlso baseDataset.Tables(AggregateHeader_DB.TableAggregateHeader).Rows.Count > 0 Then
            Return baseDataset.Tables(AggregateHeader_DB.TableAggregateHeader).Rows(0)
        Else
            Return Nothing
        End If
    End Function

    Public ReadOnly Property MinYear() As Integer
        Get
            Return m_MinYear
        End Get
    End Property

    Public ReadOnly Property AreaType() As StatisticAreaType
        Get
            If baseDataset.Tables(AggregateHeader_DB.TableSettings) Is Nothing OrElse baseDataset.Tables(AggregateHeader_DB.TableSettings).Rows.Count <> 1 OrElse baseDataset.Tables(AggregateHeader_DB.TableSettings).Rows(0)("idfsStatisticAreaType") Is DBNull.Value Then
                Return StatisticAreaType.None
            End If
            Return CType(baseDataset.Tables(AggregateHeader_DB.TableSettings).Rows(0)("idfsStatisticAreaType"), StatisticAreaType)
        End Get
    End Property

    Public ReadOnly Property PeriodType() As StatisticPeriodType
        Get
            If baseDataset.Tables(AggregateHeader_DB.TableSettings) Is Nothing OrElse baseDataset.Tables(AggregateHeader_DB.TableSettings).Rows.Count <> 1 OrElse baseDataset.Tables(AggregateHeader_DB.TableSettings).Rows(0)("idfsStatisticPeriodType") Is DBNull.Value Then
                Return StatisticPeriodType.None
            End If
            Return CType(baseDataset.Tables(AggregateHeader_DB.TableSettings).Rows(0)("idfsStatisticPeriodType"), StatisticPeriodType)
        End Get
    End Property

    Public ReadOnly Property CaseType() As AggregateCaseType
        Get
            If CurrentRow("idfsAggrCaseType") Is Nothing Then
                Return AggregateCaseType.None
            Else
                Return CType(CurrentRow("idfsAggrCaseType"), AggregateCaseType)
            End If
        End Get
    End Property

    Public Property CurrentDay() As Object
        Get
            Return CurrentRow("DayForAggr")
        End Get
        Set(ByVal value As Object)
            CurrentRow("DayForAggr") = value
            CurrentRow.EndEdit()
        End Set
    End Property
    Public Property CurrentMonth() As Integer
        Get
            If CurrentRow("MonthForAggr") Is DBNull.Value Then
                Return -1
            End If
            Return CInt(CurrentRow("MonthForAggr"))
        End Get
        Set(ByVal value As Integer)
            If value > 0 Then
                CurrentRow("MonthForAggr") = value
            Else
                CurrentRow("MonthForAggr") = DBNull.Value
            End If
            CurrentRow.EndEdit()
        End Set
    End Property
    Public Property CurrentQuarter() As Integer
        Get
            If CurrentRow("QuarterForAggr") Is DBNull.Value Then
                Return -1
            End If
            Return CInt(CurrentRow("QuarterForAggr"))
        End Get
        Set(ByVal value As Integer)
            If value > 0 Then
                CurrentRow("QuarterForAggr") = value
            Else
                CurrentRow("QuarterForAggr") = DBNull.Value
            End If
            CurrentRow.EndEdit()
        End Set
    End Property
    Public Property CurrentWeek() As Integer
        Get
            If CurrentRow("WeekForAggr") Is DBNull.Value Then
                Return -1
            End If
            Return CInt(CurrentRow("WeekForAggr"))
        End Get
        Set(ByVal value As Integer)
            If value > 0 Then
                CurrentRow("WeekForAggr") = value
            Else
                CurrentRow("WeekForAggr") = DBNull.Value
            End If
            CurrentRow.EndEdit()
        End Set
    End Property
    Public Property CurrentYear() As Integer
        Get
            If CurrentRow("YearForAggr") Is DBNull.Value Then
                Return -1
            End If
            Return CInt(CurrentRow("YearForAggr"))
        End Get
        Set(ByVal value As Integer)
            If value > 0 Then
                CurrentRow("YearForAggr") = value
            Else
                CurrentRow("YearForAggr") = DBNull.Value
            End If
            CurrentRow.EndEdit()
        End Set
    End Property
    Public Property CurrentTimeInterval() As StatisticPeriodType
        Get
            If CurrentRow() Is Nothing OrElse Utils.IsEmpty(CurrentRow("CurPeriodType")) Then
                Return StatisticPeriodType.None
            End If
            Return CType(CurrentRow("CurPeriodType"), StatisticPeriodType)
        End Get
        Set(ByVal value As StatisticPeriodType)
            CurrentRow("CurPeriodType") = value
            CurrentRow.EndEdit()
        End Set
    End Property

    Public Property CurrentAdminLevel() As StatisticAreaType
        Get
            If CurrentRow() Is Nothing OrElse Utils.IsEmpty(CurrentRow("CurAreaType")) Then
                Return StatisticAreaType.None
            End If
            Return CType(CurrentRow("CurAreaType"), StatisticAreaType)
        End Get
        Set(ByVal value As StatisticAreaType)
            CurrentRow("CurAreaType") = value
            CurrentRow.EndEdit()
        End Set
    End Property
    Private m_CurrentTimeUnit As Object
    Public Property CurrentTimeUnit() As Object
        Get
            Return m_CurrentTimeUnit
        End Get
        Set(ByVal value As Object)
            m_CurrentTimeUnit = value
        End Set
    End Property
    Public Property CurrentAdminUnit() As Object
        Get
            Return CurrentRow("idfsAdministrativeUnit")
        End Get
        Set(ByVal value As Object)
            CurrentRow("idfsAdministrativeUnit") = value
            CurrentRow.EndEdit()
        End Set
    End Property
    Public Property StartDate() As Object
        Get
            Return CurrentRow("datStartDate")
        End Get
        Set(ByVal value As Object)
            CurrentRow("datStartDate") = value
            CurrentRow.EndEdit()
        End Set
    End Property
    Public Property FinishDate() As Object
        Get
            Return CurrentRow("datFinishDate")
        End Get
        Set(ByVal value As Object)
            CurrentRow("datFinishDate") = value
            CurrentRow.EndEdit()
        End Set
    End Property
    Public Property Country() As Object
        Get
            Return CurrentRow("idfsCountry")
        End Get
        Set(ByVal value As Object)
            CurrentRow("idfsCountry") = value
            CurrentRow.EndEdit()
        End Set
    End Property
    Public Property Region() As Object
        Get
            Return CurrentRow("idfsRegion")
        End Get
        Set(ByVal value As Object)
            CurrentRow("idfsRegion") = value
            CurrentRow.EndEdit()
        End Set
    End Property
    Public Property Rayon() As Object
        Get
            Return CurrentRow("idfsRayon")
        End Get
        Set(ByVal value As Object)
            CurrentRow("idfsRayon") = value
            CurrentRow.EndEdit()
        End Set
    End Property
    Public Property Settlement() As Object
        Get
            Return CurrentRow("idfsSettlement")
        End Get
        Set(ByVal value As Object)
            CurrentRow("idfsSettlement") = value
            CurrentRow.EndEdit()
        End Set
    End Property
    Private Shared Function GetMatrixStub(ByVal formType As FFType) As List(Of AggregateCaseSection)
        Dim stub As New List(Of AggregateCaseSection)
        Dim section As AggregateCaseSection
        Select Case formType
            Case FFType.HumanAggregateCase
                section = AggregateCaseSection.HumanCase
            Case FFType.VetAggregateCase
                section = AggregateCaseSection.VetCase
            Case FFType.VetEpizooticAction
                section = AggregateCaseSection.SanitaryAction
            Case FFType.VetEpizooticActionDiagnosisInv
                section = AggregateCaseSection.DiagnosticAction
            Case FFType.VetEpizooticActionTreatment
                section = AggregateCaseSection.ProphylacticAction
            Case Else
                Return Nothing
        End Select
        stub.Add(section)
        Return stub
    End Function
    Private Shared Function SetGridDockStyleToFill(ByVal ffGrid As FlexibleForms.FFPresenter) As Boolean
        Dim sectionTable As FlexibleForms.Components.SectionTable
        sectionTable = ffGrid.GetSectionTableByIndex(0)
        If Not (sectionTable Is Nothing) Then
            sectionTable.Dock = DockStyle.Fill
            'Dim gridView As GridView = CType(sectionTable.GridControlMain.MainView, GridView)
            'If Not gridView Is Nothing Then
            '    gridView.OptionsView.NewItemRowPosition = NewItemRowPosition.None
            'End If
        Else
            Return False
        End If
        Return sectionTable.IsStubLoaded()
    End Function
    Public Shared Sub ClearFlexibleForm(ByVal ffGrid As FlexibleForms.FFPresenter)
        ffGrid.ClearUserData()
    End Sub
    Public Shared Function ShowFlexibleForm(ByVal ffGrid As FlexibleForms.FFPresenter, ByVal observationID As Long, ByVal formType As FFType, ByVal templateID As Nullable(Of Long), ByVal idfVersion As Nullable(Of Long), Optional ByVal isSummary As Boolean = False) As Boolean
        Dim stub As List(Of AggregateCaseSection) = GetMatrixStub(formType)
        If stub Is Nothing Then
            Return False
        End If
        ffGrid.ShowAggregateCase(stub(0), observationID, templateID, idfVersion, formType, True, isSummary)
        'ffGrid.ShowFlexibleForm(stub, observationID, formType)
        Return SetGridDockStyleToFill(ffGrid)
    End Function
    Public Shared Function ShowSummaryFlexibleForm(ByVal ffGrid As FlexibleForms.FFPresenter, ByVal observations As List(Of Long), ByVal formType As FFType) As Boolean
        If observations Is Nothing Then
            Return False
        End If
        Dim stub As List(Of AggregateCaseSection) = GetMatrixStub(formType)
        If stub Is Nothing Then
            Return False
        End If
        Dim result As Boolean = ffGrid.ShowSummary(observations, formType)
        Return SetGridDockStyleToFill(ffGrid) And result
    End Function
    Public Shared Function GetGridView(ByVal ffGrid As FlexibleForms.FFPresenter) As GridView
        Dim sectionTable As FlexibleForms.Components.SectionTable
        sectionTable = ffGrid.GetSectionTableByIndex(0)
        If Not (sectionTable Is Nothing) Then
            Return CType(sectionTable.GridControlMain.MainView, GridView)
        Else
            Return Nothing
        End If
    End Function

    Public ReadOnly Property EmptyAggregateSettingsMessage() As String
        Get
            Select Case CaseType
                Case AggregateCaseType.AggregateCase
                    Return EidssMessages.Get("mbEmptyHumanAggrSettings", "Human Aggregate settings is empty.")
                Case AggregateCaseType.VetAggregateAction
                    Return EidssMessages.Get("mbEmptyVetAggrActionSettings", "Vet Aggregate Action settings are empty.")
                Case AggregateCaseType.VetAggregateCase
                    Return EidssMessages.Get("mbEmptyVetAggrSettings", "Vet Aggregate settings are empty.")
                Case Else
                    Dbg.Fail("aggregate case type is not defined")
                    Return ""
            End Select
        End Get
    End Property

    Public ReadOnly Property NoAggregateCaseMessage() As String
        Get
            Select Case CaseType
                Case AggregateCaseType.AggregateCase
                    Return EidssMessages.Get("mbNoHumanAggregateCase", "Human Aggregate Case does not exist for current administrative unit and time interval.")
                Case AggregateCaseType.VetAggregateAction
                    Return EidssMessages.Get("mbNoVetAggregateAction", "Vet Aggregate Actions does not exist for current administrative unit and time interval.")
                Case AggregateCaseType.VetAggregateCase
                    Return EidssMessages.Get("mbNoVetAggregateCase", "Vet Aggregate Case does not exist for current administrative unit and time interval.")
                Case Else
                    Dbg.Fail("aggregate case type is not defined")
                    Return ""
            End Select
        End Get
    End Property
    Public Shared Sub DisplaySummary(ByVal ffGrid As FlexibleForms.FFPresenter, ByVal formType As FFType, ByVal observations As List(Of Long), ByVal lbNoMatrix As Control)
        If observations Is Nothing Then
            'DisplayEmptySummary(ffGrid, formType, lbNoMatrix)
            'Return
            observations = New List(Of Long)()
        End If
        Dim result As Boolean = ShowSummaryFlexibleForm(ffGrid, observations, formType)
        If Not lbNoMatrix Is Nothing Then
            lbNoMatrix.Visible = Not result
        End If
        ffGrid.Visible = result
    End Sub

    Public Shared Sub DisplayEmptySummary(ByVal ffGrid As FlexibleForms.FFPresenter, ByVal formType As FFType, ByVal lbNoMatrix As Control)
        'DisplaySummary(ffGrid, formType, Nothing, lbNoMatrix)
        'Return
        Dim matrixVersion As Nullable(Of Long)
        Dim view As DataView = LookupCache.Get(LookupTables.AggregateMatrixVersion)
        Dim matrixType As AggregateCaseSection
        Select Case formType
            Case FFType.HumanAggregateCase
                matrixType = AggregateCaseSection.HumanCase
            Case FFType.VetAggregateCase
                matrixType = AggregateCaseSection.VetCase
            Case FFType.VetEpizooticAction
                matrixType = AggregateCaseSection.SanitaryAction
            Case FFType.VetEpizooticActionDiagnosisInv
                matrixType = AggregateCaseSection.DiagnosticAction
            Case FFType.VetEpizooticActionTreatment
                matrixType = AggregateCaseSection.ProphylacticAction
        End Select
        Dim filter As String = String.Format("idfsAggrCaseSection={0} and blnIsActive=1", CLng(matrixType))
        view.RowFilter = filter
        If view.Count > 0 Then
            matrixVersion = CLng(view(0)("idfVersion"))
        End If
        Dim result As Boolean = ShowFlexibleForm(ffGrid, -5, formType, Nothing, matrixVersion, True)
        If Not lbNoMatrix Is Nothing Then
            lbNoMatrix.Visible = Not result
        End If
        ffGrid.Visible = result

        Dim gridView As GridView = GetGridView(ffGrid)
        If Not gridView Is Nothing Then
            gridView.OptionsBehavior.Editable = False
        End If
    End Sub
End Class


text:
A [`<Router>`](../../../react-router/docs/api/Router.md) for iOS and Android apps built using [React Native](https://facebook.github.io/react-native/).

```js
import { NativeRouter } from 'react-router-native'

<NativeRouter>
  <App/>
</NativeRouter>
```

## getUserConfirmation: func

A function to use to confirm navigation.

```js
import { Alert } from 'react-native'

// This is the default behavior
const getConfirmation = (message, callback) => {
  Alert.alert('Confirm', message, [
    { text: 'Cancel', onPress: () => callback(false) },
    { text: 'OK', onPress: () => callback(true) }
  ])
}

<NativeRouter getUserConfirmation={getConfirmation}/>
```

## keyLength: number

The length of `location.key`. Defaults to 6.

```js
<NativeRouter keyLength={12}/>
```

## children: node

A [single child element](https://facebook.github.io/react/docs/react-api.html#react.children.only) to render.

redpajama_set_name: RedPajamaGithub


text:
using UnityEngine;
using System.Collections;

public class GameControlScript : MonoBehaviour
{
	public static GameControlScript current;	//a reference to our game control so we can access it statically
	public ColumnSpawnScript columnSpawner;		//a reference to the column spawner
	public GUIText scoreText;					//a reference to text that shows the player's score
	public GameObject gameOvertext;				//a reference to the object that contains the text that appears when the player dies

	int score = 0;								//the player's score
	bool isGameOver = false;					//is the game over?

	void Awake()
	{
		//if we don't currently have a game control...
		if (current == null)
			//...set this one to be it...
			current = this;
		//...otherwise...
		else if(current != this)
			//...destroy this one because it is a duplicate
			Destroy (gameObject);
	}

	void Update()
	{
		//if the game is over and the player has pressed some input...
		if (isGameOver && Input.anyKey)
		{
			//...start a new game.
			Application.LoadLevel(Application.loadedLevel);
		}
	}

	public void BirdScored()
	{
		//the bird can't score if the game is over
		if (isGameOver)
			return;
		//increase score
		score++;
		//adjust the score text
		scoreText.text = "Score: " + score;
	}

	public void BirdDied()
	{
		//don't spawn new columns
		columnSpawner.StopSpawn ();
		//show the game over text
		gameOvertext.SetActive (true);
		//set the game to be over
		isGameOver = true;
	}
}


text:
Imports System.Runtime.InteropServices

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim objApp As SolidEdgeFramework.Application = Nothing
        Dim objType As Type = Nothing
        Dim objMatTable As SolidEdgeFramework.MatTable = Nothing
        Dim strLibrary As String = "Materials"
        Dim objDocument As SolidEdgePart.PartDocument = Nothing
        Dim strMaterial As String = ""
        Dim varGetPropVal As Object = Nothing
        Dim listOfMaterials As Object = Nothing
        Dim listOfLibraries As Object = Nothing
        Dim numMaterials As Long
        Dim strMessage As String

        Try
            ' Get SE handle
            objApp = Marshal.GetActiveObject("SolidEdge.Application")

            If objApp Is Nothing Then
                ' Get the type from the Solid Edge ProgID
                objType = Type.GetTypeFromProgID("SolidEdge.Application")
                ' Start Solid Edge
                objApp = Activator.CreateInstance(objType)
                ' Make Solid Edge visible
                objApp.Visible = True
            End If
            ' Get material table object handle
            objMatTable = objApp.GetMaterialTable()

            ' Get material list
            objMatTable.GetFavoriteMaterialList(listOfMaterials, listOfLibraries, numMaterials)
            strMaterial = listOfMaterials(5)
            strLibrary = listOfLibraries(5)

            strMessage = String.Format("Number of FAVORITE materials = {0}", numMaterials)
            MsgBox(strMessage)

            strMessage = String.Format("6h FAVORITE Material is = {0} and its library is = {1}", strMaterial, strLibrary)
            MsgBox(strMessage)

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

    End Sub

End Class


text:
package com.marsjiang.mygoogleplay.adapter;

import com.marsjiang.mygoogleplay.R;
import com.marsjiang.mygoogleplay.ui.fragment.FragmentFactory;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MainPagerAdapter extends FragmentPagerAdapter {

	private String[] tabs;

	public MainPagerAdapter(Context context,FragmentManager fm) {
		super(fm);
		tabs = context.getResources().getStringArray(R.array.tab_names);
	}

	@Override
	public Fragment getItem(int position) {
		return FragmentFactory.create(position);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return tabs.length;
	}

	@Override
	public CharSequence getPageTitle(int position) {
		// TODO Auto-generated method stub
		return tabs[position];
	}

}


text:
TRIBITS_PACKAGE_DEFINE_DEPENDENCIES(
  LIB_REQUIRED_PACKAGES SEACASSupes
)


text:
import ursgal
import importlib
import os
import sys
import pickle
import csv
import copy
import re
import pprint
from collections import defaultdict as ddict

class compomics_utilities_4_11_5(ursgal.UNode):
    """
    compomics_utilities_4_11_5 UNode

    Reference:
        Barsnes, H., Vaudel, M., Colaert, N., Helsens, K., Sickmann, A.,
        Berven, F. S., and Martens, L. (2011) compomics-utilities: an
        open-source Java library for computational proteomics. BMC\
        Bioinformatics 12, 70

    Warning:
        Implementation still in beta-stage!

    """

    META_INFO = {
        "edit_version": 1.00,
        "name": "Compomic Utilities",
        "version": "4.11.5",
        "release_date": None,
        "engine_type": {"misc_engine": True},
        "output_suffix": "compomics",
        "input_extensions": [
            ".txt",
        ],
        "output_extensions": [
            ".csv",
        ],
        "distributable": False,
        "include_in_git": False,
        "in_development": False,
        "utranslation_style": "compomics_utilities_style_1",
        "engine": {
            "platform_independent": {
                "arc_independent": {
                    "exe": "utilities-4.11.5.jar",
                    "url": "",
                    "zip_md5": "",
                },
            },
        },
        "citation": "Barsnes, H., Vaudel, M., Colaert, N., Helsens, K., Sickmann, A.,"
        "Berven, F. S., and Martens, L. (2011) compomics-utilities: an "
        "open-source Java library for computational proteomics. BMC"
        "Bioinformatics 12, 70",
    }

    def __init__(self, *args, **kwargs):
        super(compomics_utilities_4_11_5, self).__init__(*args, **kwargs)

    def set_up_command_list(self):
        """
        java
        -cp
        utilities-4.11.5.jar
        com.compomics.util.experiment.identification.protein_inference.executable.PeptideMapping
        -p /media/plan-f/Shared/databases/Saccharomyces_cerevisiae/uniprot_version_20161016_download_date_20161213/uniprot-proteome%3AUP000002311.fasta
        test.txt
        test_out.txt

        """

        if (
            self.params["translations"]["compomics_utility_name"]
            == "com.compomics.util.experiment.identification.protein_inference.executable.PeptideMapping"
        ):
            command_list = [
                "java",
                "-cp",
                self.exe,
                self.params["translations"]["compomics_utility_name"],
                "-p",
                self.params["translations"]["database"],
                self.tmp_peptide_file,
                self.params["translations"]["output_file_incl_path"],
            ]
        return command_list

    def preflight(self):
        """"""
        input_file_incl_path = os.path.join(
            self.params["input_dir_path"], self.params["input_file"]
        )
        self.params["translations"]["output_file_incl_path"] = os.path.join(
            self.params["output_dir_path"], self.params["output_file"]
        )
        if (
            self.params["translations"]["compomics_utility_name"]
            == "com.compomics.util.experiment.identification.protein_inference.executable.PeptideMapping"
        ):

            # read csv and write txt input file...
            self.tmp_peptide_file = os.path.join(
                self.params["output_dir_path"], "peptides.txt"
            )
            with open(self.tmp_peptide_file, "w") as io:
                peptides = set()
                for line_dict in csv.DictReader(open(input_file_incl_path, "r")):
                    appended = False
                    for aa_to_replace, replace_dict in sorted(
                        self.params["translations"]["aa_exception_dict"].items(),
                        reverse=True,
                    ):
                        if aa_to_replace in line_dict["Sequence"]:
                            if aa_to_replace in ["O"]:
                                if "unimod_name" in replace_dict.keys():
                                    for r_pos, aa in enumerate(line_dict["Sequence"]):
                                        if aa == aa_to_replace:
                                            index_of_aa = r_pos + 1
                                            unimod_name = replace_dict["unimod_name"]
                                            new_mod = "{0}:{1}".format(
                                                unimod_name, index_of_aa
                                            )
                                            if line_dict["Modifications"] == "":
                                                line_dict["Modifications"] += new_mod
                                            else:
                                                line_dict[
                                                    "Modifications"
                                                ] += ";{0}".format(new_mod)
                                if len(replace_dict["original_aa"]) == 1:
                                    line_dict["Sequence"] = line_dict[
                                        "Sequence"
                                    ].replace(
                                        aa_to_replace, replace_dict["original_aa"][0]
                                    )
                            elif aa_to_replace in ["J"]:
                                repeat_count = line_dict["Sequence"].count(
                                    aa_to_replace
                                )
                                # we need to do all combos for the positions of I and L in the seq...
                                positions = []
                                for index_of_aa, aa in enumerate(line_dict["Sequence"]):
                                    if aa == aa_to_replace:
                                        positions.append(index_of_aa)
                                product_combos = []
                                new_peptides = set()
                                for combo_tuple in itertools.product(
                                    replace_dict["original_aa"], repeat=repeat_count
                                ):
                                    # product_combos.append(n)
                                    for pos, new_aa in enumerate(combo_tuple):
                                        index_of_aa = positions[pos]
                                        # text[:1] + 'Z' + text[2:]
                                        remapped_peptide = "{0}{1}{2}".format(
                                            line_dict["Sequence"][:index_of_aa],
                                            new_aa,
                                            line_dict["Sequence"][index_of_aa + 1 :],
                                        )
                                        tmp_peptide_set.add(remapped_peptide)
                                        line_dict["Sequence"] = remapped_peptide
                                        csv_file_buffer.append(deepcopy(line_dict))
                                        appended = True
                            else:
                                print(
                                    """
                                    [ WARNING ] New not covered case of aa exception for: "{0}"
                                    [ WARNING ] Please adjust upeptide_mapper accordingly
                                    """.format(
                                        aa_to_replace
                                    )
                                )
                                sys.exit(1)
                    if appended is False:
                        peptides.add(line_dict["Sequence"])
                for peptide in peptides:
                    print(peptide, file=io)

        self.params["command_list"] = self.set_up_command_list()
        return self.params["translations"]["output_file_incl_path"]

    def postflight(self):
        """
        add pre and post amino acids to results and extend txt results..
        """
        # read database and get full name and also the pre and post aa
        short_2_long_name_mapping = {}
        fasta_id_dict = {}
        for fastaID, sequence in ursgal.ucore.parse_fasta(
            open(self.params["translations"]["database"], "r")
        ):
            fasta_id_dict[fastaID] = sequence
            try:
                short_2_long_name_mapping[
                    fastaID.split("|")[1]
                ] = fastaID  # uniprot style
            except:
                pass
        all_full_protein_names = list(fasta_id_dict.keys())
        buffered_maps = ddict(list)
        with open(self.params["translations"]["output_file_incl_path"], "r") as io:
            for line in io.readlines():
                peptide, protein, start_pos = line.split(",")
                if protein in fasta_id_dict.keys():
                    full_protein_name = protein
                else:
                    # this is slow and inefficient, but we need the full name
                    # use pyahocorasick automaton?? :)))
                    if protein in short_2_long_name_mapping.keys():
                        full_protein_name = short_2_long_name_mapping[protein]
                    else:
                        for full_protein_name in all_full_protein_names:
                            if protein in full_protein_name:
                                short_2_long_name_mapping[protein] = full_protein_name
                                break

                sequence = fasta_id_dict[full_protein_name]
                start_pos = int(start_pos)
                stop_pos = start_pos + len(peptide)
                pre_pos = start_pos - 1
                if pre_pos < 0:
                    pre = "-"
                else:
                    pre = sequence[pre_pos]
                try:
                    post = sequence[stop_pos]
                except:
                    post = "-"

                buffered_maps[peptide].append(
                    {
                        "start": start_pos + 1,
                        "end": stop_pos,
                        "pre": pre,
                        "post": post,
                        "id": full_protein_name,
                    }
                )
        with open(self.params["translations"]["output_file_incl_path"], "w") as io:
            for peptide, info_dict_list in buffered_maps.items():
                for info_dict in info_dict_list:
                    print(
                        "{0},{id},{start},{end},{pre},{post}".format(
                            peptide, **info_dict
                        ),
                        file=io,
                    )
        os.remove(self.tmp_peptide_file)
        return


text:
<?php

namespace JsonDb\Query;

class QueryNone extends Query implements QueryInterface
{
    /**
     * {@inheritdoc}
     */
    public function match(array $document)
    {
        return false;
    }
}


text:
imagej-cromatic-aberration-corrector
====================================

Plugin for ImageJ platform to compute & correct shifts for different color channels in 3D images, acquired with fluorescent microscopes.


text:
from .javatar_menu import *
from .javatar_project_restoration import *


text:
package wang.fragment;

import wang.interfacedemo.R;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Teacher_Fragment1 extends Fragment{
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view=inflater.inflate(R.layout.teachaernoresultfragment, null);
		return view;
	}
}


text:
define('rsvp', [], function(){
  return RSVP;
});


text:
CHECKPOINT_DIR=../data/checkpoints/run_c2d_baseline_400k_32f
mkdir ${CHECKPOINT_DIR}

python ../tools/train_net_video.py \
--config_file ../configs/DBG_kinetics_resnet_8gpu_c2d_nonlocal_400k.yaml \
TRAIN.PARAMS_FILE ../data/pretrained_model/r50_pretrain_c2_model_iter450450_clean.pkl \
VIDEO_DECODER_THREADS 5 \
NONLOCAL.CONV3_NONLOCAL False \
NONLOCAL.CONV4_NONLOCAL False \
TRAIN.VIDEO_LENGTH 32 \
TRAIN.SAMPLE_RATE 2 \
TEST.VIDEO_LENGTH 32 \
TEST.SAMPLE_RATE 2 \
MODEL.MODEL_NAME resnet_video_org \
MODEL.VIDEO_ARC_CHOICE 1 \
TRAIN.DROPOUT_RATE 0.5 \
CHECKPOINT.DIR ${CHECKPOINT_DIR} \
DATADIR ../data/lmdb/kinetics_lmdb_multicrop/ \
FILENAME_GT ../process_data/kinetics/vallist.txt \
2>&1 | tee ${CHECKPOINT_DIR}/log.txt


text:
<?xml version="1.0" encoding="utf-8" ?>
<package xmlns="http://www.mendix.com/package/1.0/">
    <clientModule name="KeyboardShortcut" version="2.0.0" xmlns="http://www.mendix.com/clientModule/1.0/">
        <widgetFiles>
            <widgetFile path="KeyboardShortcut/KeyboardShortcut.xml" />
        </widgetFiles>
        <files>
            <file path="KeyboardShortcut/widget/" />
        </files>
    </clientModule>
</package>


text:
import config from 'config';
import classes from 'dom-classes';
import Default from './default';
import SplitText from  '../vendors/SplitText';
import framework from 'framework';
import event from 'dom-event';
import debounce from 'debounce';
require('../vendors/animation.gsap');
import $ from 'jquery';
import ScrollMagic from 'scrollmagic';

class FourOhFour extends Default {

    constructor(opt) {

        super(opt);
        document.title = "404 - Paul DeCotiis";
        this.slug = '404';
    }

    init(req, done) {

        if (window.location.pathname !== '/404') {
            window.location.replace('/404');
        }

        super.init(req, done);
    }

    ready(done) {

        super.ready();
        done();
    }

    animateIn(req, done) {

        if (config.isSafari && window.innerWidth < config.desktop) {
            this.ui.pageHeader.style.height = window.innerHeight + 'px';
        }

        const nav = document.querySelector('.js-nav');

        this.splitText = new SplitText(this.ui.pageTitle, {type: 'chars'});
        this.splitText.split({linesClass: 'page-copy-line'});

        classes.add(config.body, `is-${this.slug}`);

        // this.staggerDone = () => {
        //     this.splitText.revert();
        // };

        const tl = new TimelineMax({ paused: true, onComplete: () => {
            classes.add(config.body, `is-ready`);

            if (classes.has(nav, 'nav-up')) {
                classes.remove(nav, 'nav-up');
                TweenMax.set(nav, {clearProps: "all"});
            }

            if (classes.has(nav, 'nav-down')) {
                classes.remove(nav, 'nav-down');
            }

            this.addEvents();
            done();
        }});

        tl.set(config.view, {color: config.color.black});

        tl.to(config.view, 0.5, {
            backgroundColor: config.color.white,
            ease: config.ease
        }, 0);

        tl.to(this.page, 0.5, {
            autoAlpha: 1,
            ease: config.ease
        }, 0);

        tl.staggerFrom(this.splitText.chars, 0.5, {
            autoAlpha: 0,
            y: 20,
            ease: config.ease,
        }, 0.01, 0);

        tl.staggerFrom(this.ui.staggerItem, 0.5, {
            autoAlpha: 0,
            y: 20,
            ease: config.ease
        }, 0.05, 0.5);

        tl.restart();
    }

    animateOut(req, done) {

        classes.remove(config.body, `is-${this.slug}`);
        classes.remove(config.body, `is-ready`);

        this.checkNav();

        const tl = new TimelineMax({ paused: true, onComplete: () => {
            done();
        }});

        tl.to(this.page, 0.5, {
            autoAlpha: 0,
            ease: config.ease
        });

        tl.restart();
    }

    checkNav() {
        const nav = document.querySelector('.js-nav');
        if (classes.has(nav, 'nav-up')) {
            classes.remove(nav, 'nav-up');
        }

        if (classes.has(nav, 'nav-down')) {
            classes.remove(nav, 'nav-down');
        }
    }

    initNav() {

        // Hide Header on scroll down
        let lastScrollTop = 0;

        const nav = document.querySelector('.js-nav');
        const contentWrapHeight = document.querySelector('.page-wrap').clientHeight;

        event.on(this.page, 'scroll', () => {
            debounce(hasScrolled(), 75, true);
        });

        let hasScrolled = () => {
            const navbarHeight = window.innerHeight - 180;
            const delta = document.documentElement.clientHeight;

            let scrollPos = this.page.scrollTop;

            if (scrollPos > lastScrollTop && scrollPos > navbarHeight) {
                if (!classes.has(nav, 'nav-up')) {
                    // Scroll Down
                    classes.remove(nav, 'nav-down');
                    classes.remove(nav, 'nav-top');
                    classes.add(nav, 'nav-up');
                }
            } else if (scrollPos + document.documentElement.clientHeight < contentWrapHeight && !classes.has(nav, 'nav-down')) {
                // Scroll Up
                classes.remove(nav, 'nav-up');
                classes.remove(nav, 'nav-top');
                classes.add(nav, 'nav-down');
            }

            lastScrollTop = scrollPos;

            if (scrollPos < navbarHeight) {
                classes.add(nav, 'nav-top');
            }

            if (scrollPos <= 10) {
                classes.add(nav, 'nav-top');
            }

        };

        hasScrolled();
    }

    initFooter() {
        const target = this.getAttribute('data-goto');

        const tl = new TimelineMax({paused: true, onComplete: () => {
            classes.remove(config.body, `is-ready`);
            framework.go(target);
        }});

        const nav = document.querySelector('.js-nav');
        const footer = document.querySelector('.js-footer');

        if (classes.has(nav, 'nav-down')) {
            classes.add(nav, 'nav-up');
        }

        tl.set(footer, {zIndex: 200, autoAlpha: 1, scale: 1});
        tl.to('.js-footer-content', 0.5, {autoAlpha: 0, ease: config.ease}, 0);
        tl.to(footer, 1, {height: window.innerHeight, ease: config.ease}, 0);

        tl.restart();
    }

    initScroll() {
        this.controller = new ScrollMagic.Controller({container: '.page'});

        let tl = new TimelineMax({paused: true});

        if (window.innerWidth < config.desktop ) {
            tl.fromTo('.str-v', 0.5, {x: "-35%"}, {x: "0%"});
            tl.fromTo('.str-v2', 0.5, {x: "35%"}, {x: "0%"}, 0);
        } else {
            tl.fromTo('.str-v', 0.5, {x: "-52%"}, {x: "0%"});
            tl.fromTo('.str-v2', 0.5, {x: "52%"}, {x: "0%"}, 0);
        }

        tl.to('.str-v4', 0.25, {autoAlpha: 0}, 0);
        tl.fromTo('.str-v3', 0.5, {autoAlpha: 0}, {autoAlpha: 1}, 0);

        // build scene
        this.scene = new ScrollMagic.Scene({triggerElement: '.st', duration: window.innerHeight / 1.5})
            .addTo(this.controller)
            .setTween(TweenMax.to('.str', 0.5, {autoAlpha: 0, scale: 0.98}));

        this.scene2  = new ScrollMagic.Scene({triggerElement: '.st-2', duration: window.innerHeight / 1.5, triggerHook: 0.7})
            .addTo(this.controller)
            .setTween(
                tl.restart()
            );

        this.scene3 = new ScrollMagic.Scene({triggerElement: '.st-3', duration: 420, triggerHook: 'onEnter'})
            .addTo(this.controller)
            .setTween(TweenMax.to('.str-f', 0.5, {autoAlpha: 1, scale: 1, zIndex: 0}));

        event.on(this.ui.footer, 'click', () => {
            this.controller = this.controller.destroy();
        });

    }

    initScrollBtn() {
        let pageWrap = $('.page');
        let btnScroll = document.querySelectorAll('.js-btn-scroll');

        for (let i = 0; i < btnScroll.length; i++) {
            btnScroll[i].addEventListener('click', () => {
                pageWrap.animate({scrollTop: window.innerHeight}, 300);
            });
        }
    }

    addEvents() {
        this.initNav();
        this.initScroll();
        this.initScrollBtn();
        // Init the footer
        event.on(this.ui.footer, 'click', this.initFooter);
    }

    removeEvents() {
        // noop
    }

    destroy(req, done) {

        super.destroy();

        // this.removeEvents();

        this.page.parentNode.removeChild(this.page);

        done();
    }
}

module.exports = FourOhFour;


text:
// *****************************************************************************
//
//  © Component Factory Pty Ltd 2012. All rights reserved.
//	The software and associated documentation supplied hereunder are the
//  proprietary information of Component Factory Pty Ltd, 17/267 Nepean Hwy,
//  Seaford, Vic 3198, Australia and are supplied subject to licence terms.
//
//  Version 4.4.1.0 	www.ComponentFactory.com
// *****************************************************************************

using System;
using System.Text;
using System.Drawing;
using System.Drawing.Design;
using System.Windows.Forms;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections.Generic;
using System.Diagnostics;

namespace ComponentFactory.Krypton.Toolkit
{
	/// <summary>
	/// Implement storage for month calendar appearance states.
	/// </summary>
    public class PaletteMonthCalendarDoubleState : PaletteDouble
    {
        #region Instance Fields
        private PaletteTriple _paletteHeader;
        private PaletteTriple _paletteDay;
        private PaletteTriple _paletteDayOfWeek;
        #endregion

        #region Identity
        /// <summary>
        /// Initialize a new instance of the PaletteMonthCalendarDoubleState class.
		/// </summary>
        /// <param name="redirect">Inheritence redirection instance.</param>
        public PaletteMonthCalendarDoubleState(PaletteMonthCalendarRedirect redirect)
            : this(redirect, null)
        {
        }

        /// <summary>
        /// Initialize a new instance of the PaletteMonthCalendarDoubleState class.
		/// </summary>
        /// <param name="redirect">Inheritence redirection instance.</param>
        /// <param name="needPaint">Delegate for notifying paint requests.</param>
        public PaletteMonthCalendarDoubleState(PaletteMonthCalendarRedirect redirect,
                                               NeedPaintHandler needPaint)
            : base(redirect, needPaint)
		{
            _paletteHeader = new PaletteTriple(redirect.Header, needPaint);
            _paletteDay = new PaletteTriple(redirect.Day, needPaint);
            _paletteDayOfWeek = new PaletteTriple(redirect.DayOfWeek, needPaint);
        }
        #endregion

		#region IsDefault
		/// <summary>
		/// Gets a value indicating if all values are default.
		/// </summary>
		[Browsable(false)]
		public override bool IsDefault
		{
            get
            {
                return (base.IsDefault &&
                        _paletteHeader.IsDefault &&
                        _paletteDay.IsDefault &&
                        _paletteDayOfWeek.IsDefault);
            }
		}
		#endregion

        #region Header
        /// <summary>
        /// Gets access to the month/year header appearance entries.
        /// </summary>
        [Category("Visuals")]
        [Description("Overrides for defining month/year header appearance entries.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public PaletteTriple Header
        {
            get { return _paletteHeader; }
        }

        private bool ShouldSerializeHeader()
        {
            return !_paletteHeader.IsDefault;
        }
        #endregion

        #region Day
        /// <summary>
        /// Gets access to the day appearance entries.
        /// </summary>
        [Category("Visuals")]
        [Description("Overrides for defining day appearance entries.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public PaletteTriple Day
        {
            get { return _paletteDay; }
        }

        private bool ShouldSerializeDay()
        {
            return !_paletteDay.IsDefault;
        }
        #endregion

        #region DayOfWeek
        /// <summary>
        /// Gets access to the day of week appearance entries.
        /// </summary>
        [Category("Visuals")]
        [Description("Overrides for defining day of week appearance entries.")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public PaletteTriple DayOfWeek
        {
            get { return _paletteDayOfWeek; }
        }

        private bool ShouldSerializeDayOfWeek()
        {
            return !_paletteDayOfWeek.IsDefault;
        }
        #endregion
    }
}


text:
<?php

use Modules\Content\Support\Facades\PostType;
use Modules\Content\Support\Facades\TaxonomyType;

/**
 * Register the Taxonomy Types.
 */
TaxonomyType::register('category', array(
    'labels' => array(
        'name'        => __d('content', 'Category'),
        'title'       => __d('content', 'Categories'),

        'searchItems' => __d('content', 'Search Categories'),
        'allItems'    => __d('content', 'All Category'),

        'parentItem'      => __d('content', 'Parent Category'),
        'parentItemColon' => __d('content', 'Parent Category:'),

        'editItem'    => __d('content', 'Edit Category'),
        'updateItem'  => __d('content', 'Update Category'),
        'deleteItem'  => __d('content', 'Delete Category'),
        'addNewItem'  => __d('content', 'Add New Category'),
        'newItemName' => __d('content', 'New Category Name'),

        'menuName'    => __d('content', 'Categories'),
    ),

    'label'       => __d('content', 'posts'),
    'description' => __d('content', 'A type of hierarchical taxonomy.'),

    'hierarchical' => true,

    'rewrite' => array(
        'slug' => 'posts'
    ),
));

TaxonomyType::register('tag', array(
    'labels' => array(
        'name'        => __d('content', 'Tag'),
        'title'       => __d('content', 'Tags'),

        'searchItems' => __d('content', 'Search Tags'),
        'allItems'    => __d('content', 'All Tag'),

        'parentItem'      => null,
        'parentItemColon' => null,

        'editItem'    => __d('content', 'Edit Tag'),
        'updateItem'  => __d('content', 'Update Tag'),
        'deleteItem'  => __d('content', 'Delete Tag'),
        'addNewItem'  => __d('content', 'Add New Tag'),
        'newItemName' => __d('content', 'New Tag Name'),

        'menuName'    => __d('content', 'Tags'),
    ),

    'label'       => __d('content', 'tags'),
    'description' => __d('content', 'A type of non-hierarchical taxonomy.'),

    'hierarchical' => false,

    'rewrite' => array(
        'slug' => 'tags'
    ),
));

/**
 * Register the Post Types.
 */

PostType::register('post', array(
    'model' => 'Modules\Content\Models\Post',

    'view'  => 'Modules/Content::Content/Post',

    'labels' => array(
        'name'        => __d('content', 'Post'),
        'title'       => __d('content', 'Posts'),

        'searchItems' => __d('content', 'Search Posts'),
        'allItems'    => __d('content', 'All Posts'),
        'notFound'    => __d('content', 'No posts found'),

        'parentItem'      => null,
        'parentItemColon' => null,

        'addNew'      => __d('content', 'Add New'),
        'addNewItem'  => __d('content', 'Add New Post'),
        'editItem'    => __d('content', 'Edit Post'),
        'updateItem'  => __d('content', 'Update Post'),
        'deleteItem'  => __d('content', 'Delete Post'),
        'newItem'     => __d('content', 'New Post'),
        'viewItem'    => __d('content', 'View Post'),
    ),

    'label'       => __d('content', 'posts'),
    'description' => __d('content', 'A type of content for blogging, featuring categories, tags and comments.'),

    'public'       => true,
    'hierarchical' => false,
    'hasArchive'   => true,

    'rewrite' => array(
        'slug' => 'posts'
    ),
));

PostType::register('page', array(
    'model' => 'Modules\Content\Models\Page',

    'view'  => 'Modules/Content::Content/Page',

    'labels' => array(
        'name'        => __d('content', 'Page'),
        'title'       => __d('content', 'Pages'),

        'searchItems' => __d('content', 'Search Pages'),
        'allItems'    => __d('content', 'All Pages'),
        'notFound'    => __d('content', 'No pages found'),

        'parentItem'      => __d('content', 'Parent Page'),
        'parentItemColon' => __d('content', 'Parent Page:'),

        'addNew'      => __d('content', 'Add New'),
        'addNewItem'  => __d('content', 'Add New Page'),
        'editItem'    => __d('content', 'Edit Page'),
        'updateItem'  => __d('content', 'Update Page'),
        'deleteItem'  => __d('content', 'Delete Page'),
        'newItem'     => __d('content', 'New Page'),
        'viewItem'    => __d('content', 'View Page'),
    ),

    'label'       => __d('content', 'pages'),
    'description' => __d('content', 'A stand-alone page, optionally with menu items.'),

    'public'       => true,
    'hierarchical' => true,
    'hasArchive'   => false,

    'rewrite' => array(
        'slug' => 'pages'
    ),
));

PostType::register('block', array(
    'model' => 'Modules\Content\Models\Block',

    'view'  => null, // The Blocks are rendered via the Modules\Content\Widgets\BlockHandler.

    'labels' => array(
        'name'        => __d('content', 'Block'),
        'title'       => __d('content', 'Blocks'),

        'searchItems' => __d('content', 'Search Blocks'),
        'allItems'    => __d('content', 'All Blocks'),
        'notFound'    => __d('content', 'No blocks found'),

        'parentItem'      => null,
        'parentItemColon' => null,

        'addNew'      => __d('content', 'Add New'),
        'addNewItem'  => __d('content', 'Add New Block'),
        'editItem'    => __d('content', 'Edit Block'),
        'updateItem'  => __d('content', 'Update Block'),
        'deleteItem'  => __d('content', 'Delete Block'),
        'newItem'     => __d('content', 'New Block'),
        'viewItem'    => __d('content', 'View Block'),
    ),

    'label'       => __d('content', 'blocks'),
    'description' => __d('content', 'A content element which is displayed in one of the Widget Positions.'),

    'public'       => false,
    'hierarchical' => false,
    'hasArchive'   => false,

    'rewrite' => array(
        'slug' => 'blocks'
    ),
));


text:
namespace graphic
{

	//-----------------------------------------------------------------------------------------------
	class cTaskColladaLoader : public common::cTask
	{
	public:
		cTaskColladaLoader(int id, cRenderer *renderer, const StrPath &fileName)
			: cTask(id, "cTaskColladaLoader")
			, m_renderer(renderer)
			, m_fileName(fileName) {
		}
		virtual ~cTaskColladaLoader() {
		}

		virtual eRunResult::Enum Run()
		{
			const StrPath resourcePath = cResourceManager::Get()->GetResourceFilePath(m_fileName);
			if (resourcePath.empty())
				goto error;

			cColladaModel *model = new cColladaModel;
			if (!model->Create(*m_renderer, resourcePath))
				goto error;

			cResourceManager::Get()->InsertColladaModel(m_fileName, model);
			return eRunResult::END;

		error:
			dbg::ErrLog("Error cTaskColladaLoader %s \n", m_fileName.c_str());
			SAFE_DELETE(model);
			return eRunResult::END;
		}

		StrPath m_fileName;
		cRenderer *m_renderer;
	};

	//-----------------------------------------------------------------------------------------------
	class cTaskXFileLoader : public common::cTask
	{
	public:
		cTaskXFileLoader(int id, cRenderer *renderer, const StrPath &fileName)
			: cTask(id, "cTaskXFileLoader")
			, m_renderer(renderer)
			, m_fileName(fileName) {
		}
		virtual ~cTaskXFileLoader() {
		}

		virtual eRunResult::Enum Run()
		{
			const StrPath resourcePath = cResourceManager::Get()->GetResourceFilePath(m_fileName);
			if (resourcePath.empty())
				goto error;

			cXFileMesh *mesh = new cXFileMesh;
			if (!mesh->Create(*m_renderer, resourcePath, false, true))
				goto error;

			cResourceManager::Get()->InsertXFileModel(m_fileName, mesh);
			return eRunResult::END;

		error:
			dbg::ErrLog("Error cTaskXFileLoader %s \n", m_fileName.c_str());
			SAFE_DELETE(mesh);
			return eRunResult::END;
		}

		StrPath m_fileName;
		cRenderer *m_renderer;
	};

	//-----------------------------------------------------------------------------------------------
	class cTaskShadowLoader : public common::cTask
	{
	public:
		cTaskShadowLoader(int id, cRenderer *renderer
			, const StrPath &fileName
			, cColladaModel *colladaModel
			, cXFileMesh *xfile
		)
			: cTask(id, "cTaskShadowLoader")
			, m_renderer(renderer)
			, m_fileName(fileName)
			, m_colladaModel(colladaModel)
			, m_xfile(xfile) {
		}
		virtual ~cTaskShadowLoader() {
		}

		virtual eRunResult::Enum Run()
		{
			cShadowVolume *shadow = NULL;

			if (m_colladaModel)
			{
				shadow = new cShadowVolume();
				if (!m_colladaModel->m_meshes.empty())
				{
					cMesh2 *mesh = m_colladaModel->m_meshes[0];
					if (!shadow->Create(*m_renderer, mesh->m_buffers->m_vtxBuff, mesh->m_buffers->m_idxBuff))
					{
						SAFE_DELETE(shadow);
					}
				}
			}
			else if (m_xfile)
			{
				shadow = new cShadowVolume();
				if (!shadow->Create(*m_renderer, m_xfile->m_mesh, true))
				{
					SAFE_DELETE(shadow);
				}
			}

			if (shadow)
				cResourceManager::Get()->InsertShadow(m_fileName, shadow);

			return eRunResult::END;
		}

		StrPath m_fileName;
		cRenderer *m_renderer;
		cColladaModel *m_colladaModel;
		cXFileMesh *m_xfile;
	};

	//-----------------------------------------------------------------------------------------------
	class cTaskTextureLoader : public common::cTask
	{
	public:
		cTaskTextureLoader(int id, cRenderer *renderer, const StrPath &fileName, const bool isSizePow2)
			: cTask(id, "cTaskTextureLoader")
			, m_renderer(renderer)
			, m_isSizePow2(isSizePow2)
			, m_fileName(fileName) {
		}
		virtual ~cTaskTextureLoader() {
		}

		virtual eRunResult::Enum Run()
		{
			const StrPath resourcePath = cResourceManager::Get()->GetResourceFilePath(m_fileName);
			if (resourcePath.empty())
				goto error;

			cTexture *texture = new cTexture();
			if (!texture->Create(*m_renderer, resourcePath, m_isSizePow2))
			{
				if (resourcePath == g_defaultTexture) // this file must loaded
				{
					assert(0);
					goto error;
				}
			}

			if (texture && texture->IsLoaded())
			{
				cResourceManager::Get()->InsertTexture(m_fileName, texture);
				return eRunResult::END;
			}
			else
			{
				cResourceManager::Get()->InsertTexture(m_fileName,
					cResourceManager::Get()->LoadTexture(*m_renderer, g_defaultTexture, m_isSizePow2, false));
			}

		error:
			dbg::ErrLog("Error cTaskTextureLoader %s \n", m_fileName.c_str());
			SAFE_DELETE(texture);
			return eRunResult::END;
		}

		StrPath m_fileName;
		bool m_isSizePow2;
		cRenderer *m_renderer;
	};

}


text:
@implementation VOKManagedObjectMap

+ (instancetype)mapWithForeignKeyPath:(NSString *)inputKeyPath coreDataKey:(NSString *)coreDataKey
{
    return [self mapWithForeignKeyPath:inputKeyPath coreDataKey:coreDataKey dateFormatter:[self vok_defaultDateFormatter]];
}

+ (instancetype)mapWithForeignKeyPath:(NSString *)inputKeyPath
                          coreDataKey:(NSString *)coreDataKey
                        dateFormatter:(NSDateFormatter *)dateFormatter
{
    VOKManagedObjectMap *map = [[self alloc] init];
    map.inputKeyPath = inputKeyPath;
    map.coreDataKey = coreDataKey;
    map.dateFormatter = dateFormatter;
    return map;
}

+ (instancetype)mapWithForeignKeyPath:(NSString *)inputKeyPath
                          coreDataKey:(NSString *)coreDataKey
                      numberFormatter:(NSNumberFormatter *)numberFormatter
{
    VOKManagedObjectMap *map = [[self alloc] init];
    map.inputKeyPath = inputKeyPath;
    map.coreDataKey = coreDataKey;
    map.numberFormatter = numberFormatter;
    return map;
}

+ (NSArray *)mapsFromDictionary:(NSDictionary *)mapDict
{
    NSMutableArray *mapArray = [NSMutableArray array];

    [mapDict enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        //key = input key, obj = core data key
        [mapArray addObject:[self mapWithForeignKeyPath:key coreDataKey:obj]];
    }];

    return [mapArray copy];
}

+ (NSDateFormatter *)vok_defaultDateFormatter
{
    static dispatch_once_t pred = 0;
    static NSDateFormatter *DefaultDateFormatter;
    dispatch_once(&pred, ^{
        DefaultDateFormatter = [NSDateFormatter new];
        DefaultDateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'";
        DefaultDateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    });

    return DefaultDateFormatter;
}

+ (NSDateFormatter *)vok_dateFormatterWithoutMicroseconds
{
    static dispatch_once_t formatter_dispatch_token = 0;
    static NSDateFormatter *DateFormatterWithoutMicroseconds;
    dispatch_once(&formatter_dispatch_token, ^{
        DateFormatterWithoutMicroseconds = [NSDateFormatter new];
        DateFormatterWithoutMicroseconds.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss'Z'";
        DateFormatterWithoutMicroseconds.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    });

    return DateFormatterWithoutMicroseconds;
}

+ (NSNumberFormatter *)vok_defaultNumberFormatter
{
    static NSNumberFormatter *NumberFormatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NumberFormatter = [NSNumberFormatter new];
    });

    return NumberFormatter;
}

#pragma mark - Description

- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p>\nCore Data Key : %@\nForeign Key : %@",
            NSStringFromClass([self class]), self, self.coreDataKey, self.inputKeyPath];
}

@end