text:
from rapidsms.contrib.locations.models import Location
from survey.features.page_objects.base import PageObject
from survey.investigator_configs import MONTHS
from survey.models import EnumerationArea
from survey.models.investigator import Investigator
from lettuce.django import django_url

class NewHouseholdPage(PageObject):
    url = "/households/new/"

    def valid_page(self):
        fields = ['investigator', 'surname', 'first_name', 'male', 'date_of_birth', 'occupation',
                  'level_of_education', 'resident_since_month', 'resident_since_year']
        fields += ['uid']
        for field in fields:
            assert self.browser.is_element_present_by_name(field)

    def get_household_values(self):
        return self.values

    def fill_valid_values(self, values, ea=None):
        kampala = Location.objects.get(name="Kampala")
        kampala_county = Location.objects.get(name="Kampala County")
        kampala_subcounty = Location.objects.get(name="Subcounty")
        kampala_parish = Location.objects.get(name="Parish")
        kampala_village = Location.objects.get(name="Village")
        self.fill_in_with_js('$("#location-district")', kampala.id)
        self.fill_in_with_js('$("#location-county")', kampala_county.id)
        self.fill_in_with_js('$("#location-subcounty")', kampala_subcounty.id)
        self.fill_in_with_js('$("#location-parish")', kampala_parish.id)
        self.fill_in_with_js('$("#location-village")', kampala_village.id)
        self.fill_in_with_js('$("#widget_ea")', ea.id)

        investigator = Investigator.objects.get(name="Investigator name")
        self.fill_in_with_js('$("#household-investigator")', investigator.id)
        self.fill_in_with_js('$("#household-extra_resident_since_year")', 1984)
        self.fill_in_with_js('$("#household-extra_resident_since_month")', 1)
        self.values = values
        self.browser.fill_form(self.values)

    def validate_household_created(self):
        assert self.browser.is_text_present("Household successfully registered.")

    def has_children(self, value):
        self.choose_radio('has_children', value)

    def are_children_fields_disabled(self, is_disabled=True):
        for element_id in ['aged_between_5_12_years', 'aged_between_13_17_years']:
            element_id = 'household-children-' + element_id
            assert self.is_disabled(element_id) == is_disabled
        self.are_children_below_5_fields_disabled(is_disabled=is_disabled)

    def is_no_below_5_checked(self):
        assert self.browser.find_by_id('household-children-has_children_below_5_1').selected == True

    def cannot_say_yes_to_below_5(self):
        assert self.is_disabled("household-children-has_children_below_5_0") == True
        self.are_children_fields_disabled()

    def has_children_below_5(self, value):
        self.choose_radio('has_children_below_5', value)

    def are_children_below_5_fields_disabled(self, is_disabled=True):
        for element_id in ['aged_between_0_5_months', 'aged_between_6_11_months', 'aged_between_12_23_months',
                           'aged_between_24_59_months']:
            element_id = 'household-children-' + element_id
            assert self.is_disabled(element_id) == is_disabled

    def has_women(self, value):
        self.choose_radio('has_women', value)

    def are_women_fields_disabled(self, is_disabled=True):
        for element_id in ['aged_between_15_19_years', 'aged_between_20_49_years']:
            element_id = 'household-women-' + element_id
            assert self.is_disabled(element_id) == is_disabled

    def fill_in_number_of_females_lower_than_sum_of_15_19_and_20_49(self):
        self.browser.fill('number_of_females', '1')
        self.browser.fill('aged_between_15_19_years', '2')
        self.browser.fill('aged_between_20_49_years', '3')

    def see_an_error_on_number_of_females(self):
        self.is_text_present(
            'Please enter a value that is greater or equal to the total number of women above 15 years age.')

    def choose_occupation(self, occupation_value):
        self.browser.select('occupation', occupation_value)

    def is_specify_visible(self, status=True):
        extra = self.browser.find_by_css('#extra-occupation-field')
        if status:
            assert len(extra) == 1
        else:
            assert len(extra) == 0

class HouseholdDetailsPage(PageObject):
    def __init__(self, browser, household):
        super(HouseholdDetailsPage, self).__init__(browser)
        self.browser = browser
        self.household = household
        self.url = '/households/' + str(household.id) + '/'

    def validate_household_details(self):
        household_head = self.household.get_head()
        details = {
            'Family Name': household_head.surname,
            'Other Names': household_head.first_name,
            'Age': str(household_head.get_age()),
            'Gender': 'Male' if household_head.male else 'Female',
            'Occupation / Main Livelihood': household_head.occupation,
            'Highest level of education completed': household_head.level_of_education,
            'Since when have you lived here': str(household_head.resident_since_year),
            }
        for label, text in details.items():
            self.is_text_present(label)
            self.is_text_present(text)
        self.is_text_present(MONTHS[household_head.resident_since_month][1])

    def validate_household_member_details_table_headings(self):
        member_details_headings =['Family Name', 'Date of birth', 'Sex']
        for heading in member_details_headings:
            self.is_text_present(heading)

    def validate_household_member_details_values(self):
        for member in self.household.household_member.all():
            for detail in [member.surname, member.date_of_birth.strftime('%b %d, %Y'), 'Male' if member.male else 'Female']:
                self.is_text_present(str(detail))

    def validate_household_member_details(self):
        self.validate_household_member_details_table_headings()
        self.validate_household_member_details_values()

    def validate_household_member_title_and_add_household_member_link(self):
        self.is_text_present('Household Members:')
        self.browser.find_link_by_text('Add Member')

    def validate_actions_edit_and_delete_member(self):
        self.browser.find_link_by_text('Edit')
        self.browser.find_link_by_text('Delete')

    def click_delete_link(self, member_id):
        self.browser.click_link_by_partial_href("#delete_member_%d"%member_id)

class HouseholdsListPage(PageObject):
    url = '/households/'

    def validate_fields(self):
        self.validate_fields_present(["Households List", "Household ID", "Household Head",
        "District","County", "Sub County", "Parish", "Village", "Investigator"])

    def validate_pagination(self):
        self.browser.click_link_by_text("2")

    def no_registered_huseholds(self):
        self.browser.is_text_present('There are  no households currently registered  for this country.')

class EditHouseholdsPage(PageObject):
    def __init__(self, browser, household):
        self.browser = browser
        self.household = household
        self.url = '/households/%s/edit/' %  str(household.id)


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

namespace AssetStudio
{
    public class HumanPoseMask
    {
        public uint word0;
        public uint word1;
        public uint word2;

        public HumanPoseMask(ObjectReader reader)
        {
            var version = reader.version;

            word0 = reader.ReadUInt32();
            word1 = reader.ReadUInt32();
            if (version[0] > 5 || (version[0] == 5 && version[1] >= 2)) //5.2 and up
            {
                word2 = reader.ReadUInt32();
            }
        }
    }

    public class SkeletonMaskElement
    {
        public uint m_PathHash;
        public float m_Weight;

        public SkeletonMaskElement(ObjectReader reader)
        {
            m_PathHash = reader.ReadUInt32();
            m_Weight = reader.ReadSingle();
        }
    }

    public class SkeletonMask
    {
        public SkeletonMaskElement[] m_Data;

        public SkeletonMask(ObjectReader reader)
        {
            int numElements = reader.ReadInt32();
            m_Data = new SkeletonMaskElement[numElements];
            for (int i = 0; i < numElements; i++)
            {
                m_Data[i] = new SkeletonMaskElement(reader);
            }
        }
    }

    public class LayerConstant
    {
        public uint m_StateMachineIndex;
        public uint m_StateMachineMotionSetIndex;
        public HumanPoseMask m_BodyMask;
        public SkeletonMask m_SkeletonMask;
        public uint m_Binding;
        public int m_LayerBlendingMode;
        public float m_DefaultWeight;
        public bool m_IKPass;
        public bool m_SyncedLayerAffectsTiming;

        public LayerConstant(ObjectReader reader)
        {
            var version = reader.version;

            m_StateMachineIndex = reader.ReadUInt32();
            m_StateMachineMotionSetIndex = reader.ReadUInt32();
            m_BodyMask = new HumanPoseMask(reader);
            m_SkeletonMask = new SkeletonMask(reader);
            m_Binding = reader.ReadUInt32();
            m_LayerBlendingMode = reader.ReadInt32();
            if (version[0] > 4 || (version[0] == 4 && version[1] >= 2)) //4.2 and up
            {
                m_DefaultWeight = reader.ReadSingle();
            }
            m_IKPass = reader.ReadBoolean();
            if (version[0] > 4 || (version[0] == 4 && version[1] >= 2)) //4.2 and up
            {
                m_SyncedLayerAffectsTiming = reader.ReadBoolean();
            }
            reader.AlignStream();
        }
    }

    public class ConditionConstant
    {
        public uint m_ConditionMode;
        public uint m_EventID;
        public float m_EventThreshold;
        public float m_ExitTime;

        public ConditionConstant(ObjectReader reader)
        {
            m_ConditionMode = reader.ReadUInt32();
            m_EventID = reader.ReadUInt32();
            m_EventThreshold = reader.ReadSingle();
            m_ExitTime = reader.ReadSingle();
        }
    }

    public class TransitionConstant
    {
        public ConditionConstant[] m_ConditionConstantArray;
        public uint m_DestinationState;
        public uint m_FullPathID;
        public uint m_ID;
        public uint m_UserID;
        public float m_TransitionDuration;
        public float m_TransitionOffset;
        public float m_ExitTime;
        public bool m_HasExitTime;
        public bool m_HasFixedDuration;
        public int m_InterruptionSource;
        public bool m_OrderedInterruption;
        public bool m_Atomic;
        public bool m_CanTransitionToSelf;

        public TransitionConstant(ObjectReader reader)
        {
            var version = reader.version;

            int numConditions = reader.ReadInt32();
            m_ConditionConstantArray = new ConditionConstant[numConditions];
            for (int i = 0; i < numConditions; i++)
            {
                m_ConditionConstantArray[i] = new ConditionConstant(reader);
            }

            m_DestinationState = reader.ReadUInt32();
            if (version[0] >= 5) //5.0 and up
            {
                m_FullPathID = reader.ReadUInt32();
            }

            m_ID = reader.ReadUInt32();
            m_UserID = reader.ReadUInt32();
            m_TransitionDuration = reader.ReadSingle();
            m_TransitionOffset = reader.ReadSingle();
            if (version[0] >= 5) //5.0 and up
            {
                m_ExitTime = reader.ReadSingle();
                m_HasExitTime = reader.ReadBoolean();
                m_HasFixedDuration = reader.ReadBoolean();
                reader.AlignStream();
                m_InterruptionSource = reader.ReadInt32();
                m_OrderedInterruption = reader.ReadBoolean();
            }
            else
            {
                m_Atomic = reader.ReadBoolean();
            }

            if (version[0] > 4 || (version[0] == 4 && version[1] >= 5)) //4.5 and up
            {
                m_CanTransitionToSelf = reader.ReadBoolean();
            }

            reader.AlignStream();
        }
    }

    public class LeafInfoConstant
    {
        public uint[] m_IDArray;
        public uint m_IndexOffset;

        public LeafInfoConstant(ObjectReader reader)
        {
            m_IDArray = reader.ReadUInt32Array();
            m_IndexOffset = reader.ReadUInt32();
        }
    }

    public class MotionNeighborList
    {
        public uint[] m_NeighborArray;

        public MotionNeighborList(ObjectReader reader)
        {
            m_NeighborArray = reader.ReadUInt32Array();
        }
    }

    public class Blend2dDataConstant
    {
        public Vector2[] m_ChildPositionArray;
        public float[] m_ChildMagnitudeArray;
        public Vector2[] m_ChildPairVectorArray;
        public float[] m_ChildPairAvgMagInvArray;
        public MotionNeighborList[] m_ChildNeighborListArray;

        public Blend2dDataConstant(ObjectReader reader)
        {
            m_ChildPositionArray = reader.ReadVector2Array();
            m_ChildMagnitudeArray = reader.ReadSingleArray();
            m_ChildPairVectorArray = reader.ReadVector2Array();
            m_ChildPairAvgMagInvArray = reader.ReadSingleArray();

            int numNeighbours = reader.ReadInt32();
            m_ChildNeighborListArray = new MotionNeighborList[numNeighbours];
            for (int i = 0; i < numNeighbours; i++)
            {
                m_ChildNeighborListArray[i] = new MotionNeighborList(reader);
            }
        }
    }

    public class Blend1dDataConstant // wrong labeled
    {
        public float[] m_ChildThresholdArray;

        public Blend1dDataConstant(ObjectReader reader)
        {
            m_ChildThresholdArray = reader.ReadSingleArray();
        }
    }

    public class BlendDirectDataConstant
    {
        public uint[] m_ChildBlendEventIDArray;
        public bool m_NormalizedBlendValues;

        public BlendDirectDataConstant(ObjectReader reader)
        {
            m_ChildBlendEventIDArray = reader.ReadUInt32Array();
            m_NormalizedBlendValues = reader.ReadBoolean();
            reader.AlignStream();
        }
    }

    public class BlendTreeNodeConstant
    {
        public uint m_BlendType;
        public uint m_BlendEventID;
        public uint m_BlendEventYID;
        public uint[] m_ChildIndices;
        public float[] m_ChildThresholdArray;
        public Blend1dDataConstant m_Blend1dData;
        public Blend2dDataConstant m_Blend2dData;
        public BlendDirectDataConstant m_BlendDirectData;
        public uint m_ClipID;
        public uint m_ClipIndex;
        public float m_Duration;
        public float m_CycleOffset;
        public bool m_Mirror;

        public BlendTreeNodeConstant(ObjectReader reader)
        {
            var version = reader.version;

            if (version[0] > 4 || (version[0] == 4 && version[1] >= 1)) //4.1 and up
            {
                m_BlendType = reader.ReadUInt32();
            }
            m_BlendEventID = reader.ReadUInt32();
            if (version[0] > 4 || (version[0] == 4 && version[1] >= 1)) //4.1 and up
            {
                m_BlendEventYID = reader.ReadUInt32();
            }
            m_ChildIndices = reader.ReadUInt32Array();
            if (version[0] < 4 || (version[0] == 4 && version[1] < 1)) //4.1 down
            {
                m_ChildThresholdArray = reader.ReadSingleArray();
            }

            if (version[0] > 4 || (version[0] == 4 && version[1] >= 1)) //4.1 and up
            {
                m_Blend1dData = new Blend1dDataConstant(reader);
                m_Blend2dData = new Blend2dDataConstant(reader);
            }

            if (version[0] >= 5) //5.0 and up
            {
                m_BlendDirectData = new BlendDirectDataConstant(reader);
            }

            m_ClipID = reader.ReadUInt32();
            if (version[0] == 4 && version[1] >= 5) //4.5 - 5.0
            {
                m_ClipIndex = reader.ReadUInt32();
            }

            m_Duration = reader.ReadSingle();

            if (version[0] > 4
                || (version[0] == 4 && version[1] > 1)
                || (version[0] == 4 && version[1] == 1 && version[2] >= 3)) //4.1.3 and up
            {
                m_CycleOffset = reader.ReadSingle();
                m_Mirror = reader.ReadBoolean();
                reader.AlignStream();
            }
        }
    }

    public class BlendTreeConstant
    {
        public BlendTreeNodeConstant[] m_NodeArray;
        public ValueArrayConstant m_BlendEventArrayConstant;

        public BlendTreeConstant(ObjectReader reader)
        {
            var version = reader.version;

            int numNodes = reader.ReadInt32();
            m_NodeArray = new BlendTreeNodeConstant[numNodes];
            for (int i = 0; i < numNodes; i++)
            {
                m_NodeArray[i] = new BlendTreeNodeConstant(reader);
            }

            if (version[0] < 4 || (version[0] == 4 && version[1] < 5)) //4.5 down
            {
                m_BlendEventArrayConstant = new ValueArrayConstant(reader);
            }
        }
    }

    public class StateConstant
    {
        public TransitionConstant[] m_TransitionConstantArray;
        public int[] m_BlendTreeConstantIndexArray;
        public LeafInfoConstant[] m_LeafInfoArray;
        public BlendTreeConstant[] m_BlendTreeConstantArray;
        public uint m_NameID;
        public uint m_PathID;
        public uint m_FullPathID;
        public uint m_TagID;
        public uint m_SpeedParamID;
        public uint m_MirrorParamID;
        public uint m_CycleOffsetParamID;
        public float m_Speed;
        public float m_CycleOffset;
        public bool m_IKOnFeet;
        public bool m_WriteDefaultValues;
        public bool m_Loop;
        public bool m_Mirror;

        public StateConstant(ObjectReader reader)
        {
            var version = reader.version;

            int numTransistions = reader.ReadInt32();
            m_TransitionConstantArray = new TransitionConstant[numTransistions];
            for (int i = 0; i < numTransistions; i++)
            {
                m_TransitionConstantArray[i] = new TransitionConstant(reader);
            }

            m_BlendTreeConstantIndexArray = reader.ReadInt32Array();

            if (version[0] < 5 || (version[0] == 5 && version[1] < 2)) //5.2 down
            {
                int numInfos = reader.ReadInt32();
                m_LeafInfoArray = new LeafInfoConstant[numInfos];
                for (int i = 0; i < numInfos; i++)
                {
                    m_LeafInfoArray[i] = new LeafInfoConstant(reader);
                }
            }

            int numBlends = reader.ReadInt32();
            m_BlendTreeConstantArray = new BlendTreeConstant[numBlends];
            for (int i = 0; i < numBlends; i++)
            {
                m_BlendTreeConstantArray[i] = new BlendTreeConstant(reader);
            }

            m_NameID = reader.ReadUInt32();
            if (version[0] > 4 || (version[0] == 4 && version[1] >= 3)) //4.3 and up
            {
                m_PathID = reader.ReadUInt32();
            }
            if (version[0] >= 5) //5.0 and up
            {
                m_FullPathID = reader.ReadUInt32();
            }

            m_TagID = reader.ReadUInt32();
            if (version[0] > 5 || (version[0] == 5 && version[1] >= 1)) //5.1 and up
            {
                m_SpeedParamID = reader.ReadUInt32();
                m_MirrorParamID = reader.ReadUInt32();
                m_CycleOffsetParamID = reader.ReadUInt32();
            }

            if (version[0] > 2017 || (version[0] == 2017 && version[1] >= 2)) //2017.2 and up
            {
                var m_TimeParamID = reader.ReadUInt32();
            }

            m_Speed = reader.ReadSingle();
            if (version[0] > 4 || (version[0] == 4 && version[1] >= 1)) //4.1 and up
            {
                m_CycleOffset = reader.ReadSingle();
            }
            m_IKOnFeet = reader.ReadBoolean();
            if (version[0] >= 5) //5.0 and up
            {
                m_WriteDefaultValues = reader.ReadBoolean();
            }

            m_Loop = reader.ReadBoolean();
            if (version[0] > 4 || (version[0] == 4 && version[1] >= 1)) //4.1 and up
            {
                m_Mirror = reader.ReadBoolean();
            }

            reader.AlignStream();
        }
    }

    public class SelectorTransitionConstant
    {
        public uint m_Destination;
        public ConditionConstant[] m_ConditionConstantArray;

        public SelectorTransitionConstant(ObjectReader reader)
        {
            m_Destination = reader.ReadUInt32();

            int numConditions = reader.ReadInt32();
            m_ConditionConstantArray = new ConditionConstant[numConditions];
            for (int i = 0; i < numConditions; i++)
            {
                m_ConditionConstantArray[i] = new ConditionConstant(reader);
            }
        }
    }

    public class SelectorStateConstant
    {
        public SelectorTransitionConstant[] m_TransitionConstantArray;
        public uint m_FullPathID;
        public bool m_isEntry;

        public SelectorStateConstant(ObjectReader reader)
        {
            int numTransitions = reader.ReadInt32();
            m_TransitionConstantArray = new SelectorTransitionConstant[numTransitions];
            for (int i = 0; i < numTransitions; i++)
            {
                m_TransitionConstantArray[i] = new SelectorTransitionConstant(reader);
            }

            m_FullPathID = reader.ReadUInt32();
            m_isEntry = reader.ReadBoolean();
            reader.AlignStream();
        }
    }

    public class StateMachineConstant
    {
        public StateConstant[] m_StateConstantArray;
        public TransitionConstant[] m_AnyStateTransitionConstantArray;
        public SelectorStateConstant[] m_SelectorStateConstantArray;
        public uint m_DefaultState;
        public uint m_MotionSetCount;

        public StateMachineConstant(ObjectReader reader)
        {
            var version = reader.version;

            int numStates = reader.ReadInt32();
            m_StateConstantArray = new StateConstant[numStates];
            for (int i = 0; i < numStates; i++)
            {
                m_StateConstantArray[i] = new StateConstant(reader);
            }

            int numAnyStates = reader.ReadInt32();
            m_AnyStateTransitionConstantArray = new TransitionConstant[numAnyStates];
            for (int i = 0; i < numAnyStates; i++)
            {
                m_AnyStateTransitionConstantArray[i] = new TransitionConstant(reader);
            }

            if (version[0] >= 5) //5.0 and up
            {
                int numSelectors = reader.ReadInt32();
                m_SelectorStateConstantArray = new SelectorStateConstant[numSelectors];
                for (int i = 0; i < numSelectors; i++)
                {
                    m_SelectorStateConstantArray[i] = new SelectorStateConstant(reader);
                }
            }

            m_DefaultState = reader.ReadUInt32();
            m_MotionSetCount = reader.ReadUInt32();
        }
    }

    public class ValueArray
    {
        public bool[] m_BoolValues;
        public int[] m_IntValues;
        public float[] m_FloatValues;
        public Vector4[] m_VectorValues;
        public Vector3[] m_PositionValues;
        public Vector4[] m_QuaternionValues;
        public Vector3[] m_ScaleValues;

        public ValueArray(ObjectReader reader)
        {
            var version = reader.version;

            if (version[0] < 5 || (version[0] == 5 && version[1] < 5)) //5.5 down
            {
                m_BoolValues = reader.ReadBooleanArray();
                reader.AlignStream();
                m_IntValues = reader.ReadInt32Array();
                m_FloatValues = reader.ReadSingleArray();
            }

            if (version[0] < 4 || (version[0] == 4 && version[1] < 3)) //4.3 down
            {
                m_VectorValues = reader.ReadVector4Array();
            }
            else
            {
                int numPosValues = reader.ReadInt32();
                m_PositionValues = new Vector3[numPosValues];
                for (int i = 0; i < numPosValues; i++)
                {
                    m_PositionValues[i] = version[0] > 5 || (version[0] == 5 && version[1] >= 4) ? reader.ReadVector3() : (Vector3)reader.ReadVector4(); //5.4 and up
                }

                m_QuaternionValues = reader.ReadVector4Array();

                int numScaleValues = reader.ReadInt32();
                m_ScaleValues = new Vector3[numScaleValues];
                for (int i = 0; i < numScaleValues; i++)
                {
                    m_ScaleValues[i] = version[0] > 5 || (version[0] == 5 && version[1] >= 4) ? reader.ReadVector3() : (Vector3)reader.ReadVector4(); //5.4 and up
                }

                if (version[0] > 5 || (version[0] == 5 && version[1] >= 5)) //5.5 and up
                {
                    m_FloatValues = reader.ReadSingleArray();
                    m_IntValues = reader.ReadInt32Array();
                    m_BoolValues = reader.ReadBooleanArray();
                    reader.AlignStream();
                }
            }
        }
    }

    public class ControllerConstant
    {
        public LayerConstant[] m_LayerArray;
        public StateMachineConstant[] m_StateMachineArray;
        public ValueArrayConstant m_Values;
        public ValueArray m_DefaultValues;

        public ControllerConstant(ObjectReader reader)
        {
            int numLayers = reader.ReadInt32();
            m_LayerArray = new LayerConstant[numLayers];
            for (int i = 0; i < numLayers; i++)
            {
                m_LayerArray[i] = new LayerConstant(reader);
            }

            int numStates = reader.ReadInt32();
            m_StateMachineArray = new StateMachineConstant[numStates];
            for (int i = 0; i < numStates; i++)
            {
                m_StateMachineArray[i] = new StateMachineConstant(reader);
            }

            m_Values = new ValueArrayConstant(reader);
            m_DefaultValues = new ValueArray(reader);
        }
    }

    public sealed class AnimatorController : RuntimeAnimatorController
    {
        public PPtr<AnimationClip>[] m_AnimationClips;

        public AnimatorController(ObjectReader reader) : base(reader)
        {
            var m_ControllerSize = reader.ReadUInt32();
            var m_Controller = new ControllerConstant(reader);

            int tosSize = reader.ReadInt32();
            var m_TOS = new KeyValuePair<uint, string>[tosSize];
            for (int i = 0; i < tosSize; i++)
            {
                m_TOS[i] = new KeyValuePair<uint, string>(reader.ReadUInt32(), reader.ReadAlignedString());
            }

            int numClips = reader.ReadInt32();
            m_AnimationClips = new PPtr<AnimationClip>[numClips];
            for (int i = 0; i < numClips; i++)
            {
                m_AnimationClips[i] = new PPtr<AnimationClip>(reader);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.ning.http.client.providers.netty;

import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.async.HostnameVerifierTest;
import com.ning.http.client.async.ProviderUtil;

public class NettyHostnameVerifierTest extends HostnameVerifierTest {

    @Override
    public AsyncHttpClient getAsyncHttpClient(AsyncHttpClientConfig config) {
        return ProviderUtil.nettyProvider(config);
    }
}


text:
@interface ImageViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *pageLabel;

-(IBAction)toPrevImage:(id)sender;
-(IBAction)toNextImage:(id)sender;

-(IBAction)randomAudio:(id)sender;
-(IBAction)playAudio:(id)sender;
-(IBAction)stopAudio:(id)sender;
-(IBAction)pauseAudio:(id)sender;

@end


text:
rm -f Bug.txt

echo

echo "Examining performance of Wagner's MersenneTwister.h C++ class..."

# Extract the various distribution series from each generator's output

for NAME in *.out; do
	BASE=`basename $NAME .out`
	grep -A 200 "integer generation:" $NAME | tail -200 > $BASE.integer.tmp
	grep -A 200 -F "[0,1) generation:" $NAME | tail -200 > $BASE.exclusive.tmp
	grep -A 400 -F "[0,1] generation:" $NAME | tail -400 > $BASE.inclusive.tmp
done

# Compare the output to the inventors' reference output

rm -f *.reference.tmp
for NAME in *.out; do
	BASE=`basename $NAME .out`
	diff --brief $BASE.integer.tmp Reference.integer.tmp >> $BASE.reference.tmp
	diff --brief $BASE.exclusive.tmp Reference.exclusive.tmp >> $BASE.reference.tmp
	diff --brief $BASE.inclusive.tmp Reference.inclusive.tmp >> $BASE.reference.tmp
done

# Look for an available awk command

if which awk &> /dev/null
then
	AWK=awk
elif which gawk &> /dev/null
then
	AWK=gawk
elif which nawk &> /dev/null
then
	AWK=nawk
fi

# Report comparison test results

if [ $AWK ]; then
	echo
	echo "Comparison of integer generation rate with other versions:"

	printf "  This version                 "
	if [ -s Wagner.out ]; then
		$AWK '/Time elapsed/{ printf( "%6.1f million per second", 1000 / $4 ) }' Wagner.out
		if [ -s Wagner.reference.tmp ]; then
			printf " (non-conforming)\n"
		else
			printf "\n"
		fi
	else
		printf "       Failed to run\n"
	fi

	printf "  Inventors' version           "
	if [ -s Original.out ]; then
		$AWK '/Time elapsed/{ printf( "%6.1f million per second", 1000 / $4 ) }' Original.out
		if [ -s Original.reference.tmp ]; then
			printf " (non-conforming)\n"
		else
			printf "\n"
		fi
	else
		printf "       Failed to run\n"
	fi

	printf "  Bedaux's version             "
	if [ -s Bedaux.out ]; then
		$AWK '/Time elapsed/{ printf( "%6.1f million per second", 1000 / $4 ) }' Bedaux.out
		if [ -s Bedaux.reference.tmp ]; then
			printf " (non-conforming)\n"
		else
			printf "\n"
		fi
	else
		printf "       Failed to run\n"
	fi

	printf "  Blevins's version            "
	if [ -s Blevins.out ]; then
		$AWK '/Time elapsed/{ printf( "%6.1f million per second", 1000 / $4 ) }' Blevins.out
		if [ -s Blevins.reference.tmp ]; then
			printf " (non-conforming)\n"
		else
			printf "\n"
		fi
	else
		printf "       Failed to run\n"
	fi

	printf "  Cokus's version              "
	if [ -s Cokus.out ]; then
		$AWK '/Time elapsed/{ printf( "%6.1f million per second", 1000 / $4 ) }' Cokus.out
		if [ -s Cokus.reference.tmp ]; then
			printf " (non-conforming)\n"
		else
			printf "\n"
		fi
	else
		printf "       Failed to run\n"
	fi

	printf "  Kuenning's version           "
	if [ -s Kuenning.out ]; then
		$AWK '/Time elapsed/{ printf( "%6.1f million per second", 1000 / $4 ) }' Kuenning.out
		if [ -s Kuenning.reference.tmp ]; then
			printf " (non-conforming)\n"
		else
			printf "\n"
		fi
	else
		printf "       Failed to run\n"
	fi

	printf "  Ladd's version               "
	if [ -s Ladd.out ]; then
		$AWK '/Time elapsed/{ printf( "%6.1f million per second", 1000 / $4 ) }' Ladd.out
		if [ -s Ladd.reference.tmp ]; then
			printf " (non-conforming)\n"
		else
			printf "\n"
		fi
	else
		printf "       Failed to run\n"
	fi

	printf "  Yang's version               "
	if [ -s Yang.out ]; then
		$AWK '/Time elapsed/{ printf( "%6.1f million per second", 1000 / $4 ) }' Yang.out
		if [ -s Yang.reference.tmp ]; then
			printf " (non-conforming)\n"
		else
			printf "\n"
		fi
	else
		printf "       Failed to run\n"
	fi

	printf "  Built-in rand()              "
	if [ -s Standard.out ]; then
		$AWK '/Time elapsed/{ printf( "%6.1f million per second", 1000 / $4 ) }' Standard.out
		if [ -s Standard.reference.tmp ]; then
			printf " (non-conforming)\n"
		else
			printf "\n"
		fi
	else
		printf "       Failed to run\n"
	fi
fi

# Report own performance test results

echo

grep -A 100 "Test of generation rates in various distributions:" Wagner.out

# Summarize results

echo

grep "Error" Wagner.out >> Wagner.error.tmp

if [ -s Wagner.reference.tmp ] && ![ -s Wagner.error.tmp ]; then
	cat Wagner.out Original.out Cokus.out > Bug.txt
	echo "Failed tests - MersenneTwister.h generated incorrect output"
	echo "Results have been written to a file called 'Bug.txt'"
	echo "Please send a copy of 'Bug.txt' and system info to wagnerr@umich.edu"
else
	echo "MersenneTwister.h passed all tests"
fi

rm -f *.tmp

exit 0


text:
import Immutable from 'seamless-immutable';

import types from '../../constants/ActionTypes';

const initialState = Immutable({
  token: null,
  userId: null,
});

function authReducer(state = initialState, action) {
  switch (action.type) {
    case types.API.AUTH_GET_SUCCESS: {
      return { ...initialState, ...action.payload.auth };
    }

    case types.API.RESERVATION_DELETE_ERROR:
    case types.API.RESERVATION_PUT_ERROR:
    case types.API.RESERVATION_POST_ERROR: {
      if (action.payload.status === 401) {
        return initialState;
      }
      return state;
    }

    default: {
      return state;
    }
  }
}

export default authReducer;


text:
/*
 * Created with JetBrains PhpStorm.
 * User: campaign
 * Date: 10/8/13
 * Time: 6:15 PM
 * To change this template use File | Settings | File Templates.
 */
UE.plugin = function(){
    var _plugins = {};
    return {
        register : function(pluginName,fn,oldOptionName,afterDisabled){
            if(oldOptionName && utils.isFunction(oldOptionName)){
                afterDisabled = oldOptionName;
                oldOptionName = null
            }
            _plugins[pluginName] = {
                optionName : oldOptionName || pluginName,
                execFn : fn,
                //当插件被禁用时执行
                afterDisabled : afterDisabled
            }
        },
        load : function(editor){
            utils.each(_plugins,function(plugin){
                var _export = plugin.execFn.call(editor);
                if(editor.options[plugin.optionName] !== false){
                    if(_export){
                        //后边需要再做扩展
                        utils.each(_export,function(v,k){
                            switch(k.toLowerCase()){
                                case 'shortcutkey':
                                    editor.addshortcutkey(v);
                                    break;
                                case 'bindevents':
                                    utils.each(v,function(fn,eventName){
                                        editor.addListener(eventName,fn);
                                    });
                                    break;
                                case 'bindmultievents':
                                    utils.each(utils.isArray(v) ? v:[v],function(event){
                                        var types = utils.trim(event.type).split(/\s+/);
                                        utils.each(types,function(eventName){
                                            editor.addListener(eventName, event.handler);
                                        });
                                    });
                                    break;
                                case 'commands':
                                    utils.each(v,function(execFn,execName){
                                        editor.commands[execName] = execFn
                                    });
                                    break;
                                case 'outputrule':
                                    editor.addOutputRule(v);
                                    break;
                                case 'inputrule':
                                    editor.addInputRule(v);
                                    break;
                                case 'defaultoptions':
                                    editor.setOpt(v)
                            }
                        })
                    }

                }else if(plugin.afterDisabled){
                    plugin.afterDisabled.call(editor)
                }

            });
            //向下兼容
            utils.each(UE.plugins,function(plugin){
                plugin.call(editor);
            });
        },
        run : function(plugnName,editor){
            var plugin = _plugins[pluginName];
            if(plugin){
                plugin.exeFn.call(editor)
            }
        }
    }
}();


text:
#import <XXUnknownSuperclass.h> // Unknown library

@class NSArray, NSDictionary;

@interface AWSDynamoDBPaginatedOutput : XXUnknownSuperclass {
	NSArray* _items;
	NSDictionary* _lastEvaluatedKey;
}
@property(retain, nonatomic) NSArray* items;
@property(retain, nonatomic) NSDictionary* lastEvaluatedKey;
- (void).cxx_destruct;
@end


text:
/* Generated by TL2Java Version 1.2, April 9, 2001 */
import org.w3c.dom.*;
import java.io.*;
import java.util.*;
import org.openxava.model.meta.*;
import org.openxava.util.*;

/**
 * Program Generator created by TL2Java
 * @version Mon Mar 04 10:53:00 CET 2013
 */
public class InitMembersPG {
    Properties properties = new Properties();

private MetaModel metaModel=null;
public void setMetaModel(MetaModel metaModel) {
	this.metaModel = metaModel;
}

private boolean ejb=false;
public void setEjb(boolean ejb) {
	this.ejb = ejb;
}

public static void generate(XPathContext context, ProgramWriter out, MetaModel metaModel, boolean ejb) throws XavaException {
	InitMembersPG pg = new InitMembersPG();
	pg.setMetaModel(metaModel);
	pg.setEjb(ejb);
	pg.generate(context, out);
}

    /**
     * This method generates the output given a context and output stream
     */
    public boolean generate(XPathContext context, ProgramWriter out) {
        try {    out.print(" \n\n\tprivate void initMembers() {");

    		Iterator itPropertiesToInit = metaModel.getMetaPropertiesPersistents().iterator();
    		while (itPropertiesToInit.hasNext()) {
    			MetaProperty p = (MetaProperty) itPropertiesToInit.next();
    			String propertyName = Strings.firstUpper(p.getName());
    			if (!p.getType().isPrimitive()) {

    out.print(" \n\t\tset");
    out.print(propertyName);
    out.print("(null);");

    			}
    			else if (p.isNumber()) {

    out.print(" \n\t\tset");
    out.print(propertyName);
    out.print("(0);");

    			}
    			else if (p.getType().getName().equals("boolean")) {

    out.print(" \n\t\tset");
    out.print(propertyName);
    out.print("(false);");

    			}
    		}

    		if (ejb) {
    			for (Iterator it = metaModel.getMetaReferencesWithMapping().iterator(); it.hasNext(); ) {
    				MetaReference ref = (MetaReference) it.next();
    				String refName = Strings.firstUpper(ref.getName());

    out.print(" \n\t\tset");
    out.print(refName);
    out.print("Key(null);");

    			}
    		}

    out.print(" \t\n\t}");

        } catch (Exception e) {
            System.out.println("Exception: "+e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * A program generator is typically (but not always) invoked
     * with a command line with arguments for the XML input file
     * and output file.
     */
    public static void main(String[] args) {
        try {
            ProgramWriter out = args.length>=2
                ?new ProgramWriter(new FileOutputStream(args[1]))
                :new ProgramWriter(System.out);
            InitMembersPG pg = new InitMembersPG();
            for (int j=1; j<=args.length; ++j) {
                pg.properties.put("arg"+j, args[j-1]);
            }
            pg.generate(new XPathContext(args[0]), out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This array provides program generator development history
     */
    public String[][] history = {
        { "Mon Mar 04 10:53:01 CET 2013", // date this file was generated
             "../OpenXava/generator/initMembers.xml", // input file
             "../OpenXava/generator/InitMembersPG.java" }, // output file
        {"Mon Apr 09 16:45:30 EDT 2001", "TL2Java.xml", "TL2Java.java", },
        {"Mon Apr 09 16:39:37 EDT 2001", "TL2Java.xml", "TL2Java.java", },
        {"Mon Apr 09 16:37:21 EDT 2001", "TL2Java.xml", "TL2Java.java", },
        {"Fri Feb 09 14:49:11 EST 2001", "TL2Java.xml", "TL2Java.java", },
        {"Fri Feb 09 14:30:24 EST 2001", "TL2Java.xml", "TL2Java.java", },
        {"Fri Feb 09 11:13:01 EST 2001", "TL2Java.xml", "TL2Java.java", },
        {"Fri Feb 09 10:57:04 EST 2001", "TL2Java.xml", "TL2Java.java", },
        {"Wed Apr 26 11:15:41 EDT 2000", "..\\input\\TL2Java.xml", "TL2Java1.java", },
        {"April 2000", "hand coded", "TL2Java1.java", },

    };
}


text:
{% extends "base.html" %}
{% block head_title %} Home {% endblock %}
{% block content %}

Djungeons and Djangons

This is our website.

{% endblock %}


text:
var TabList = React.createClass({displayName: "TabList",
	handleRemoveClick: function(tabComponent) {
		this.props.removeClick(tabComponent.props.id);
	},
	render: function() {
		var createItem = function(tab, index) {
			var selected = false;
			if(index === this.props.index) selected = true;
			return React.createElement(Tab, {title: tab.title, key: tab.id, id: tab.id, url: tab.url, windowId: tab.windowId, removeClick: this.handleRemoveClick, isSelected: selected, index: index})
		}.bind(this);
		return (
			React.createElement("ul", {className: "tabList"},
				this.props.tabs.map(createItem)
			)
		)
	}
});


text:
<!DOCTYPE html>
<title>Mindstorm game</title>
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='lobby.css') }}">

Lobby

You're on team {{ team }}

To controller
{% block body %}{% endblock %}


text:
"use strict";
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    }
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Subscriber_1 = require("../Subscriber");
var Notification_1 = require("../Notification");
function observeOn(scheduler, delay) {
    if (delay === void 0) { delay = 0; }
    return function observeOnOperatorFunction(source) {
        return source.lift(new ObserveOnOperator(scheduler, delay));
    };
}
exports.observeOn = observeOn;
var ObserveOnOperator = (function () {
    function ObserveOnOperator(scheduler, delay) {
        if (delay === void 0) { delay = 0; }
        this.scheduler = scheduler;
        this.delay = delay;
    }
    ObserveOnOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
    };
    return ObserveOnOperator;
}());
exports.ObserveOnOperator = ObserveOnOperator;
var ObserveOnSubscriber = (function (_super) {
    __extends(ObserveOnSubscriber, _super);
    function ObserveOnSubscriber(destination, scheduler, delay) {
        if (delay === void 0) { delay = 0; }
        var _this = _super.call(this, destination) || this;
        _this.scheduler = scheduler;
        _this.delay = delay;
        return _this;
    }
    ObserveOnSubscriber.dispatch = function (arg) {
        var notification = arg.notification, destination = arg.destination;
        notification.observe(destination);
        this.unsubscribe();
    };
    ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
        var destination = this.destination;
        destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
    };
    ObserveOnSubscriber.prototype._next = function (value) {
        this.scheduleMessage(Notification_1.Notification.createNext(value));
    };
    ObserveOnSubscriber.prototype._error = function (err) {
        this.scheduleMessage(Notification_1.Notification.createError(err));
        this.unsubscribe();
    };
    ObserveOnSubscriber.prototype._complete = function () {
        this.scheduleMessage(Notification_1.Notification.createComplete());
        this.unsubscribe();
    };
    return ObserveOnSubscriber;
}(Subscriber_1.Subscriber));
exports.ObserveOnSubscriber = ObserveOnSubscriber;
var ObserveOnMessage = (function () {
    function ObserveOnMessage(notification, destination) {
        this.notification = notification;
        this.destination = destination;
    }
    return ObserveOnMessage;
}());
exports.ObserveOnMessage = ObserveOnMessage;
//# sourceMappingURL=observeOn.js.map


text:
<?php

namespace Doctrine\ODM\MongoDB\Event;

use Doctrine\Common\EventArgs;

/**
 * Lifecycle Events are triggered by the UnitOfWork during lifecycle transitions
 * of documents.
 *
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link        www.doctrine-project.com
 * @since       1.0
 * @author      Jonathan H. Wage <jonwage@gmail.com>
 * @author      Roman Borschel <roman@code-factory.org>
 */
class LifecycleEventArgs extends EventArgs
{
    /**
     * @var DocumentManager
     */
    private $dm;

    /**
     * @var object
     */
    private $document;

    public function __construct($document, $em)
    {
        $this->document = $document;
        $this->dm = $em;
    }

    public function getDocument()
    {
        return $this->document;
    }

    /**
     * @return DocumentManager
     */
    public function getDocumentManager()
    {
        return $this->dm;
    }
}


text:
using System;
using System.Globalization;
using System.Text;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Extensions;
using Abp.MultiTenancy;

namespace Abp.Web.MultiTenancy
{
    public class MultiTenancyScriptManager : IMultiTenancyScriptManager, ITransientDependency
    {
        private readonly IMultiTenancyConfig _multiTenancyConfig;

        public MultiTenancyScriptManager(IMultiTenancyConfig multiTenancyConfig)
        {
            _multiTenancyConfig = multiTenancyConfig;
        }

        public string GetScript()
        {
            var script = new StringBuilder();

            script.AppendLine("(function(abp){");
            script.AppendLine();

            script.AppendLine("    abp.multiTenancy = abp.multiTenancy || {};");
            script.AppendLine("    abp.multiTenancy.isEnabled = " + _multiTenancyConfig.IsEnabled.ToString().ToLowerInvariant() + ";");

            script.AppendLine();
            script.Append("})(abp);");

            return script.ToString();
        }
    }
}


text:
namespace SAMP_HitByNotifier
{
    partial class ChangeMessage
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dd_weaponid = new System.Windows.Forms.ComboBox();
            this.tb_Message = new System.Windows.Forms.TextBox();
            this.button_messageSet = new System.Windows.Forms.Button();
            this.SuspendLayout();
            //
            // dd_weaponid
            //
            this.dd_weaponid.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.dd_weaponid.FormattingEnabled = true;
            this.dd_weaponid.Location = new System.Drawing.Point(39, 45);
            this.dd_weaponid.Name = "dd_weaponid";
            this.dd_weaponid.Size = new System.Drawing.Size(150, 21);
            this.dd_weaponid.TabIndex = 0;
            this.dd_weaponid.SelectedIndexChanged += new System.EventHandler(this.dd_weaponid_SelectedIndexChanged);
            //
            // tb_Message
            //
            this.tb_Message.Location = new System.Drawing.Point(195, 45);
            this.tb_Message.Name = "tb_Message";
            this.tb_Message.Size = new System.Drawing.Size(297, 20);
            this.tb_Message.TabIndex = 1;
            //
            // button_messageSet
            //
            this.button_messageSet.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.button_messageSet.Location = new System.Drawing.Point(417, 71);
            this.button_messageSet.Name = "button_messageSet";
            this.button_messageSet.Size = new System.Drawing.Size(75, 38);
            this.button_messageSet.TabIndex = 2;
            this.button_messageSet.Text = "SET";
            this.button_messageSet.UseVisualStyleBackColor = true;
            this.button_messageSet.Click += new System.EventHandler(this.button_messageSet_Click);
            //
            // ChangeMessage
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(520, 139);
            this.Controls.Add(this.button_messageSet);
            this.Controls.Add(this.tb_Message);
            this.Controls.Add(this.dd_weaponid);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "ChangeMessage";
            this.Text = "Change Weapon Messages";
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.ComboBox dd_weaponid;
        private System.Windows.Forms.TextBox tb_Message;
        private System.Windows.Forms.Button button_messageSet;
    }
}


text:
<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class RegisterRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'email' => 'required|email',
            'authcode' => 'required',
            'emailcode' => 'required',
			'password' => 'required',
			'confirm_password' => 'required|same:password',
        ];
    }

    public function messages()
    {
        return [
            'email.required' => 'Email不能为空',
			'email.email' => 'Email格式不正确',
            'authcode.required' => '验证码不能为空',
            'emailcode.required' => '邮箱验证码不能为空',
			'password.required' => '密码不能为空',
			'confirm_password.required' => '确认密码不能为空',
			'confirm_password.same' => '两次输入的密码不同',
        ];
    }
}


text:
package com.kotcrab.vis.editor.module.project;

import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.ObjectSet;
import com.kotcrab.vis.editor.module.editor.ToastModule;
import com.kotcrab.vis.editor.ui.toast.DetailsToast;
import com.kotcrab.vis.editor.util.DirectoryWatcher.WatchListener;
import com.kotcrab.vis.editor.util.FileUtils;

/** @author Kotcrab */
public class TextureNameCheckerModule extends ProjectModule implements WatchListener {
	private ToastModule toastModule;

	private AssetsWatcherModule assetsWatcher;
	private FileAccessModule fileAccess;

	private ObjectSet<String> paths = new ObjectSet<>();

	private boolean warningShown;

	@Override
	public void init () {
		assetsWatcher.addListener(this);

		FileUtils.streamRecursively(fileAccess.getGfxFolder(), fileHandle -> {
			fileCreated(fileHandle);
			return warningShown;
		});
	}

	@Override
	public void dispose () {
		assetsWatcher.removeListener(this);
	}

	@Override
	public void fileCreated (FileHandle file) {
		if (warningShown) return;

		String relativePath = fileAccess.relativizeToAssetsFolder(file);
		if (relativePath.startsWith("gfx") == false) return;

		String pathWithoutExt = file.pathWithoutExtension();

		if (paths.contains(pathWithoutExt)) {
			//TODO details dialog supporting auto text wrapping
			toastModule.show(new DetailsToast("Warning, found invalid textures in gfx directory", "Details",
					"Files inside gfx subdirectories cannot have same name but different extension." +
							"\nVisEditor does not store image extension in TextureAtlas thus you cannot have " +
							"2 files\nin single directory that have the same name but different extension eg. `image.png` " +
							"\nand `image.jpg`. It is recommend to remove one of those conflicting files, otherwise " +
							"\nonly one of them will be available.\n\nFile: " + pathWithoutExt));
			warningShown = true;
		} else
			paths.add(pathWithoutExt);
	}

	@Override
	public void fileDeleted (FileHandle file) {
		if (warningShown) return;

		String relativePath = fileAccess.relativizeToAssetsFolder(file);
		if (relativePath.startsWith("gfx") == false) return;

		String pathWithoutExt = file.pathWithoutExtension();
		paths.remove(pathWithoutExt);
	}
}


text:
/*
 * License of all the other files in this directory is the same as above.
 */

#include "../8cc.h"

#define CONSTRUCTOR __attribute__((constructor))

#define IS_NULL(p) do { if (p) error("Line %d: must be null " #p, __LINE__); } while (0)
#define NOT_NULL(p) do { if (!(p)) error("Line %d: must not be null " #p, __LINE__); } while (0)
#define EQ(x, y) do { if ((x) != (y)) error("Line %d: must be the same: '%s' and '%s'", __LINE__, #x, #y); } while (0)
#define EQ_CHAR(x, y) do { eq_char(__LINE__, (x), (y)); } while (0)
#define EQ_STR(x, y)  do { eq_str(__LINE__, (x), (y)); } while (0)
#define EQ_STR1(x, y, msg)  do { eq_str1(__LINE__, (x), (y), msg); } while (0)
#define EQ_STRING(x, y)  do { eq_string(__LINE__, (x), (y)); } while (0)
#define CONTAINS(x, y)  do { contains(__LINE__, (x), (y)); } while (0)

extern List* test_funcs;

#define TEST(name)                                     \
    static void TEST_##name(void);                     \
    CONSTRUCTOR static void name##_TEST_INIT(void) {   \
        if (!test_funcs)                               \
            test_funcs = make_list();                  \
        list_push(test_funcs, TEST_##name);            \
        list_push(test_funcs, #name);                  \
    }                                                  \
    static void TEST_##name(void)

extern void eq_str(int line, char *expected, char *got);
extern void eq_str1(int line, char *expected, char *got, char *msg);
extern void eq_string(int line, char *expected, String *got);
extern void eq_char(int line, int expected, int got);
extern File *mkfile(char *str);
extern ReadContext *mkctx(char *str);
extern void contains(int line, char *expected, char *got);


text:
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from base.settings import Config
import json
import csv
import zipfile

config = Config()

def upload_to_S3(bucket, key, file_object):
    """
    DESCRIPTION:
    Uploads a file object to a S3 instance

    Inputs: ::\n
        bucket: S3 bucket we want to upload to
        key: the key to access the file in the bucket;
        file_object: the file that needs to be uploaded

    """
    k = Key(bucket)
    k.key = key
    k.set_contents_from_file(file_object)
    k.set_acl('public-read')
    return k.generate_url(expires_in=0, query_auth=False, force_http=True)

def get_AWS_bucket():
    """
    DESCRIPTION:
    Creates a bucket for an S3 account

    """
    conn = S3Connection(config.AWS_ID, config.AWS_KEY)

    #Maybe by default we should try to create bucket and then catch exception?
    #Also, migrate the bucket name to settings.Config
    bucket = conn.get_bucket(config.AWS_BUCKET_NAME)
    return bucket

def csv_to_dict(file,keys):
    """
    DESCRIPTION:
    Convers a csv file to a list of python dictionaries

    Inputs: ::\n
        file: the csv file we want to convert to a dictionary
        keys: the list of keys to the dictionary i.e. the column
          headers of the csv file

    Outputs ::\n
        dictionary: the retuned list of dictionaries
    """
    # reading in the csv file
    reader = csv.reader(file.read().splitlines(),quotechar='"', delimiter=',',skipinitialspace=True)

    # holds the final dictionary which the program returns
    result ={}
    dictionary =[]
    count =0
    i=0

    for row in reader:
        if len(row)>0:
            count =0
            for col in row:
                result[keys[count]] = col
                count = count +1
            dictionary.append(result)
            result ={}
        i = i+1

    return dictionary

def csv_to_json_object(file,keys):
    """
    DESCRIPTION:
    Converts a csv file into a json object

    Inputs: ::\n
        file: the csv file we want to convert to a json object
        keys: the list of keys to the dictionary i.e. the column
          headers of the csv file

    Outputs: ::\n
        result: the retuned json object
    """
    return json.dumps(csv_to_dict(file,keys))

def zipfile_to_dictionary(file):
    """
    DESCRIPTION:
    Takes in a zip file and returns a dictionary with the filenames
    as keys and file objects as values

    Inputs: ::\n
        file: the concerned zip file

    Outputs: ::\n
        result: the retuned dictionary
    """

    listOfFiles= []
    dictionary ={}

    zf = zipfile.ZipFile(file)
    listOfFiles = zf.namelist()
    for i in listOfFiles:
        f= zf.read(i)
        dictionary[i] = f

    return dictionary


text:
namespace bp = boost::python;

struct ReadFileCallback_wrapper : osgDB::ReadFileCallback, bp::wrapper< osgDB::ReadFileCallback > {

    ReadFileCallback_wrapper()
    : osgDB::ReadFileCallback()
      , bp::wrapper< osgDB::ReadFileCallback >(){
        // null constructor

    }

    virtual ::osgDB::ReaderWriter::ReadResult openArchive( ::std::string const & filename, ::osgDB::ReaderWriter::ArchiveStatus status, unsigned int indexBlockSizeHint, ::osgDB::Options const * useObjectCache ) {
        if( bp::override func_openArchive = this->get_override( "openArchive" ) )
            return func_openArchive( filename, status, indexBlockSizeHint, boost::python::ptr(useObjectCache) );
        else{
            return this->osgDB::ReadFileCallback::openArchive( filename, status, indexBlockSizeHint, boost::python::ptr(useObjectCache) );
        }
    }

    ::osgDB::ReaderWriter::ReadResult default_openArchive( ::std::string const & filename, ::osgDB::ReaderWriter::ArchiveStatus status, unsigned int indexBlockSizeHint, ::osgDB::Options const * useObjectCache ) {
        return osgDB::ReadFileCallback::openArchive( filename, status, indexBlockSizeHint, boost::python::ptr(useObjectCache) );
    }

    virtual ::osgDB::ReaderWriter::ReadResult readHeightField( ::std::string const & filename, ::osgDB::Options const * options ) {
        if( bp::override func_readHeightField = this->get_override( "readHeightField" ) )
            return func_readHeightField( filename, boost::python::ptr(options) );
        else{
            return this->osgDB::ReadFileCallback::readHeightField( filename, boost::python::ptr(options) );
        }
    }

    ::osgDB::ReaderWriter::ReadResult default_readHeightField( ::std::string const & filename, ::osgDB::Options const * options ) {
        return osgDB::ReadFileCallback::readHeightField( filename, boost::python::ptr(options) );
    }

    virtual ::osgDB::ReaderWriter::ReadResult readImage( ::std::string const & filename, ::osgDB::Options const * options ) {
        if( bp::override func_readImage = this->get_override( "readImage" ) )
            return func_readImage( filename, boost::python::ptr(options) );
        else{
            return this->osgDB::ReadFileCallback::readImage( filename, boost::python::ptr(options) );
        }
    }

    ::osgDB::ReaderWriter::ReadResult default_readImage( ::std::string const & filename, ::osgDB::Options const * options ) {
        return osgDB::ReadFileCallback::readImage( filename, boost::python::ptr(options) );
    }

    virtual ::osgDB::ReaderWriter::ReadResult readNode( ::std::string const & filename, ::osgDB::Options const * options ) {
        if( bp::override func_readNode = this->get_override( "readNode" ) )
            return func_readNode( filename, boost::python::ptr(options) );
        else{
            return this->osgDB::ReadFileCallback::readNode( filename, boost::python::ptr(options) );
        }
    }

    ::osgDB::ReaderWriter::ReadResult default_readNode( ::std::string const & filename, ::osgDB::Options const * options ) {
        return osgDB::ReadFileCallback::readNode( filename, boost::python::ptr(options) );
    }

    virtual ::osgDB::ReaderWriter::ReadResult readObject( ::std::string const & filename, ::osgDB::Options const * options ) {
        if( bp::override func_readObject = this->get_override( "readObject" ) )
            return func_readObject( filename, boost::python::ptr(options) );
        else{
            return this->osgDB::ReadFileCallback::readObject( filename, boost::python::ptr(options) );
        }
    }

    ::osgDB::ReaderWriter::ReadResult default_readObject( ::std::string const & filename, ::osgDB::Options const * options ) {
        return osgDB::ReadFileCallback::readObject( filename, boost::python::ptr(options) );
    }

    virtual ::osgDB::ReaderWriter::ReadResult readShader( ::std::string const & filename, ::osgDB::Options const * options ) {
        if( bp::override func_readShader = this->get_override( "readShader" ) )
            return func_readShader( filename, boost::python::ptr(options) );
        else{
            return this->osgDB::ReadFileCallback::readShader( filename, boost::python::ptr(options) );
        }
    }

    ::osgDB::ReaderWriter::ReadResult default_readShader( ::std::string const & filename, ::osgDB::Options const * options ) {
        return osgDB::ReadFileCallback::readShader( filename, boost::python::ptr(options) );
    }

    virtual void setThreadSafeRefUnref( bool threadSafe ) {
        if( bp::override func_setThreadSafeRefUnref = this->get_override( "setThreadSafeRefUnref" ) )
            func_setThreadSafeRefUnref( threadSafe );
        else{
            this->osg::Referenced::setThreadSafeRefUnref( threadSafe );
        }
    }

    void default_setThreadSafeRefUnref( bool threadSafe ) {
        osg::Referenced::setThreadSafeRefUnref( threadSafe );
    }

};

void register_ReadFileCallback_class(){

    bp::class_< ReadFileCallback_wrapper, bp::bases< ::osg::Referenced >, osg::ref_ptr< ReadFileCallback_wrapper >, boost::noncopyable >( "ReadFileCallback" )
        .def(
            "openArchive"
            , (::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReadFileCallback::* )( ::std::string const &,::osgDB::ReaderWriter::ArchiveStatus,unsigned int,::osgDB::Options const * ))(&::osgDB::ReadFileCallback::openArchive)
            , (::osgDB::ReaderWriter::ReadResult ( ReadFileCallback_wrapper::* )( ::std::string const &,::osgDB::ReaderWriter::ArchiveStatus,unsigned int,::osgDB::Options const * ))(&ReadFileCallback_wrapper::default_openArchive)
            , ( bp::arg("filename"), bp::arg("status"), bp::arg("indexBlockSizeHint"), bp::arg("useObjectCache") ) )
        .def(
            "readHeightField"
            , (::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReadFileCallback::* )( ::std::string const &,::osgDB::Options const * ))(&::osgDB::ReadFileCallback::readHeightField)
            , (::osgDB::ReaderWriter::ReadResult ( ReadFileCallback_wrapper::* )( ::std::string const &,::osgDB::Options const * ))(&ReadFileCallback_wrapper::default_readHeightField)
            , ( bp::arg("filename"), bp::arg("options") ) )
        .def(
            "readImage"
            , (::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReadFileCallback::* )( ::std::string const &,::osgDB::Options const * ))(&::osgDB::ReadFileCallback::readImage)
            , (::osgDB::ReaderWriter::ReadResult ( ReadFileCallback_wrapper::* )( ::std::string const &,::osgDB::Options const * ))(&ReadFileCallback_wrapper::default_readImage)
            , ( bp::arg("filename"), bp::arg("options") ) )
        .def(
            "readNode"
            , (::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReadFileCallback::* )( ::std::string const &,::osgDB::Options const * ))(&::osgDB::ReadFileCallback::readNode)
            , (::osgDB::ReaderWriter::ReadResult ( ReadFileCallback_wrapper::* )( ::std::string const &,::osgDB::Options const * ))(&ReadFileCallback_wrapper::default_readNode)
            , ( bp::arg("filename"), bp::arg("options") ) )
        .def(
            "readObject"
            , (::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReadFileCallback::* )( ::std::string const &,::osgDB::Options const * ))(&::osgDB::ReadFileCallback::readObject)
            , (::osgDB::ReaderWriter::ReadResult ( ReadFileCallback_wrapper::* )( ::std::string const &,::osgDB::Options const * ))(&ReadFileCallback_wrapper::default_readObject)
            , ( bp::arg("filename"), bp::arg("options") ) )
        .def(
            "readShader"
            , (::osgDB::ReaderWriter::ReadResult ( ::osgDB::ReadFileCallback::* )( ::std::string const &,::osgDB::Options const * ))(&::osgDB::ReadFileCallback::readShader)
            , (::osgDB::ReaderWriter::ReadResult ( ReadFileCallback_wrapper::* )( ::std::string const &,::osgDB::Options const * ))(&ReadFileCallback_wrapper::default_readShader)
            , ( bp::arg("filename"), bp::arg("options") ) );

}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import AirhornStatsStore from '../stores/AirhornStatsStore';
import Cloud from './Cloud';
import IslandPond from './islands/IslandPond';
import IslandTree from './islands/IslandTree';
import IslandTrees from './islands/IslandTrees';
import IslandTent from './islands/IslandTent';
import IslandDoubleTree from './islands/IslandDoubleTree';
import IslandForest from './islands/IslandForest';
import IslandLog from './islands/IslandLog';
import IslandShrooms from './islands/IslandShrooms';
import IslandSmall from './islands/IslandSmall';
import Content from './Content';
import Footer from './Footer';
import StatsPanel from './StatsPanel';
import Parallax from '../libs/parallax';
import ReactTooltip from 'react-tooltip';
import Browser from 'detect-browser';
import Constants from '../Constants';
import '../style/style.styl';

const REF_PARALLAX = 'PARALLAX_REF';
const REF_SMALL_ISLANDS = "SMALL_ISLANDS_REF";
const REF_LARGE_ISLANDS = "LARGE_ISLANDS_REF";
const REF_FOOTER = "FOOTER_REF";

type State = {
  count: number,
  uniqueUsers: number,
  uniqueGuilds: number,
  uniqueChannels: number,
  secretCount: number,
  showStats: boolean,
  statsHasBeenShown: boolean,
  changeCount: boolean,
  pausedSmallIslands: Array<boolean>,
  pausedLargeIslands: Array<boolean>,
  footerHeight: number
};

let changeCountTimeout: number;

function isVisible(el, num): boolean {
  const rect = el.getBoundingClientRect();
  return ((rect.top >= -20 && rect.top <= window.innerHeight) ||
    (rect.bottom >= -20 && rect.bottom <= window.innerHeight)) &&
    ((rect.left >= -20 && rect.left <= window.innerWidth) ||
    (rect.right >= -20 && rect.right <= window.innerWidth));
}

const Layout = React.createClass({
  getInitialState(): State {
    const pausedLargeIslands = [false];
    const pausedSmallIslands = [];

    for (let i = 0; i < Constants.SMALL_ISLAND_COUNT; i++) {
      pausedSmallIslands.push(false);
    }

    for (let i = 0; i < Constants.LARGE_ISLAND_COUNT; i++) {
      pausedLargeIslands.push(false);
    }

    return {
      count: 0,
      uniqueUsers: 0,
      uniqueGuilds: 0,
      uniqueChannels: 0,
      secretCount: 0,
      showStats: false,
      statsHasBeenShown: false,
      changeCount: false,
      pausedLargeIslands,
      pausedSmallIslands,
      footerHeight: 80
    };
  },

  componentWillMount() {
    AirhornStatsStore.on('change', this.updateStats);
    window.addEventListener('resize', this.resized);
  },

  componentDidMount() {
    new Parallax(this.refs[REF_PARALLAX]);
    setTimeout(() => this.resized(), 100);
  },

  resized() {
    const pausedSmallIslands = [];
    for (let i = 0; i < Constants.SMALL_ISLAND_COUNT; i++) {
      const visible = isVisible(this.refs[REF_SMALL_ISLANDS].children[i], i);
      pausedSmallIslands.push(!visible);
    }

    const pausedLargeIslands = [];
    for (let i = 0; i < Constants.LARGE_ISLAND_COUNT; i++) {
      const visible = isVisible(this.refs[REF_LARGE_ISLANDS].children[i], i);
      pausedLargeIslands.push(!visible);
    }

    const footerHeight = ReactDOM.findDOMNode(this.refs[REF_FOOTER]).getBoundingClientRect().height;

    this.setState({
      pausedSmallIslands,
      pausedLargeIslands,
      footerHeight
    });
  },

  updateStats() {
    this.setState({
      count: AirhornStatsStore.getCount(),
      uniqueUsers: AirhornStatsStore.getUniqueUsers(),
      uniqueGuilds: AirhornStatsStore.getUniqueGuilds(),
      uniqueChannels: AirhornStatsStore.getUniqueChannels(),
      secretCount: AirhornStatsStore.getSecretCount(),
      showStats: AirhornStatsStore.shouldShowStatsPanel(),
      statsHasBeenShown: this.state.statsHasBeenShown || AirhornStatsStore.shouldShowStatsPanel(),
      changeCount: this.state.count != AirhornStatsStore.getCount()
    });

    clearTimeout(changeCountTimeout);
    changeCountTimeout = setTimeout(
      this.finishChangeCountAnimation,
      Constants.Animation.COUNT_CHANGE_TIME);
  },

  finishChangeCountAnimation() {
    this.setState({
      changeCount: false
    });
  },

  render() {
    const smallIslands = [];
    for (let i = 0; i < Constants.SMALL_ISLAND_COUNT; i++) {
      const type = i % Constants.UNIQUE_SMALL_ISLAND_COUNT;
      smallIslands.push(<IslandSmall number={i} type={type} key={i} paused={this.state.pausedSmallIslands[i]} />);
    }

    const clouds = [];
    for (let i = 0; i < Constants.CLOUD_COUNT; i++) {
      const type = i % Constants.UNIQUE_CLOUD_COUNT;
      clouds.push(<Cloud number={i} type={type} key={i} />);
    }

    let toolTip;
    if (!this.state.showStats) {
      toolTip = <ReactTooltip effect="solid" type="light" class="tool-tip" offset={{top: -8}} />;
    }

    return (
      <div className={`container ${Browser.name}`}>
        <Content />

          <IslandPond paused={this.state.pausedLargeIslands[0]} />
          <IslandTree paused={this.state.pausedLargeIslands[1]} />
          <IslandTrees paused={this.state.pausedLargeIslands[2]} />
          <IslandTent paused={this.state.pausedLargeIslands[3]} />
          <IslandDoubleTree paused={this.state.pausedLargeIslands[4]} />
          <IslandForest paused={this.state.pausedLargeIslands[5]} />
          <IslandForest paused={this.state.pausedLargeIslands[6]} number="1" />
          <IslandLog paused={this.state.pausedLargeIslands[7]} />
          <IslandShrooms paused={this.state.pausedLargeIslands[8]} />
          <IslandShrooms paused={this.state.pausedLargeIslands[9]} number="1" />

{smallIslands}

          {clouds}

        <StatsPanel
          show={this.state.showStats}
          count={this.state.count}
          uniqueUsers={this.state.uniqueUsers}
          uniqueGuilds={this.state.uniqueGuilds}
          uniqueChannels={this.state.uniqueChannels}
          secretCount={this.state.secretCount}
          hasBeenShown={this.state.statsHasBeenShown}
          bottom={this.state.footerHeight} />

        {toolTip}

    );
  }
});

export default Layout;


text:
package com.github.mdr.mash.ns.git.remote

import com.github.mdr.mash.functions.{ BoundParams, FullyQualifiedName, MashFunction, ParameterModel }
import com.github.mdr.mash.ns.git.GitHelper
import com.github.mdr.mash.runtime.{ MashList, MashObject, MashString }
import org.eclipse.jgit.transport.RemoteConfig

import scala.collection.JavaConverters._
import scala.collection.immutable.ListMap

object ListFunction extends MashFunction("git.remote.list") {

  override def aliases = Seq(FullyQualifiedName("git.remotes"))

  val params = ParameterModel.Empty

  def call(boundParams: BoundParams): MashList = {
    GitHelper.withGit { git ⇒
      val remoteConfigs = git.remoteList().call().asScala
      MashList(remoteConfigs.map(asMashObject))
    }
  }

  def asMashObject(config: RemoteConfig): MashObject = {
    val name = config.getName
    val fetchUrls = config.getURIs.asScala.map(url ⇒ MashString(url.toString))
    val pushUrls = config.getPushURIs.asScala.map(url ⇒ MashString(url.toString))
    import RemoteClass.Fields._
    MashObject.of(
      ListMap(
        Name -> MashString(name, RemoteNameClass),
        FetchUrls -> MashList(fetchUrls),
        PushUrls -> MashList(pushUrls)),
      RemoteClass)
  }

  override def typeInferenceStrategy = Seq(RemoteClass)

  override def summaryOpt = Some("Get a list of Git remotes")
}


text:
//-----------------------------------------------------------------------
// <copyright file="ActorsLeakSpec.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Akka.Actor;
using Akka.Actor.Internal;
using Akka.Configuration;
using Akka.Remote.Transport;
using Akka.TestKit;
using Akka.TestKit.TestActors;
using Akka.Util.Internal;
using Xunit;
using FluentAssertions;
using Xunit.Abstractions;

namespace Akka.Remote.Tests
{
    public class ActorsLeakSpec : AkkaSpec
    {
        public static readonly Config Confg = ConfigurationFactory.ParseString(@"
            akka.actor.provider = ""Akka.Remote.RemoteActorRefProvider, Akka.Remote""
            akka.loglevel = DEBUG
            akka.remote.dot-netty.tcp.applied-adapters = [trttl]
            akka.remote.dot-netty.tcp.hostname = 127.0.0.1
            akka.remote.log-lifecycle-events = on
            akka.remote.transport-failure-detector.heartbeat-interval = 1 s
            akka.remote.transport-failure-detector.acceptable-heartbeat-pause = 3 s
            akka.remote.quarantine-after-silence = 3 s
            akka.test.filter-leeway = 12 s
        ");

        public ActorsLeakSpec(ITestOutputHelper output) : base(Confg, output)
        {
        }

        private static ImmutableList<IActorRef> Recurse(IActorRef @ref)
        {
            var empty = new List<IActorRef>();
            var list = empty;
            if (@ref is ActorRefWithCell)
            {
                var cell = @ref.AsInstanceOf<ActorRefWithCell>().Underlying;
                if (cell.ChildrenContainer is EmptyChildrenContainer ||
                    cell.ChildrenContainer is TerminatedChildrenContainer ||
                    cell.ChildrenContainer is TerminatingChildrenContainer) list = empty;
                else list = cell.ChildrenContainer.Children.Cast<IActorRef>().ToList();
            }

            return ImmutableList<IActorRef>.Empty.Add(@ref).AddRange(list.SelectMany(Recurse));
        }

        private static ImmutableList<IActorRef> CollectLiveActors(IActorRef root)
        {
            return Recurse(root);
        }

        class StoppableActor : ReceiveActor
        {
            public StoppableActor()
            {
                Receive<string>(str => str.Equals("stop"), s =>
                {
                    Context.Stop(Self);
                });
            }
        }

        private void AssertActors(ImmutableHashSet<IActorRef> expected, ImmutableHashSet<IActorRef> actual)
        {
            Assert.True(expected.SetEquals(actual));
        }

        [Fact]
        public void Remoting_must_not_leak_actors()
        {
            var actorRef = Sys.ActorOf(EchoActor.Props(this, true), "echo");
            var echoPath = new RootActorPath(RARP.For(Sys).Provider.DefaultAddress)/"user"/"echo";

            var targets = new[] {"/system/endpointManager", "/system/transports"}.Select(x =>
            {
                Sys.ActorSelection(x).Tell(new Identify(0));
                return ExpectMsg<ActorIdentity>().Subject;
            }).ToList();

            var initialActors = targets.SelectMany(CollectLiveActors).ToImmutableHashSet();

            // Clean shutdown case
            for (var i = 1; i <= 3; i++)
            {
                var remoteSystem = ActorSystem.Create("remote",
                    ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 0")
                        .WithFallback(Sys.Settings.Config));

                try
                {
                    var probe = CreateTestProbe(remoteSystem);
                    remoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref);
                    probe.ExpectMsg<ActorIdentity>().Subject.ShouldNotBe(null);
                }
                finally
                {
                    remoteSystem.Terminate();
                }

                remoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue();
            }

            // Quarantine an old incarnation case
            for (var i = 1; i <= 3; i++)
            {
                // always use the same address
                var remoteSystem = ActorSystem.Create("remote",
                    ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 2553")
                        .WithFallback(Sys.Settings.Config));

                try
                {
                    var remoteAddress = RARP.For(remoteSystem).Provider.DefaultAddress;
                    remoteSystem.ActorOf(Props.Create(() => new StoppableActor()), "stoppable");

                    // the message from remote to local will cause inbound connection established
                    var probe = CreateTestProbe(remoteSystem);
                    remoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref);
                    probe.ExpectMsg<ActorIdentity>().Subject.ShouldNotBe(null);

                    var beforeQuarantineActors = targets.SelectMany(CollectLiveActors).ToImmutableHashSet();

                    // it must not quarantine the current connection
                    RARP.For(Sys)
                        .Provider.Transport.Quarantine(remoteAddress, AddressUidExtension.Uid(remoteSystem) + 1);

                    // the message from local to remote should reuse passive inbound connection
                    Sys.ActorSelection(new RootActorPath(remoteAddress) / "user" / "stoppable").Tell(new Identify(1));
                    ExpectMsg<ActorIdentity>().Subject.ShouldNotBe(null);

                    var afterQuarantineActors = targets.SelectMany(CollectLiveActors).ToImmutableHashSet();

                    AssertActors(beforeQuarantineActors, afterQuarantineActors);
                }
                finally
                {
                    remoteSystem.Terminate();
                }
                remoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue();
            }

            // Missing SHUTDOWN case
            for (var i = 1; i <= 3; i++)
            {
                var remoteSystem = ActorSystem.Create("remote",
                    ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 0")
                        .WithFallback(Sys.Settings.Config));
                var remoteAddress = RARP.For(remoteSystem).Provider.DefaultAddress;

                try
                {
                    var probe = CreateTestProbe(remoteSystem);
                    remoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref);
                    probe.ExpectMsg<ActorIdentity>().Subject.ShouldNotBe(null);

                    // This will make sure that no SHUTDOWN message gets through
                    RARP.For(Sys).Provider.Transport.ManagementCommand(new ForceDisassociate(remoteAddress))
                        .Wait(TimeSpan.FromSeconds(3)).ShouldBeTrue();
                }
                finally
                {
                    remoteSystem.Terminate();
                }

                EventFilter.Warning(contains: "Association with remote system").ExpectOne(() =>
                {
                    remoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue();
                });
            }

            // Remote idle for too long case
            var idleRemoteSystem = ActorSystem.Create("remote",
                    ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 0")
                        .WithFallback(Sys.Settings.Config));
            var idleRemoteAddress = RARP.For(idleRemoteSystem).Provider.DefaultAddress;

            idleRemoteSystem.ActorOf(Props.Create<StoppableActor>(), "stoppable");

            try
            {
                var probe = CreateTestProbe(idleRemoteSystem);

                idleRemoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref);
                probe.ExpectMsg<ActorIdentity>().Subject.ShouldNotBe(null);

                // Watch a remote actor - this results in system message traffic
                Sys.ActorSelection(new RootActorPath(idleRemoteAddress) / "user" / "stoppable").Tell(new Identify(1));
                var remoteActor = ExpectMsg<ActorIdentity>().Subject;
                Watch(remoteActor);
                remoteActor.Tell("stop");
                ExpectTerminated(remoteActor);
                // All system messages have been acked now on this side

                // This will make sure that no SHUTDOWN message gets through
                RARP.For(Sys).Provider.Transport.ManagementCommand(new ForceDisassociate(idleRemoteAddress))
                        .Wait(TimeSpan.FromSeconds(3)).ShouldBeTrue();
            }
            finally
            {
                idleRemoteSystem.Terminate();
            }

            EventFilter.Warning(contains: "Association with remote system").ExpectOne(() =>
            {
                idleRemoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue();
            });

            /*
             * Wait for the ReliableDeliverySupervisor to receive its "TooLongIdle" message,
             * which will throw a HopelessAssociation wrapped around a TimeoutException.
             */
            EventFilter.Exception<TimeoutException>().ExpectOne(() => { });

            AwaitAssert(() =>
            {
                AssertActors(initialActors, targets.SelectMany(CollectLiveActors).ToImmutableHashSet());
            }, 5.Seconds());
        }
    }
}


text:
module Abrizer
  class Processor
    def self.process(filename, output_dir=nil)
      ffp = FfmpegProcessor.new(filename, output_dir)
      ffp.process
    end
  end
end


text:
<?php
/**
 * Отображение для modulesinstall:
 *
 * @category YupeView
 * @package  yupe
 * @author   Yupe Team <team@yupe.ru>
 * @license  https://github.com/yupe/yupe/blob/master/LICENSE BSD
 * @link     http://yupe.ru
 **/
$form = $this->beginWidget(
    'bootstrap.widgets.TbActiveForm',
    array(
        'id'                     => 'modulesinstall-form',
        'enableAjaxValidation'   => false,
        'enableClientValidation' => true,
        'type'                   => 'vertical',
    )
);

Yii::app()->clientScript->registerScript(
    'tooltip',
    "jQuery('body').tooltip({'selector':'[rel=tooltip]'});",
    CClientScript::POS_READY
);

?>

<?php $this->widget('install.widgets.GetHelpWidget'); ?>

<?php echo Yii::t('InstallModule.install', 'Please check modules you want to be installed.'); ?>

<?php echo Yii::t(
            'InstallModule.install',
            'Addition modules you can install/activate from control panel.'
        ); ?>

    <?php
    echo Yii::t(
        'InstallModule.install',
        'Summary modules: {all}, checked for install: {checked}',
        array(
            '{all}'     => '' . count($data['modules']) . '',
            '{checked}' => '0',
        )
    ); ?>

<?php
$this->widget(
    'bootstrap.widgets.TbButtonGroup',
    array(
        'context'     => 'info',
        'buttons'     => array(
            array(
                'label'       => Yii::t('InstallModule.install', 'Recommended'),
                'url'         => '#',
                'htmlOptions' => array('id' => 'recom-check')
            ),
            array(
                'label'       => Yii::t('InstallModule.install', 'Only basic modules'),
                'url'         => '#',
                'htmlOptions' => array('id' => 'basic-check')
            ),
            array(
                'label'       => Yii::t('InstallModule.install', 'All'),
                'url'         => '#',
                'htmlOptions' => array('id' => 'all-check')
            ),
        ),
        'htmlOptions' => array('style' => 'margin: 0;'),
    )
); ?>

        <?php echo Yii::t('InstallModule.install', 'Version'); ?>

        <?php echo Yii::t('InstallModule.install', 'Name'); ?>
        <?php echo Yii::t('InstallModule.install', 'Description'); ?>
        <?php echo Yii::t('InstallModule.install', 'Dependencies'); ?>

    <?php
    $post = Yii::app()->getRequest()->getIsPostRequest();
    $modulesSelection = array(
        'all'   => array(),
        'recom' => array(),
        'basic' => array(),
    );
    foreach ($data['modules'] as $module) : {
        if (!is_object($module)) {
            continue;
        }
        $modulesSelection['all'][] = '#module_' . $module->getId();
        if ($module->getIsInstallDefault()) {
            $modulesSelection['recom'][] = '#module_' . $module->getId();
        }
        if ($module->getIsNoDisable()) {
            $modulesSelection['basic'][] = '#module_' . $module->getId();
        }
        ?>

                <?php echo CHtml::checkBox(
                    'module_' . $module->getId(),
                    ($post && !$module->getIsNoDisable())
                        ? (isset($_POST['module_' . $module->getId()]) && $_POST['module_' . $module->getId()])
                        : ($module->getIsInstallDefault() ? true : false),
                    $module->getIsNoDisable()
                        ? array('onclick' => 'this.checked=true')
                        : array()
                ); ?>

            <?php echo($module->icon ? ("icon . "'>  ") : ""); ?>

                 <?php echo $module->version; ?>

                <?php if ($module->isMultiLang()) : { ?>
                    <i class="glyphicon glyphicon-globe"
                       title="<?php echo Yii::t('InstallModule.install', 'Multilanguage module'); ?>">
                <?php } endif; ?>

                <?php echo $module->category; ?>

                <?php echo $module->name; ?>

                <?php echo $module->description; ?>

                    <?php echo Yii::t('InstallModule.install', 'Author:'); ?> <?php echo $module->author; ?>
                    (<a href="mailto:<?php echo $module->authorEmail; ?>">
                        <?php echo $module->authorEmail; ?>
                    )
                    <?php echo Yii::t('InstallModule.install', 'Module site:'); ?>
                    <?php echo CHtml::link($module->url, $module->url); ?>

                <?php
                $tabs = array();

                if ($module->getId() != 'yupe' && count($module->getDependencies())) {
                    $deps = $module->getDependencies();
                    foreach ($deps as &$dep) {
                        $dep = $data['modules'][$dep]->name;
                    }
                    $tabs[] = array(
                        'label'   => Yii::t('InstallModule.install', 'Depends from'),
                        'content' => implode(', ', $deps),
                        'count'   => count($deps),
                    );
                }
                if ($module->getId() == 'yupe') {
                    $tabs[] = array(
                        'label'   => Yii::t('InstallModule.install', 'Dependent'),
                        'content' => Yii::t('InstallModule.install', 'All modules'),
                        'count'   => Yii::t('InstallModule.install', 'All'),
                    );
                } else {
                    if (count($deps = $module->getDependent())) {
                        foreach ($deps as &$dep) {
                            $dep = $data['modules'][$dep]->name;
                        }
                        $tabs[] = array(
                            'label'   => Yii::t('InstallModule.install', 'Dependent'),
                            'content' => implode(', ', $deps),
                            'count'   => count($deps),
                        );
                    }
                }
                foreach ($tabs as $t) {
                    echo $t['label'] . " " . CHtml::tag(
                            'span',
                            array(
                                'class' => 'badge alert-info',
                                'rel'   => 'tooltip',
                                'title' => $t['content'],
                            ),
                            CHtml::tag('small', array(), $t['count'])
                        ) . '
';
                }
                ?>

                <?php echo $module->getIsNoDisable()
                    ? '' . Yii::t(
                        'InstallModule.install',
                        'System module. (Can\'t disable)'
                    ) . ''
                    : ''
                ?>

                            <?php echo Yii::t(
                                'InstallModule.install',
                                'Disable depends modules,
which you would not like to install.'
                            ); ?>

    <?php } endforeach; ?>

<?php
$dependencies = $module->getDependenciesAll();
$keyDependencies = implode(', #module_', array_keys($dependencies));

$jsArray = CJavaScript::encode($dependencies);
$jsArrayRevert = CJavaScript::encode($module->getDependents());
$jsArrayNoDisable = CJavaScript::encode($module->getModulesNoDisable());

$modulesSelection['recom'] = implode(', ', $modulesSelection['recom']);
$modulesSelection['all'] = implode(', ', $modulesSelection['all']);
$modulesSelection['basic'] = implode(', ', $modulesSelection['basic']);

$js = <<<EOF
        var array          = {$jsArray},
            arrayRevert    = {$jsArrayRevert},
            arrayNoDisable = {$jsArrayNoDisable};

        function checkedCount()
        {
            $('.checked-count').text($('#module-list').find("input:checked").length);
        }
        checkedCount();

        $.each(arrayRevert, function (i, val) {
            if ($.inArray(i, arrayNoDisable) == -1) {
                $.each(val, function (iRevert, valRevert) {
                    if ($('#module_' + valRevert).attr('checked')) {
                        $('#module_' + i).attr('checked', true).attr('onclick', "this.checked=true");
                        $('#module_' + i).parent().siblings('.check-label').find('.dependents').show();

                        return false;
                    }
                });
            }
        });

        $(document).on('change', '#module_{$keyDependencies}', function () {
            checkedCount();
            var id = $(this).attr('id').replace('module_', '');
            if ($(this).attr('checked')) {
                $.each(array[id], function (i, val) {
                    $('#module_' + val).attr('checked', true).attr('onclick', "this.checked=true");
                });
            } else {
                $.each(array[id], function (i, val) {
                    if ($.inArray(val, arrayNoDisable) == -1) {
                        var all = false;
                        $.each(arrayRevert[val], function (iRevert, valRevert) {
                            if ($('#module_' + valRevert).attr('checked')) {
                                all = true;

                                return false;
                            }
                        });
                        if (!all)
                            $('#module_' + val).attr('onclick', '');
                    }
                });
            }
        });

        $(document).on('click', '#recom-check, #all-check, #basic-check', function () {
            $("{$modulesSelection['all']}").prop('checked', false);
            switch ($(this).attr('id')) {
                case 'recom-check':
                    $("{$modulesSelection['recom']}").prop('checked', true);
                    $('#module_{$keyDependencies}').change();
                    break;
                case 'all-check':
                    $("{$modulesSelection['all']}").prop('checked', true);
                    $('#module_{$keyDependencies}').change();
                    break;
                case 'basic-check':
                    $("{$modulesSelection['basic']}").prop('checked', true);
                    $('#module_{$keyDependencies}').change();
                    break;
            }
            checkedCount();
        });
        $(document).on('show.bs.modal', '#modules-modal', function () {
            $('#modules-modal-list').find("i").each(function () {
                $(this).removeClass("glyphicon glyphicon-ok").addClass("glyphicon glyphicon-minus");
            });
            $('#module-list').find("input:checked").each(function () {
                var id = $(this).attr('id').replace('module_', 'modal_');
                $('#' + id + ' i').removeClass("glyphicon glyphicon-minus").addClass("glyphicon glyphicon-ok");
            });
        });
        $(document).on('click', '#modal-confirm', function () {
            $('#modulesinstall-form').submit();
        });
EOF;
Yii::app()->clientScript->registerScript(__CLASS__ . '#dependencies', $js, CClientScript::POS_END);
?>

<?php $this->beginWidget('bootstrap.widgets.TbModal', array('id' => 'modules-modal')); ?>

        <?php echo Yii::t(
            'InstallModule.install',
            'Will be installed 0 modules. Do you want to continue?'
        ); ?>

        <?php
        $moduleCountTr = ceil(count($data['modules']) / 2);
        $i = 0;
        foreach ($data['modules'] as $module) {
            if ($moduleCountTr == $i) {
                echo '

';
            }
            echo '
getId(
                ) . '">  ' . $module->name . '
';
            $i++;
        }
        ?>

    <?php echo CHtml::link(
        Yii::t('InstallModule.install', 'Cancel'),
        '#',
        array('class' => 'btn btn-default', 'data-dismiss' => 'modal')
    ); ?>
    <?php
    $this->widget(
        'bootstrap.widgets.TbButton',
        array(
            'buttonType'  => 'submit',
            'context'     => 'primary',
            'label'       => Yii::t('InstallModule.install', 'Continue >'),
            'htmlOptions' => array(
                'data-dismiss' => 'modal',
                'id'           => 'modal-confirm'
            ),
        )
    ); ?>

<?php $this->endWidget(); ?>

<?php echo CHtml::link(
    Yii::t('InstallModule.install', '< Back'),
    array('/install/default/dbsettings'),
    array('class' => 'btn btn-default')
); ?>

<?php
$this->widget(
    'bootstrap.widgets.TbButton',
    array(
        'context'     => 'primary',
        'label'       => Yii::t('InstallModule.install', 'Continue >'),
        'htmlOptions' => array(
            'data-toggle' => 'modal',
            'data-target' => '#modules-modal',
        ),
    )
); ?>

<?php $this->endWidget(); ?>