text:
RSpec.describe RuboCop::Cop::Lint::RedundantSafeNavigation, :config do
  let(:cop_config) { { 'AllowedMethods' => %w[respond_to?] } }

  it 'registers an offense and corrects when `&.` is used inside `if` condition' do
    expect_offense(<<~RUBY)
      if foo&.respond_to?(:bar)
            ^^^^^^^^^^^^^^^^^^^ Redundant safe navigation detected.
        do_something
      elsif foo&.respond_to?(:baz)
               ^^^^^^^^^^^^^^^^^^^ Redundant safe navigation detected.
        do_something_else
      end
    RUBY

    expect_correction(<<~RUBY)
      if foo.respond_to?(:bar)
        do_something
      elsif foo.respond_to?(:baz)
        do_something_else
      end
    RUBY
  end

  it 'registers an offense and corrects when `&.` is used inside `unless` condition' do
    expect_offense(<<~RUBY)
      do_something unless foo&.respond_to?(:bar)
                             ^^^^^^^^^^^^^^^^^^^ Redundant safe navigation detected.
    RUBY

    expect_correction(<<~RUBY)
      do_something unless foo.respond_to?(:bar)
    RUBY
  end

  %i[while until].each do |loop_type|
    it 'registers an offense and corrects when `&.` is used inside `#{loop_type}` condition' do
      expect_offense(<<~RUBY, loop_type: loop_type)
        %{loop_type} foo&.respond_to?(:bar)
        _{loop_type}    ^^^^^^^^^^^^^^^^^^^ Redundant safe navigation detected.
          do_something
        end

        begin
          do_something
        end %{loop_type} foo&.respond_to?(:bar)
            _{loop_type}    ^^^^^^^^^^^^^^^^^^^ Redundant safe navigation detected.
      RUBY

      expect_correction(<<~RUBY)
        #{loop_type} foo.respond_to?(:bar)
          do_something
        end

        begin
          do_something
        end #{loop_type} foo.respond_to?(:bar)
      RUBY
    end
  end

  it 'registers an offense and corrects when `&.` is used inside complex condition' do
    expect_offense(<<~RUBY)
      do_something if foo&.respond_to?(:bar) && !foo&.respond_to?(:baz)
                         ^^^^^^^^^^^^^^^^^^^ Redundant safe navigation detected.
                                                    ^^^^^^^^^^^^^^^^^^^ Redundant safe navigation detected.
    RUBY

    expect_correction(<<~RUBY)
      do_something if foo.respond_to?(:bar) && !foo.respond_to?(:baz)
    RUBY
  end

  it 'does not register an offense when using `&.` outside of conditions' do
    expect_no_offenses(<<~RUBY)
      foo&.respond_to?(:bar)

      if condition
        foo&.respond_to?(:bar)
      end
    RUBY
  end

  it 'does not register an offense when using `&.` with non-allowed method in condition' do
    expect_no_offenses(<<~RUBY)
      do_something if foo&.bar?
    RUBY
  end

  it 'does not register an offense when using `&.respond_to?` with `nil` specific method as argument in condition' do
    expect_no_offenses(<<~RUBY)
      do_something if foo&.respond_to?(:to_a)
    RUBY
  end
end


text:
/*****  Vca::VOutputSequencer Implementation  *****/

/************************
 ************************
 *****  Interfaces  *****
 ************************
 ************************/

/********************
 *****  System  *****
 ********************/

#include "Vk.h"

/******************
 *****  Self  *****
 ******************/

#include "Vca_VOutputSequencer.h"

/************************
 *****  Supporting  *****
 ************************/

#include "Vca_CompilerHappyPill.h"

#include "Vca_IError.h"
#include "Vca_ITrigger.h"

/*******************************************
 *******************************************
 *****                                 *****
 *****  Vca::VOutputSequencer::Output  *****
 *****                                 *****
 *******************************************
 *******************************************/

/******************************
 ******************************
 *****  State Transition  *****
 ******************************
 ******************************/

void Vca::VOutputSequencer::Output::startThis () {	    // typically called from constructor of concrete class
    onStart ();
    m_pSequencer->queue (this);
}

void Vca::VOutputSequencer::Output::setStatusToAvailable () {
    if (statusIsBlocked ()) {
	m_xStatus = Status_Available;
	m_pSequencer->start (this);
    }
}

void Vca::VOutputSequencer::Output::setStatusToDone () {
    if (m_xStatus != Status_Final) {
	m_xStatus = Status_Done;
	onSuccess ();
    }
}

/*****************
 *****************
 *****  Use  *****
 *****************
 *****************/

void Vca::VOutputSequencer::Output::onSequencerShutdown () {
    static VString const sErrorMessage ("Aborted By Shutdown", false);
    onFailure (0, sErrorMessage);
}

/************************************************
 ************************************************
 *****                                      *****
 *****  Vca::VOutputSequencer::OutputPause  *****
 *****                                      *****
 ************************************************
 ************************************************/

/**************************
 **************************
 *****  Construction  *****
 **************************
 **************************/

Vca::VOutputSequencer::OutputPause::OutputPause (
    Sequencer *pSequencer) : BaseClass (pSequencer, Status_Blocked
) {
    retain (); {
	startThis ();
    } untain ();
}

/*****************
 *****************
 *****  Use  *****
 *****************
 *****************/

void Vca::VOutputSequencer::OutputPause::load (Fifo &rOutputFifo) {
    rOutputFifo.clear ();
    setStatusToDone ();
}

/*****************************************************
 *****************************************************
 *****                                           *****
 *****  Vca::VOutputSequencer::OutputTerminator  *****
 *****                                           *****
 *****************************************************
 *****************************************************/

/**************************
 **************************
 *****  Construction  *****
 **************************
 **************************/

Vca::VOutputSequencer::OutputTerminator::OutputTerminator (
    Sequencer *pSequencer) : BaseClass (pSequencer, Status_Final
) {
    retain (); {
	startThis ();
    } untain ();
}

/*****************
 *****************
 *****  Use  *****
 *****************
 *****************/

void Vca::VOutputSequencer::OutputTerminator::load (Fifo &rOutputFifo) {
    rOutputFifo.clear ();
}

/***********************************************
 ***********************************************
 *****                                     *****
 *****  Vca::VOutputSequencer::BlobOutput  *****
 *****                                     *****
 ***********************************************
 ***********************************************/

/**************************
 **************************
 *****  Construction  *****
 **************************
 **************************/

Vca::VOutputSequencer::BlobOutput::BlobOutput (
    Sequencer *pSequencer, Blob const &rBlob
) : BaseClass (pSequencer, Status_Available), m_iBlob (rBlob) {
    retain (); {
	startThis ();
    } untain ();
}

/*****************
 *****************
 *****  Use  *****
 *****************
 *****************/

void Vca::VOutputSequencer::BlobOutput::load (Fifo &rOutputFifo) {
    rOutputFifo.setToData (m_iBlob.contentArea (), m_iBlob.contentSize ());
    setStatusToDone ();
}

/*************************************************
 *************************************************
 *****                                       *****
 *****  Vca::VOutputSequencer::StringOutput  *****
 *****                                       *****
 *************************************************
 *************************************************/

/**************************
 **************************
 *****  Construction  *****
 **************************
 **************************/

Vca::VOutputSequencer::StringOutput::StringOutput (
    Sequencer *pSequencer, VString const &rString
) : BaseClass (pSequencer, Status_Available), m_iString (rString) {
    retain (); {
	startThis ();
    } untain ();
}

/*****************
 *****************
 *****  Use  *****
 *****************
 *****************/

void Vca::VOutputSequencer::StringOutput::load (Fifo &rOutputFifo) {
    rOutputFifo.setToData (m_iString, m_iString.length ());
    setStatusToDone ();
}

/***********************************
 ***********************************
 *****                         *****
 *****  Vca::VOutputSequencer  *****
 *****                         *****
 ***********************************
 ***********************************/

/**************************
 **************************
 *****  Construction  *****
 **************************
 **************************/

Vca::VOutputSequencer::VOutputSequencer (
     VBSConsumer *pBS
) : Schedulable (this), m_ppOutputQueueTail (&m_pOutputQueueHead), m_pBS (pBS), m_pBSClient (this) {
    traceInfo ("Creating Sequencer");
}

/*************************
 *************************
 *****  Destruction  *****
 *************************
 *************************/

Vca::VOutputSequencer::~VOutputSequencer () {
    traceInfo ("Destroying Sequencer");
}

/***********************
 ***********************
 *****  Callbacks  *****
 ***********************
 ***********************/

void Vca::VOutputSequencer::OnTransfer (IBSClient *pRole, size_t sTransfer) {
    m_iOutputFifo.consume (sTransfer);
    if (m_iOutputFifo.consumerAreaIsEmpty ())
	resume ();
}

void Vca::VOutputSequencer::OnError (
    IClient *pRole, IError *pError, VString const &rMessage
) {
    m_pFinalError.setTo (pError);
    m_iFinalErrorMessage.setTo (rMessage);

    m_pBS.clear ();
    if (suspended ())
	resume ();
}

/*******************************
 *******************************
 *****  Output Generation  *****
 *******************************
 *******************************/

void Vca::VOutputSequencer::outputBlob (BlobOutput::Reference &rpBlobOutput, Blob const &rBlob) {
    if (rBlob.contentSize () > 0)
	rpBlobOutput.setTo (new BlobOutput (this, rBlob));
    else
	rpBlobOutput.clear ();
}

void Vca::VOutputSequencer::outputBlob (Blob const &rBlob) {
    BlobOutput::Reference pBlobOutput;
    outputBlob (pBlobOutput, rBlob);
}

void Vca::VOutputSequencer::outputString (StringOutput::Reference &rpStringOutput, VString const &rString) {
    if (rString.length () > 0)
	rpStringOutput.setTo (new StringOutput (this, rString));
    else
	rpStringOutput.clear ();
}

void Vca::VOutputSequencer::outputString (VString const &rString) {
    StringOutput::Reference pStringOutput;
    outputString (pStringOutput, rString);
}

void Vca::VOutputSequencer::outputPause (OutputPause::Reference &rpOutputPause) {
    rpOutputPause.setTo (new OutputPause (this));
}

void Vca::VOutputSequencer::outputTerminator (OutputTerminator::Reference &rpOutputTerminator) {
    rpOutputTerminator.setTo (new OutputTerminator (this));
}

void Vca::VOutputSequencer::outputTerminator () {
    OutputTerminator::Reference pOutputTerminator;
    outputTerminator (pOutputTerminator);
}

/***********************
 ***********************
 *****  Execution  *****
 ***********************
 ***********************/

void Vca::VOutputSequencer::queue (Output *pOutput) {
    m_ppOutputQueueTail->setTo (pOutput);
    m_ppOutputQueueTail = &pOutput->m_pSuccessor;
    start (pOutput);
}

void Vca::VOutputSequencer::start (Output *pOutput) {
    if (pOutput == m_pOutputQueueHead)
	resume ();
}

void Vca::VOutputSequencer::schedule_() {
    m_iScheduler.schedule (this);
}

void Vca::VOutputSequencer::run_() {
    IBSClient::Reference pBSClient;
    getRole (pBSClient);
    while (!suspended () && m_pBS.isntNil ()) {
	if (m_pOutputQueueHead.isNil ())
	    suspend ();
	else switch (m_pOutputQueueHead->status ()) {
	case Output::Status_Available:
	    m_pOutputQueueHead->load (m_iOutputFifo);
	    m_iOutputFifo.consume (m_pBS->put (pBSClient, m_iOutputFifo));
	    if (m_iOutputFifo.consumerAreaIsntEmpty ())
		suspend ();
	    break;
	case Output::Status_Blocked:
	    suspend ();
	    break;
	case Output::Status_Final:
	    m_pOutputQueueHead->onSuccess ();
	    m_pBS->Close ();
	    OnEnd (pBSClient);
	    /*****  No BREAK  *****/
	default:
	    m_pOutputQueueHead.claim (m_pOutputQueueHead->m_pSuccessor);
	    if (m_pOutputQueueHead.isNil ())
		m_ppOutputQueueTail = &m_pOutputQueueHead;
	    break;
	}
    }
    if (m_pBS.isNil ()) {
	while (m_pOutputQueueHead) {
	    m_pOutputQueueHead->onSequencerShutdown ();
	    m_pOutputQueueHead.claim (m_pOutputQueueHead->m_pSuccessor);
	}
	m_ppOutputQueueTail = &m_pOutputQueueHead;
	if (!suspended ())
	    suspend ();
	m_pOnEndTriggers.trigger ();
    }
}

/********************************
 ********************************
 *****  Event Subscription  *****
 ********************************
 ********************************/

void Vca::VOutputSequencer::onEndTrigger (ITrigger *pTrigger) {
    m_pOnEndTriggers.Insert (pTrigger);
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

/*============================================================
**
**
**
** Purpose: The structure for holding all of the data needed
**          for object serialization and deserialization.
**
**
===========================================================*/
namespace System.Runtime.Serialization
{

    using System;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Runtime.Remoting;
#if FEATURE_REMOTING
    using System.Runtime.Remoting.Proxies;
#endif
    using System.Globalization;
    using System.Diagnostics.Contracts;
    using System.Security;
#if FEATURE_CORECLR
    using System.Runtime.CompilerServices;
#endif

    [System.Runtime.InteropServices.ComVisible(true)]
    public sealed class SerializationInfo
    {
        private const int defaultSize = 4;
        private const string s_mscorlibAssemblySimpleName = "mscorlib";
        private const string s_mscorlibFileName = s_mscorlibAssemblySimpleName + ".dll";

        // Even though we have a dictionary, we're still keeping all the arrays around for back-compat.
        // Otherwise we may run into potentially breaking behaviors like GetEnumerator() not returning entries in the same order they were added.
        internal String[] m_members;
        internal Object[] m_data;
        internal Type[] m_types;
        private Dictionary<string, int> m_nameToIndex;
        internal int m_currMember;
        internal IFormatterConverter m_converter;
        private String m_fullTypeName;
        private String m_assemName;
        private Type objectType;
        private bool isFullTypeNameSetExplicit;
        private bool isAssemblyNameSetExplicit;
        private bool requireSameTokenInPartialTrust;

        [CLSCompliant(false)]
        public SerializationInfo(Type type, IFormatterConverter converter)
            : this(type, converter, false)
        {
        }

        [CLSCompliant(false)]
        public SerializationInfo(Type type, IFormatterConverter converter, bool requireSameTokenInPartialTrust)
        {
            if ((object)type == null)
            {
                throw new ArgumentNullException("type");
            }

            if (converter == null)
            {
                throw new ArgumentNullException("converter");
            }

            Contract.EndContractBlock();

            objectType = type;
            m_fullTypeName = type.FullName;
            m_assemName = type.Module.Assembly.FullName;

            m_members = new String[defaultSize];
            m_data = new Object[defaultSize];
            m_types = new Type[defaultSize];

            m_nameToIndex = new Dictionary<string, int>();

            m_converter = converter;

            this.requireSameTokenInPartialTrust = requireSameTokenInPartialTrust;
        }

        public String FullTypeName
        {
            get
            {
                return m_fullTypeName;
            }
            set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }
                Contract.EndContractBlock();

                m_fullTypeName = value;
                isFullTypeNameSetExplicit = true;
            }
        }

        public String AssemblyName
        {
            get
            {
                return m_assemName;
            }
            [SecuritySafeCritical]
            set
            {
                if (null == value)
                {
                    throw new ArgumentNullException("value");
                }
                Contract.EndContractBlock();
                if (this.requireSameTokenInPartialTrust)
                {
                    DemandForUnsafeAssemblyNameAssignments(this.m_assemName, value);
                }
                m_assemName = value;
                isAssemblyNameSetExplicit = true;
            }
        }

        [SecuritySafeCritical]
        public void SetType(Type type)
        {
            if ((object)type == null)
            {
                throw new ArgumentNullException("type");
            }
            Contract.EndContractBlock();

            if (this.requireSameTokenInPartialTrust)
            {
                DemandForUnsafeAssemblyNameAssignments(this.ObjectType.Assembly.FullName, type.Assembly.FullName);
            }

            if (!Object.ReferenceEquals(objectType, type))
            {
                objectType = type;
                m_fullTypeName = type.FullName;
                m_assemName = type.Module.Assembly.FullName;
                isFullTypeNameSetExplicit = false;
                isAssemblyNameSetExplicit = false;
            }
        }

        private static bool Compare(byte[] a, byte[] b)
        {
            // if either or both assemblies do not have public key token, we should demand, hence, returning false will force a demand
            if (a == null || b == null || a.Length == 0 || b.Length == 0 || a.Length != b.Length)
            {
                return false;
            }
            else
            {
                for (int i = 0; i < a.Length; i++)
                {
                    if (a[i] != b[i]) return false;
                }

                return true;
            }
        }

        [SecuritySafeCritical]
        internal static void DemandForUnsafeAssemblyNameAssignments(string originalAssemblyName, string newAssemblyName)
        {
            if (!IsAssemblyNameAssignmentSafe(originalAssemblyName, newAssemblyName))
            {
                CodeAccessPermission.Demand(PermissionType.SecuritySerialization);
            }
        }

        internal static bool IsAssemblyNameAssignmentSafe(string originalAssemblyName, string newAssemblyName)
        {
            if (originalAssemblyName == newAssemblyName)
            {
                return true;
            }

            AssemblyName originalAssembly = new AssemblyName(originalAssemblyName);
            AssemblyName newAssembly = new AssemblyName(newAssemblyName);

            // mscorlib will get loaded by the runtime regardless of its string casing or its public key token,
            // so setting the assembly name to mscorlib must always be protected by a demand
            if (string.Equals(newAssembly.Name, s_mscorlibAssemblySimpleName, StringComparison.OrdinalIgnoreCase) ||
                string.Equals(newAssembly.Name, s_mscorlibFileName, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            return Compare(originalAssembly.GetPublicKeyToken(), newAssembly.GetPublicKeyToken());
        }

        public int MemberCount
        {
            get
            {
                return m_currMember;
            }
        }

        public Type ObjectType
        {
            get
            {
                return objectType;
            }
        }

        public bool IsFullTypeNameSetExplicit
        {
            get
            {
                return isFullTypeNameSetExplicit;
            }
        }

        public bool IsAssemblyNameSetExplicit
        {
            get
            {
                return isAssemblyNameSetExplicit;
            }
        }

        public SerializationInfoEnumerator GetEnumerator()
        {
            return new SerializationInfoEnumerator(m_members, m_data, m_types, m_currMember);
        }

        private void ExpandArrays()
        {
            int newSize;
            Contract.Assert(m_members.Length == m_currMember, "[SerializationInfo.ExpandArrays]m_members.Length == m_currMember");

            newSize = (m_currMember * 2);

            //
            // In the pathological case, we may wrap
            //
            if (newSize < m_currMember)
            {
                if (Int32.MaxValue > m_currMember)
                {
                    newSize = Int32.MaxValue;
                }
            }

            //
            // Allocate more space and copy the data
            //
            String[] newMembers = new String[newSize];
            Object[] newData = new Object[newSize];
            Type[] newTypes = new Type[newSize];

            Array.Copy(m_members, newMembers, m_currMember);
            Array.Copy(m_data, newData, m_currMember);
            Array.Copy(m_types, newTypes, m_currMember);

            //
            // Assign the new arrys back to the member vars.
            //
            m_members = newMembers;
            m_data = newData;
            m_types = newTypes;
        }

        public void AddValue(String name, Object value, Type type)
        {
            if (null == name)
            {
                throw new ArgumentNullException("name");
            }

            if ((object)type == null)
            {
                throw new ArgumentNullException("type");
            }
            Contract.EndContractBlock();

            AddValueInternal(name, value, type);
        }

        public void AddValue(String name, Object value)
        {
            if (null == value)
            {
                AddValue(name, value, typeof(Object));
            }
            else
            {
                AddValue(name, value, value.GetType());
            }
        }

        public void AddValue(String name, bool value)
        {
            AddValue(name, (Object)value, typeof(bool));
        }

        public void AddValue(String name, char value)
        {
            AddValue(name, (Object)value, typeof(char));
        }

        [CLSCompliant(false)]
        public void AddValue(String name, sbyte value)
        {
            AddValue(name, (Object)value, typeof(sbyte));
        }

        public void AddValue(String name, byte value)
        {
            AddValue(name, (Object)value, typeof(byte));
        }

        public void AddValue(String name, short value)
        {
            AddValue(name, (Object)value, typeof(short));
        }

        [CLSCompliant(false)]
        public void AddValue(String name, ushort value)
        {
            AddValue(name, (Object)value, typeof(ushort));
        }

        public void AddValue(String name, int value)
        {
            AddValue(name, (Object)value, typeof(int));
        }

        [CLSCompliant(false)]
        public void AddValue(String name, uint value)
        {
            AddValue(name, (Object)value, typeof(uint));
        }

        public void AddValue(String name, long value)
        {
            AddValue(name, (Object)value, typeof(long));
        }

        [CLSCompliant(false)]
        public void AddValue(String name, ulong value)
        {
            AddValue(name, (Object)value, typeof(ulong));
        }

        public void AddValue(String name, float value)
        {
            AddValue(name, (Object)value, typeof(float));
        }

        public void AddValue(String name, double value)
        {
            AddValue(name, (Object)value, typeof(double));
        }

        public void AddValue(String name, decimal value)
        {
            AddValue(name, (Object)value, typeof(decimal));
        }

        public void AddValue(String name, DateTime value)
        {
            AddValue(name, (Object)value, typeof(DateTime));
        }

        internal void AddValueInternal(String name, Object value, Type type)
        {
            if (m_nameToIndex.ContainsKey(name))
            {
                BCLDebug.Trace("SER", "[SerializationInfo.AddValue]Tried to add ", name, " twice to the SI.");
                throw new SerializationException(Environment.GetResourceString("Serialization_SameNameTwice"));
            }
            m_nameToIndex.Add(name, m_currMember);

            //
            // If we need to expand the arrays, do so.
            //
            if (m_currMember >= m_members.Length)
            {
                ExpandArrays();
            }

            //
            // Add the data and then advance the counter.
            //
            m_members[m_currMember] = name;
            m_data[m_currMember] = value;
            m_types[m_currMember] = type;
            m_currMember++;
        }

        /*=================================UpdateValue==================================
        **Action: Finds the value if it exists in the current data.  If it does, we replace
        **        the values, if not, we append it to the end.  This is useful to the
        **        ObjectManager when it's performing fixups, but shouldn't be used by
        **        clients.  Exposing out this functionality would allow children to overwrite
        **        their parent's values.
        **Returns: void
        **Arguments: name  -- the name of the data to be updated.
        **           value -- the new value.
        **           type  -- the type of the data being added.
        **Exceptions: None.  All error checking is done with asserts.
        ==============================================================================*/
        internal void UpdateValue(String name, Object value, Type type)
        {
            Contract.Assert(null != name, "[SerializationInfo.UpdateValue]name!=null");
            Contract.Assert(null != value, "[SerializationInfo.UpdateValue]value!=null");
            Contract.Assert(null != (object)type, "[SerializationInfo.UpdateValue]type!=null");

            int index = FindElement(name);
            if (index < 0)
            {
                AddValueInternal(name, value, type);
            }
            else
            {
                m_data[index] = value;
                m_types[index] = type;
            }

        }

        private int FindElement(String name)
        {
            if (null == name)
            {
                throw new ArgumentNullException("name");
            }
            Contract.EndContractBlock();
            BCLDebug.Trace("SER", "[SerializationInfo.FindElement]Looking for ", name, " CurrMember is: ", m_currMember);
            int index;
            if (m_nameToIndex.TryGetValue(name, out index))
            {
                return index;
            }
            return -1;
        }

        /*==================================GetElement==================================
        **Action: Use FindElement to get the location of a particular member and then return
        **        the value of the element at that location.  The type of the member is
        **        returned in the foundType field.
        **Returns: The value of the element at the position associated with name.
        **Arguments: name -- the name of the element to find.
        **           foundType -- the type of the element associated with the given name.
        **Exceptions: None.  FindElement does null checking and throws for elements not
        **            found.
        ==============================================================================*/
        private Object GetElement(String name, out Type foundType)
        {
            int index = FindElement(name);
            if (index == -1)
            {
                throw new SerializationException(Environment.GetResourceString("Serialization_NotFound", name));
            }

            Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
            Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");

            foundType = m_types[index];
            Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
            return m_data[index];
        }

        [System.Runtime.InteropServices.ComVisible(true)]
        private Object GetElementNoThrow(String name, out Type foundType)
        {
            int index = FindElement(name);
            if (index == -1)
            {
                foundType = null;
                return null;
            }

            Contract.Assert(index < m_data.Length, "[SerializationInfo.GetElement]index<m_data.Length");
            Contract.Assert(index < m_types.Length, "[SerializationInfo.GetElement]index<m_types.Length");

            foundType = m_types[index];
            Contract.Assert((object)foundType != null, "[SerializationInfo.GetElement]foundType!=null");
            return m_data[index];
        }

        //
        // The user should call one of these getters to get the data back in the
        // form requested.
        //

        [System.Security.SecuritySafeCritical]  // auto-generated
        public Object GetValue(String name, Type type)
        {

            if ((object)type == null)
            {
                throw new ArgumentNullException("type");
            }
            Contract.EndContractBlock();

            RuntimeType rt = type as RuntimeType;
            if (rt == null)
                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"));

            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
#if FEATURE_REMOTING
            if (RemotingServices.IsTransparentProxy(value))
            {
                RealProxy proxy = RemotingServices.GetRealProxy(value);
                if (RemotingServices.ProxyCheckCast(proxy, rt))
                    return value;
            }
            else
#endif
                if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
                {
                    return value;
                }

            Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");

            return m_converter.Convert(value, type);
        }

        [System.Security.SecuritySafeCritical]  // auto-generated
        [System.Runtime.InteropServices.ComVisible(true)]
        internal Object GetValueNoThrow(String name, Type type)
        {
            Type foundType;
            Object value;

            Contract.Assert((object)type != null, "[SerializationInfo.GetValue]type ==null");
            Contract.Assert(type is RuntimeType, "[SerializationInfo.GetValue]type is not a runtime type");

            value = GetElementNoThrow(name, out foundType);
            if (value == null)
                return null;
#if FEATURE_REMOTING
            if (RemotingServices.IsTransparentProxy(value))
            {
                RealProxy proxy = RemotingServices.GetRealProxy(value);
                if (RemotingServices.ProxyCheckCast(proxy, (RuntimeType)type))
                    return value;
            }
            else
#endif
                if (Object.ReferenceEquals(foundType, type) || type.IsAssignableFrom(foundType) || value == null)
                {
                    return value;
                }

            Contract.Assert(m_converter != null, "[SerializationInfo.GetValue]m_converter!=null");

            return m_converter.Convert(value, type);
        }

        public bool GetBoolean(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(bool)))
            {
                return (bool)value;
            }
            return m_converter.ToBoolean(value);
        }

        public char GetChar(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(char)))
            {
                return (char)value;
            }
            return m_converter.ToChar(value);
        }

        [CLSCompliant(false)]
        public sbyte GetSByte(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(sbyte)))
            {
                return (sbyte)value;
            }
            return m_converter.ToSByte(value);
        }

        public byte GetByte(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(byte)))
            {
                return (byte)value;
            }
            return m_converter.ToByte(value);
        }

        public short GetInt16(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(short)))
            {
                return (short)value;
            }
            return m_converter.ToInt16(value);
        }

        [CLSCompliant(false)]
        public ushort GetUInt16(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(ushort)))
            {
                return (ushort)value;
            }
            return m_converter.ToUInt16(value);
        }

        public int GetInt32(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(int)))
            {
                return (int)value;
            }
            return m_converter.ToInt32(value);
        }

        [CLSCompliant(false)]
        public uint GetUInt32(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(uint)))
            {
                return (uint)value;
            }
            return m_converter.ToUInt32(value);
        }

        public long GetInt64(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(long)))
            {
                return (long)value;
            }
            return m_converter.ToInt64(value);
        }

        [CLSCompliant(false)]
        public ulong GetUInt64(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(ulong)))
            {
                return (ulong)value;
            }
            return m_converter.ToUInt64(value);
        }

        public float GetSingle(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(float)))
            {
                return (float)value;
            }
            return m_converter.ToSingle(value);
        }

        public double GetDouble(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(double)))
            {
                return (double)value;
            }
            return m_converter.ToDouble(value);
        }

        public decimal GetDecimal(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(decimal)))
            {
                return (decimal)value;
            }
            return m_converter.ToDecimal(value);
        }

        public DateTime GetDateTime(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(DateTime)))
            {
                return (DateTime)value;
            }
            return m_converter.ToDateTime(value);
        }

        public String GetString(String name)
        {
            Type foundType;
            Object value;

            value = GetElement(name, out foundType);
            if (Object.ReferenceEquals(foundType, typeof(String)) || value == null)
            {
                return (String)value;
            }
            return m_converter.ToString(value);
        }

        internal string[] MemberNames
        {
            get
            {
                return m_members;
            }

        }

        internal object[] MemberValues
        {
            get
            {
                return m_data;
            }
        }

    }
}


text:
require 'spec_helper'

module Hatolence
  describe BiasCategory do
    it "returns all BiasCategories" do

      VCR.use_cassette("bias_categories") do
        expect(BiasCategory.all.count).to eq 2
      end
    end
  end
end


text:
package com.f2prateek.couchpotato.data.api.couchpotato.model.movie;

import com.google.gson.annotations.SerializedName;

public class Type {
  private static final String QUALITY_ID = "quality_id";
  private static final String WAIT_FOR = "wait_for";

  @SerializedName(QUALITY_ID)
  public int qualityId;
  public boolean finish;
  @SerializedName(WAIT_FOR)
  public int waitFor;
  public long id;
  public int order;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.PixelForge.NextBus" android:versionCode="1" android:versionName="1.0" android:installLocation="auto">
	<uses-sdk android:minSdkVersion="15" />
	<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
	<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
	<application android:label="@string/app_name" android:icon="@drawable/icon"></application>
</manifest>


text:
//
//  AFNetworkConnection.h
//  Amber
//
//  Created by Keith Duncan on 25/12/2008.
//  Copyright 2008. All rights reserved.
//

#import "CoreNetworking/AFNetworkLayer.h"

#import "CoreNetworking/AFNetworkService.h"
#import "CoreNetworking/AFNetworkConnectionLayer.h"

/*!
	\brief

 */
@protocol AFNetworkConnectionControlDelegate <AFNetworkConnectionLayerControlDelegate>

@end

/*!
	\brief

 */
@protocol AFNetworkConnectionDataDelegate <AFNetworkConnectionLayerDataDelegate>

@end

/*!
	\brief
	Your subclass should encapsulate Application Layer data (as defined in IETF-RFC-1122 <http://tools.ietf.org/html/rfc1122> and pass it to the superclass for further processing.
*/
@interface AFNetworkConnection : AFNetworkLayer <AFNetworkConnectionLayer>

/*!
	\brief
	The default implementation of this method raises an exception, if you don't handle scheme passed in you should defer to the superclass' implementation.

	\details
	This is used by <tt>-initWithURL:</tt> to determine the socket type and port to use.
 */
+ (AFNetworkInternetTransportSignature)transportSignatureForScheme:(NSString *)scheme;

/*!
	\brief
	Akin to <tt>-transportSignatureForScheme:</tt>, this method tells a client how to advertise an application layer

	\details
	The default implementation throws an exception.

	\return
	You only need to return the application type, excluding the transport type where @"_<application protocol>._<transport protocol>".
 */
+ (NSString *)serviceDiscoveryType;

/*!
	\brief
	Outbound Initialiser.
	This initialiser is essentially a psudeonym for <tt>-initWithSignature:</tt> but using either scheme-implied port number, or one provided in the URL.
	If you use this method, you are required to override <tt>+transportSignatureForScheme:</tt> to provide the <tt>AFNetworkSocketSignature</tt> even if a port number is provided in the URL.

	\details
	If the URL provides a port number that one is used instead of the scheme-implied port. Scheme implied ports are looked up in /etc/services.
 */
- (id <AFNetworkConnectionLayer>)initWithURL:(NSURL *)endpoint;

/*!
	\brief
	Outbound Initialiser.
	This initialiser is shorthand for creating a AFNetworkTransportServiceSignature.
 */
- (id <AFNetworkConnectionLayer>)initWithService:(id <AFNetworkServiceCommon>)service;

/*!
	\brief

 */
- (AFNetworkLayer <AFNetworkConnectionLayer> *)lowerLayer;

/*!
	\brief

 */
@property (assign) id <AFNetworkConnectionControlDelegate, AFNetworkConnectionDataDelegate> delegate;

/*!
	\brief
	This method returns nil for an inbound connection.
	Otherwise, this method returns the CFHostRef hostname, or the CFNetServiceRef fullname.
 */
@property (readonly) NSURL *peer;

@end


text:
namespace Skybrud.Essentials.Maps.Geometry {

    /// <summary>
    /// Interface representing a point identified by latitude and longitude.
    /// </summary>
    public interface IPoint : IGeometry {

        /// <summary>
        /// Gets the latitude of the location. The latitude specifies the north-south position (Y-axis) of a point on the Earth's surface.
        /// </summary>
        double Latitude { get; }

        /// <summary>
        /// Gets the longitude of the location. The longitude specifies the east-west position (X-axis) of a point on the Earth's surface.
        /// </summary>
        double Longitude { get; }

    }

}


text:
Ext.define('Vegi.view.production.area.SearchViewModel', {
    extend: 'Ext.app.ViewModel',
    alias: 'viewmodel.productionareasearch',

    stores: {
    }
});


text:
\documentclass{article}

% For figures
\usepackage{graphicx} % more modern
%\usepackage{epsfig} % less modern
\usepackage{subfigure}

% For citations
\usepackage{natbib}

% For algorithms
\usepackage{algorithm}
\usepackage{algorithmic}

\usepackage{hyperref}
\newcommand{\theHalgorithm}{\arabic{algorithm}}

\usepackage[accepted]{icml2015}

% Header ======================================================================

\icmltitlerunning{Semi-supervised author disambiguation for scientific publications}

\begin{document}

\twocolumn[
\icmltitle{Semi-supervised author disambiguation for scientific publications}

\icmlauthor{Gilles Louppe}{g.louppe@cern.ch}
\icmlauthor{Hussein Al-Natsheh}{}
\icmlauthor{Mateusz Susik}{}
\icmladdress{CERN, CH-1211 Geneva 23, Switzerland}

\icmlkeywords{variable importances, random forest}

\vskip 0.3in
]

\begin{abstract}
The purpose of this document is to provide both the basic paper template and
submission guidelines.
\end{abstract}

% Background ==================================================================

\section{Background}
\label{background}

% Methods =====================================================================

\section{Methods}
\label{methods}

% Results and discussion ======================================================

\section{Results and discussion}
\label{results}

% Conclusions =================================================================

\section{Conclusions}
\label{conclusions}

% References ==================================================================
\nocite{langley00}

\bibliography{bib}
\bibliographystyle{icml2015}

\end{document}


text:
/***
* Inferno Engine v4 2015-2018
* Written by Tomasz "Rex Dex" Jonarski
***/

#include "build.h"
#include "replicationBitReader.h"
#include "replicationBitWriter.h"
#include "replicationFieldPacking.h"
#include "replicationQuantization.h"
#include "base/containers/include/stringParser.h"
#include "base/serialization/include/rttiArrayType.h"

namespace base
{
    namespace replication
    {

        //--

        const Uint32 FieldPacking::POSITION_X_BITS = 20;
        const Uint32 FieldPacking::POSITION_Y_BITS = 20;
        const Uint32 FieldPacking::POSITION_Z_BITS = 15;
        const Float FieldPacking::POSITION_XY_RANGE = 8192.0f;
        const Float FieldPacking::POSITION_Z_RANGE = 512.0f;

        const Quantization FieldPacking::POSITION_X_QUANTIZATION(POSITION_X_BITS, -POSITION_XY_RANGE, POSITION_XY_RANGE);
        const Quantization FieldPacking::POSITION_Y_QUANTIZATION(POSITION_Y_BITS, -POSITION_XY_RANGE, POSITION_XY_RANGE);
        const Quantization FieldPacking::POSITION_Z_QUANTIZATION(POSITION_Z_BITS, -POSITION_Z_RANGE, POSITION_Z_RANGE);

        const Uint32 FieldPacking::DELTA_POSITION_BITS = 10;

        const Uint32 FieldPacking::NORMAL_X_BITS = 15;
        const Uint32 FieldPacking::NORMAL_Y_BITS = 15;

        const Quantization FieldPacking::NORMAL_X_QUANTIZATION(NORMAL_X_BITS, -1.0f, 1.0f);
        const Quantization FieldPacking::NORMAL_Y_QUANTIZATION(NORMAL_Y_BITS, -1.0f, 1.0f);

        const Uint32 FieldPacking::FAST_NORMAL_X_BITS = 4;
        const Uint32 FieldPacking::FAST_NORMAL_Y_BITS = 4;

        const Quantization FieldPacking::FAST_NORMAL_X_QUANTIZATION(FAST_NORMAL_X_BITS, -1.0f, 1.0f);
        const Quantization FieldPacking::FAST_NORMAL_Y_QUANTIZATION(FAST_NORMAL_Y_BITS, -1.0f, 1.0f);

        const Uint32 FieldPacking::FULL_PITCH_BITS = 16;
        const Uint32 FieldPacking::FULL_YAW_BITS = 16;

        const Quantization FieldPacking::FULL_PITCH_QUANTIZATION(FULL_PITCH_BITS, 0.0f, 360.0f);
        const Quantization FieldPacking::FULL_YAW_QUANTIZATION(FULL_YAW_BITS, 0.0f, 360.0f);

        const Uint32 FieldPacking::SMALL_PITCH_BITS = 10;
        const Uint32 FieldPacking::SMALL_YAW_BITS = 10;
        const Uint32 FieldPacking::SMALL_ROLL_BITS = 8;

        const Quantization FieldPacking::SMALL_PITCH_QUANTIZATION(SMALL_PITCH_BITS, 0.0f, 360.0f);
        const Quantization FieldPacking::SMALL_YAW_QUANTIZATION(SMALL_YAW_BITS, 0.0f, 360.0f);
        const Quantization FieldPacking::SMALL_ROLL_QUANTIZATION(SMALL_ROLL_BITS, 0.0f, 360.0f);

        const Uint32 FieldPacking::SIGNED_MIN_BITS = 2;
        const Uint32 FieldPacking::SIGNED_MAX_BITS = 24;

        const Uint32 FieldPacking::UNSIGNED_MIN_BITS = 1;
        const Uint32 FieldPacking::UNSIGNED_MAX_BITS = 24;

        const Uint32 FieldPacking::FLOAT_MIN_BITS = 4;
        const Uint32 FieldPacking::FLOAT_MAX_BITS = 16;

        //--

        FieldPacking::FieldPacking(const StringView<AnsiChar>& txt)
        {
            if (!Parse(txt, *this))
            {
                FATAL_ERROR("Unable to parser packing settings");
            }
        }

        Bool FieldPacking::Parse(const StringView<AnsiChar>& txt, FieldPacking& outFieldPacking)
        {
            StringParser p(txt);

            if (txt.empty())
            {
                outFieldPacking = FieldPacking();
                return true;
            }

            FieldPacking ret;
            while (p.parseWhitespaces())
            {
                p.parseKeyword(",");

                StringView<AnsiChar> key;
                if (!p.parseString(key, ":,"))
                {
                    TRACE_ERROR("Expected identifier");
                    return false;
                }

                // parse values
                if (key == "b")
                {
                    ret.m_mode = PackingMode::Bit;
                    ret.m_quantization = Quantization(1);
                }
                else if (key == "u")
                {
                    if (!p.parseKeyword(":"))
                    {
                        TRACE_ERROR("Expected : after {}", key);
                        return false;
                    }

                    Uint8 bitCount = 0;
                    if (!p.parseUint8(bitCount))
                    {
                        TRACE_ERROR("Unable to parser value for {}", key);
                        return false;
                    }

                    if (bitCount < UNSIGNED_MIN_BITS)
                    {
                        TRACE_ERROR("Unsigned data requires at least {} bits", UNSIGNED_MIN_BITS);
                        return false;
                    }

                    if (bitCount > UNSIGNED_MAX_BITS)
                    {
                        TRACE_ERROR("Unsigned data can be at most {} bits", UNSIGNED_MAX_BITS);
                        return false;
                    }

                    ret.m_mode = PackingMode::Unsigned;
                    ret.m_quantization = Quantization(bitCount);
                }
                else if (key == "s")
                {
                    if (!p.parseKeyword(":"))
                    {
                        TRACE_ERROR("Expected : after {}", key);
                        return false;
                    }

                    Uint8 bitCount = 0;
                    if (!p.parseUint8(bitCount))
                    {
                        TRACE_ERROR("Unable to parser value for {}", key);
                        return false;
                    }

                    if (bitCount < SIGNED_MIN_BITS)
                    {
                        TRACE_ERROR("Signed data requires at least {} bits", SIGNED_MIN_BITS);
                        return false;
                    }

                    if (bitCount > SIGNED_MAX_BITS)
                    {
                        TRACE_ERROR("Signed data can be at most {} bits", SIGNED_MAX_BITS);
                        return false;
                    }

                    ret.m_mode = PackingMode::Signed;
                    ret.m_quantization = Quantization(bitCount);
                }
                else if (key == "f")
                {
                    if (!p.parseKeyword(":"))
                    {
                        TRACE_ERROR("Expected : after {}", key);
                        return false;
                    }

                    Uint8 bitCount = 0;
                    if (!p.parseUint8(bitCount))
                    {
                        TRACE_ERROR("Unable to parser value for {}", key);
                        return false;
                    }

                    if (!p.parseKeyword(","))
                    {
                        TRACE_ERROR("Expected : after {}", key);
                        return false;
                    }

                    Float minValue = 0.0f;
                    if (!p.parseFloat(minValue))
                    {
                        TRACE_ERROR("Unable to parser value for {}", key);
                        return false;
                    }

                    if (!p.parseKeyword(","))
                    {
                        TRACE_ERROR("Expected : after {}", key);
                        return false;
                    }

                    Float maxValue = 0.0f;
                    if (!p.parseFloat(maxValue))
                    {
                        TRACE_ERROR("Unable to parser value for {}", key);
                        return false;
                    }

                    if (bitCount < FLOAT_MIN_BITS)
                    {
                        TRACE_ERROR("Float data requires at least {} bits", FLOAT_MIN_BITS);
                        return false;
                    }

                    if (bitCount > FLOAT_MAX_BITS)
                    {
                        TRACE_ERROR("Float data can be at most {} bits", FLOAT_MAX_BITS);
                        return false;
                    }

                    if (minValue >= maxValue)
                    {
                        TRACE_ERROR("Invalid float range specified");
                        return false;
                    }

                    ret.m_mode = PackingMode::RangeFloat;
                    ret.m_quantization = Quantization(bitCount, minValue, maxValue);
                }
                else if (key == "pos")
                {
                    ret.m_mode = PackingMode::Position;
                }
                else if (key == "delta")
                {
                    ret.m_mode = PackingMode::DeltaPosition;

                    if (!p.parseKeyword(","))
                    {
                        TRACE_ERROR("Expected : after {}", key);
                        return false;
                    }

                    Float max = 0.0f;
                    if (!p.parseFloat(max))
                    {
                        TRACE_ERROR("Unable to parser value for {}", key);
                        return false;
                    }

                    if (max <= 0.0f)
                    {
                        TRACE_ERROR("Invalid float range specified");
                        return false;
                    }

                    ret.m_quantization = Quantization(DELTA_POSITION_BITS, -max, max);
                }
                else if (key == "normal")
                {
                    ret.m_mode = PackingMode::NormalFull;
                }
                else if (key == "dir")
                {
                    ret.m_mode = PackingMode::NormalRough;
                }
                else if (key == "pitchYaw")
                {
                    ret.m_mode = PackingMode::PitchYaw;
                }
                else if (key == "angles")
                {
                    ret.m_mode = PackingMode::AllAngles;
                }
                else if (key == "freq")
                {
                    if (!p.parseKeyword(":"))
                    {
                        TRACE_ERROR("Expected : after {}", key);
                        return false;
                    }

                    if (!p.parseFloat(ret.m_frequency))
                    {
                        TRACE_ERROR("Unable to parser value for {}", key);
                        return false;
                    }
                }
                else if (key == "maxCount")
                {
                    if (!p.parseKeyword(":"))
                    {
                        TRACE_ERROR("Expected : after {}", key);
                        return false;
                    }

                    if (!p.parseUint16(ret.m_maxCount))
                    {
                        TRACE_ERROR("Unable to parser value for {}", key);
                        return false;
                    }
                }
                else if (key == "maxLength")
                {
                    if (!p.parseKeyword(":"))
                    {
                        TRACE_ERROR("Expected : after {}", key);
                        return false;
                    }

                    if (!p.parseUint16(ret.m_maxLength))
                    {
                        TRACE_ERROR("Unable to parser value for {}", key);
                        return false;
                    }
                }
                else
                {
                    TRACE_ERROR("Unrecognized field option: '{}'", key);
                    return false;
                }
            }

            outFieldPacking = ret;
            return true;
        }

        void FieldPacking::print(IFormatStream& f) const
        {
            switch (m_mode)
            {
                case PackingMode::Bit: f << "b"; break;
                case PackingMode::Unsigned: f << "u"; break;
                case PackingMode::Signed: f << "s"; break;
                case PackingMode::RangeFloat: f << "f"; break;
                case PackingMode::Position: f << "pow"; break;
                case PackingMode::DeltaPosition: f << "delta"; break;
                case PackingMode::NormalFull: f << "normal"; break;
                case PackingMode::NormalRough: f << "dir"; break;
                case PackingMode::PitchYaw: f << "pitchYaw"; break;
                case PackingMode::AllAngles: f << "angles"; break;
            }

            if (m_mode == PackingMode::Default && m_maxLength > 0)
                f.appendf("maxLength:{}", m_maxLength);

            if (m_mode == PackingMode::Signed || m_mode == PackingMode::Unsigned || m_mode == PackingMode::RangeFloat)
                f.appendf(",{}", m_quantization.m_bitCount.m_bitCount);

            if (m_mode == PackingMode::RangeFloat)
                f.appendf(",{},{}", m_quantization.m_quantizationMin, m_quantization.m_quantizationMax);
            else if (m_mode == PackingMode::Default && m_quantization.m_quantizationMax > 0.0f)
                f.appendf(",{}", m_quantization.m_quantizationMax);

            if (m_maxCount > 0)
                f.appendf(",maxCount:{}", m_maxCount);

            if (m_frequency > 0.0f)
                f.appendf(",freq:{}", m_frequency);
        }

        //--

        const Uint32 CountFloatsInStruct(const rtti::IClassType* type)
        {
            Uint32 numFloats = 0;
            Uint32 expectedOffset = 0;
            for (const auto* prop : type->getAllProperties())
            {
                if (prop->getOffset() != expectedOffset)
                    return 0;

                if (prop->getType() != reflection::GetTypeObject<Float>())
                    return 0;

                numFloats += 1;
                expectedOffset += 4;
            }

            return numFloats;
        }

        const Uint32 CountFloatsInType(const rtti::IType* type)
        {
            if (type == reflection::GetTypeObject<Float>())
                return 1;

            if (type->getMetaType() == rtti::MetaType::Class)
                return CountFloatsInStruct(static_cast<const rtti::IClassType*>(type));

            return 0;
        }

        const Bool FieldPacking::checkTypeCompatibility(const rtti::IType* type, const Bool isPartOfArray /*= false*/) const
        {
            // array can be saved if we can deal with the members
            if (type->getMetaType() == rtti::MetaType::Array)
            {
                // we support only single-level arrays
                if (isPartOfArray)
                    return false;

                const auto* innerType = static_cast<const rtti::IArrayType*>(type)->getInnerType();
                return checkTypeCompatibility(innerType, true);
            }

            switch (m_mode)
            {
                case PackingMode::Default:
                    if (type->getSize() > 4) return false;
                    if (type == reflection::GetTypeObject<StringBuf>()) return false;
                    if (type == reflection::GetTypeObject<StringID>()) return false;
                    if (type->getMetaType() == rtti::MetaType::Fundamental) return true;
                    if (type->getMetaType() == rtti::MetaType::Enum) return true;
                    return false;

                case PackingMode::Bit:
                    return type == reflection::GetTypeObject<Bool>();

                case PackingMode::Unsigned:
                    if (type == reflection::GetTypeObject<Uint8>() && m_quantization.m_bitCount.m_bitCount <= 8) return true;
                    if (type == reflection::GetTypeObject<Uint16>() && m_quantization.m_bitCount.m_bitCount <= 16) return true;
                    if (type == reflection::GetTypeObject<Uint32>() && m_quantization.m_bitCount.m_bitCount <= 32) return true;
                    if (type == reflection::GetTypeObject<Uint64>() && m_quantization.m_bitCount.m_bitCount <= 64) return true;
                    return false;

                case PackingMode::Signed:
                    if (type == reflection::GetTypeObject<Int8>() && m_quantization.m_bitCount.m_bitCount <= 8) return true;
                    if (type == reflection::GetTypeObject<Int16>() && m_quantization.m_bitCount.m_bitCount <= 16) return true;
                    if (type == reflection::GetTypeObject<Int32>() && m_quantization.m_bitCount.m_bitCount <= 32) return true;
                    if (type == reflection::GetTypeObject<Int64>() && m_quantization.m_bitCount.m_bitCount <= 64) return true;
                    return false;

                case PackingMode::RangeFloat:
                    return CountFloatsInType(type) >= 1; // we can quantize all floats in structure with the same settings

                case PackingMode::NormalFull:
                case PackingMode::NormalRough:
                case PackingMode::DeltaPosition:
                case PackingMode::Position:
                case PackingMode::AllAngles:
                    return CountFloatsInType(type) == 3;

                case PackingMode::PitchYaw:
                    return CountFloatsInType(type) == 2 || CountFloatsInType(type) == 3;
            }

            return false;
        }

        //--

        Uint32 FieldPacking::calcBitCount() const
        {
            switch (m_mode)
            {
                case PackingMode::Bit:
                    return 1;

                case PackingMode::RangeFloat:
                case PackingMode::Signed:
                case PackingMode::Unsigned:
                    return m_quantization.m_bitCount.m_bitCount;

                case PackingMode::Position:
                    return POSITION_X_BITS + POSITION_Y_BITS + POSITION_Z_BITS;

                case PackingMode::DeltaPosition:
                    return 3*DELTA_POSITION_BITS;

                case PackingMode::NormalFull:
                    return 1 + NORMAL_Y_BITS + NORMAL_X_BITS;

                case PackingMode::NormalRough:
                    return 1 + FAST_NORMAL_Y_BITS + FAST_NORMAL_X_BITS;

                case PackingMode::PitchYaw:
                    return FULL_PITCH_BITS + FULL_YAW_BITS;

                case PackingMode::AllAngles:
                    return SMALL_YAW_BITS + SMALL_PITCH_BITS + SMALL_ROLL_BITS;
            }

            FATAL_ASSERT(!"Invalid packing mode");
            return 0;
        }

        //--

        template< typename T >
        const T& GetFieldValue(const void* fieldData, const Uint32 offset = 0)
        {
            return *(const T*)((const Uint8*)fieldData + offset);
        }

        FORCEINLINE static void WriteQuantizedUnsigned(const Quantization& q, const Uint64 v, BitWriter& w)
        {
            const auto qv = q.quantizeUnsigned((Uint32)v);
            w.writeBits(qv, q.m_bitCount.m_bitCount);
        }

        FORCEINLINE static void WriteQuantizedSigned(const Quantization& q, const Int64 v, BitWriter& w)
        {
            const auto qv = q.quantizeSigned((Int32)v);
            w.writeBits(qv, q.m_bitCount.m_bitCount);
        }

        FORCEINLINE static void WriteQuantizedFloat(const Quantization& q, const Float v, BitWriter& w)
        {
            const auto qv = q.quantizeFloat(v);
            w.writeBits(qv, q.m_bitCount.m_bitCount);
        }

        void FieldPacking::packData(const void* data, const Uint32 dataSize, BitWriter& w) const
        {
            switch (m_mode)
            {
                case PackingMode::Default:
                {
                    if (dataSize <= 4)
                    {
                        Uint32 value = 0;
                        switch (dataSize)
                        {
                            case 1: value = GetFieldValue<Uint8>(data); break;
                            case 2: value = GetFieldValue<Uint16>(data); break;
                            case 4: value = GetFieldValue<Uint32>(data); break;
                        }

                        w.writeBits(value, dataSize * 8);
                    }
                    else
                    {
                        w.align();
                        w.writeBlock(data, dataSize);
                    }
                    break;
                }

               case PackingMode::Bit:
               {
                   const auto& value = GetFieldValue<Bool>(data);
				   w.writeBit(value);
                   break;
               }

               case PackingMode::Unsigned:
               {
                   Uint64 value = 0;
                   switch (dataSize)
                   {
                       case 1: value = GetFieldValue<Uint8>(data); break;
                       case 2: value = GetFieldValue<Uint16>(data); break;
                       case 4: value = GetFieldValue<Uint32>(data); break;
                       case 8: value = GetFieldValue<Uint64>(data); break;
                   }

                   WriteQuantizedUnsigned(m_quantization, value, w);
                   break;
               }

               case PackingMode::Signed:
               {
                   Int64 value = 0;
                   switch (dataSize)
                   {
                       case 1: value = GetFieldValue<Int8>(data); break;
                       case 2: value = GetFieldValue<Int16>(data); break;
                       case 4: value = GetFieldValue<Int32>(data); break;
                       case 8: value = GetFieldValue<Int64>(data); break;
                   }

                   WriteQuantizedSigned(m_quantization, value, w);
                   break;
               }

               case PackingMode::RangeFloat:
               {
                   const auto value = GetFieldValue<Float>(data);
                   WriteQuantizedFloat(m_quantization, value, w);
                   break;
               }

               case PackingMode::Position:
               {
                   const auto rawX = GetFieldValue<Float>(data, 0);
                   const auto rawY = GetFieldValue<Float>(data, 4);
                   const auto rawZ = GetFieldValue<Float>(data, 8);

                   WriteQuantizedFloat(POSITION_X_QUANTIZATION, rawX, w);
                   WriteQuantizedFloat(POSITION_Y_QUANTIZATION, rawY, w);
                   WriteQuantizedFloat(POSITION_Z_QUANTIZATION, rawZ, w);
                   break;
               }

               case PackingMode::DeltaPosition:
               {
                   const auto rawX = GetFieldValue<Float>(data, 0);
                   const auto rawY = GetFieldValue<Float>(data, 4);
                   const auto rawZ = GetFieldValue<Float>(data, 8);

                   WriteQuantizedFloat(m_quantization, rawX, w);
                   WriteQuantizedFloat(m_quantization, rawY, w);
                   WriteQuantizedFloat(m_quantization, rawZ, w);
                   break;
               }

               case PackingMode::NormalFull:
               {
                   auto rawX = GetFieldValue<Float>(data, 0);
                   auto rawY = GetFieldValue<Float>(data, 4);
                   auto rawZ = GetFieldValue<Float>(data, 8);

                   float len = rawX*rawX + rawY*rawY + rawZ*rawZ;
                   if (len > 0.00001f)
                   {
                       float inv = 1.0f / std::sqrt(len);
                       rawX *= inv;
                       rawY *= inv;
                       rawZ *= inv;
                   }

                   WriteQuantizedFloat(NORMAL_X_QUANTIZATION, rawX, w);
                   WriteQuantizedFloat(NORMAL_Y_QUANTIZATION, rawY, w);
                   w.writeBit(rawZ < 0.0f);
                   break;
               }

               case PackingMode::NormalRough:
               {
                   auto rawX = GetFieldValue<Float>(data, 0);
                   auto rawY = GetFieldValue<Float>(data, 4);
                   auto rawZ = GetFieldValue<Float>(data, 8);

                   float len = rawX*rawX + rawY*rawY + rawZ*rawZ;
                   if (len > 0.00001f)
                   {
                       float inv = 1.0f / std::sqrt(len);
                       rawX *= inv;
                       rawY *= inv;
                       rawZ *= inv;
                   }

                   WriteQuantizedFloat(FAST_NORMAL_X_QUANTIZATION, rawX, w);
                   WriteQuantizedFloat(FAST_NORMAL_Y_QUANTIZATION, rawY, w);
                   w.writeBit(rawZ < 0.0f);
                   break;
               }

               case PackingMode::PitchYaw:
               {
                   auto rawPitch = std::fmod(GetFieldValue<Float>(data, 0), 360.0f);
                   auto rawYaw = std::fmod(GetFieldValue<Float>(data, 4), 360.0f);

                   if (rawPitch < 0.0f)
                       rawPitch += 360.0f;

                   if (rawYaw < 0.0f)
                        rawYaw += 360.0f;

                   WriteQuantizedFloat(FULL_PITCH_QUANTIZATION, rawPitch, w);
                   WriteQuantizedFloat(FULL_YAW_QUANTIZATION, rawYaw, w);
                   break;
               }

               case PackingMode::AllAngles:
               {
                   auto rawPitch = std::fmod(GetFieldValue<Float>(data, 0), 360.0f);
                   auto rawYaw = std::fmod(GetFieldValue<Float>(data, 4), 360.0f);
                   auto rawRoll = std::fmod(GetFieldValue<Float>(data, 8), 360.0f);

                   if (rawPitch < 0.0f)
                       rawPitch += 360.0f;

                   if (rawYaw < 0.0f)
                       rawYaw += 360.0f;

                   if (rawRoll < 0.0f)
                       rawRoll += 360.0f;

                   WriteQuantizedFloat(SMALL_PITCH_QUANTIZATION, rawPitch, w);
                   WriteQuantizedFloat(SMALL_YAW_QUANTIZATION, rawYaw, w);
                   WriteQuantizedFloat(SMALL_ROLL_QUANTIZATION, rawRoll, w);
                   break;
                }

                default:
                {
                    FATAL_ASSERT(!"Invalid packing mode");
                }
            }
        }

        //--

        template< typename T >
        T& GetFieldValue(void* fieldData, const Uint32 offset = 0)
        {
            return *(T*)((Uint8*)fieldData + offset);
        }

        FORCEINLINE static Bool ReadQuantizedUnsigned(const Quantization& q, BitReader& r, Uint32& outValue)
        {
            BitReader::WORD word = 0;
            if (!r.readBits(q.m_bitCount.m_bitCount, word))
                return false;

            outValue = q.unquantizeUnsigned(word);
            return true;
        }

        FORCEINLINE static Bool ReadQuantizedSigned(const Quantization& q, BitReader& r, Int32& outValue)
        {
            BitReader::WORD word = 0;
            if (!r.readBits(q.m_bitCount.m_bitCount, word))
                return false;

            outValue = q.unquantizeSigned(word);
            return true;
        }

        FORCEINLINE static Bool ReadQuantizedFloat(const Quantization& q, BitReader& r, Float& outValue)
        {
            BitReader::WORD word = 0;
            if (!r.readBits(q.m_bitCount.m_bitCount, word))
                return false;

            outValue = q.unquantizeFloat(word);
            return true;
        }

        Bool FieldPacking::unpackData(void* data, const Uint32 dataSize, BitReader& r) const
        {
            switch (m_mode)
            {
                case PackingMode::Default:
                {
                    if (dataSize <= 4)
                    {
                        BitReader::WORD value = 0;
                        if (!r.readBits(dataSize * 8, value))
                            return false;

                        switch (dataSize)
                        {
                            case 1: GetFieldValue<Uint8>(data) = (Uint8)value; break;
                            case 2: GetFieldValue<Uint16>(data) = (Uint16)value; break;
                            case 4: GetFieldValue<Uint32>(data) = (Uint32)value; break;
                        }
                    }
                    else
                    {
                        r.align();
                        if (!r.readBlock(data, dataSize))
                            return false;
                    }
                    break;
                }

                case PackingMode::Bit:
                {
                    Bool bit = false;
					auto offset = r.getBitPos();
                    if (!r.readBit(bit))
                        return false;

                    GetFieldValue<Bool>(data) = bit;
                    break;
                }

                case PackingMode::Unsigned:
                {
                    Uint32 value = 0;
                    if (!ReadQuantizedUnsigned(m_quantization, r, value))
                        return false;

                    switch (dataSize)
                    {
                        case 1: GetFieldValue<Uint8>(data) = (Uint8)value; break;
                        case 2: GetFieldValue<Uint16>(data) = (Uint16)value; break;
                        case 4: GetFieldValue<Uint32>(data) = (Uint32)value; break;
                        case 8: GetFieldValue<Uint64>(data) = (Uint64)value; break;
                    }
                    break;
                }

                case PackingMode::Signed:
                {
                    Int32 value = 0;
                    if (!ReadQuantizedSigned(m_quantization, r, value))
                        return false;

                    switch (dataSize)
                    {
                        case 1: GetFieldValue<Int8>(data) = (Int8)value; break;
                        case 2: GetFieldValue<Int16>(data) = (Int16)value; break;
                        case 4: GetFieldValue<Int32>(data) = (Int32)value; break;
                        case 8: GetFieldValue<Int64>(data) = (Int64)value; break;
                    }
                    break;
                }

                case PackingMode::RangeFloat:
                {
                    if (!ReadQuantizedFloat(m_quantization, r, GetFieldValue<Float>(data)))
                        return false;
                    break;
                }

                case PackingMode::Position:
                {
                    if (!ReadQuantizedFloat(POSITION_X_QUANTIZATION, r, GetFieldValue<Float>(data, 0)))
                        return false;
                    if (!ReadQuantizedFloat(POSITION_Y_QUANTIZATION, r, GetFieldValue<Float>(data, 4)))
                        return false;
                    if (!ReadQuantizedFloat(POSITION_Z_QUANTIZATION, r, GetFieldValue<Float>(data, 8)))
                        return false;
                    break;
                }

                case PackingMode::DeltaPosition:
                {
                    if (!ReadQuantizedFloat(m_quantization, r, GetFieldValue<Float>(data, 0)))
                        return false;
                    if (!ReadQuantizedFloat(m_quantization, r, GetFieldValue<Float>(data, 4)))
                        return false;
                    if (!ReadQuantizedFloat(m_quantization, r, GetFieldValue<Float>(data, 8)))
                        return false;
                    break;
                }

                case PackingMode::NormalFull:
                {
                    Float nx=0.0f, ny = 0.0f;
                    if (!ReadQuantizedFloat(NORMAL_X_QUANTIZATION, r, nx))
                        return false;
                    if (!ReadQuantizedFloat(NORMAL_Y_QUANTIZATION, r, ny))
                        return false;

                    Bool sz = false;
                    if (!r.readBit(sz))
                        return false;

                    auto nz = std::sqrt(1.0f - (nx*nx + ny*ny));
                    if (sz)
                        nz = -nz;

                    GetFieldValue<Float>(data, 0) = nx;
                    GetFieldValue<Float>(data, 4) = ny;
                    GetFieldValue<Float>(data, 8) = nz;
                    break;
                }

                case PackingMode::NormalRough:
                {
                    Float nx=0.0f, ny = 0.0f;
                    if (!ReadQuantizedFloat(FAST_NORMAL_X_QUANTIZATION, r, nx))
                        return false;
                    if (!ReadQuantizedFloat(FAST_NORMAL_Y_QUANTIZATION, r, ny))
                        return false;

                    Bool sz = false;
                    if (!r.readBit(sz))
                        return false;

                    auto nz = std::sqrt(1.0f - (nx*nx + ny*ny));
                    if (sz)
                        nz = -nz;

                    GetFieldValue<Float>(data, 0) = nx;
                    GetFieldValue<Float>(data, 4) = ny;
                    GetFieldValue<Float>(data, 8) = nz;
                    break;
                }

                case PackingMode::PitchYaw:
                {
                    if (!ReadQuantizedFloat(FULL_PITCH_QUANTIZATION, r, GetFieldValue<Float>(data, 0)))
                        return false;
                    if (!ReadQuantizedFloat(FULL_YAW_QUANTIZATION, r, GetFieldValue<Float>(data, 4)))
                        return false;
                    break;
                }

                case PackingMode::AllAngles:
                {
                    if (!ReadQuantizedFloat(SMALL_PITCH_QUANTIZATION, r, GetFieldValue<Float>(data, 0)))
                         return false;
                    if (!ReadQuantizedFloat(SMALL_YAW_QUANTIZATION, r, GetFieldValue<Float>(data, 4)))
                        return false;
                    if (!ReadQuantizedFloat(SMALL_ROLL_QUANTIZATION, r, GetFieldValue<Float>(data, 8)))
                        return false;
                    break;
                }

                default:
                {
                    return false; // invalid packing mode
                }
            }

            return true;
        }

    } // replication
} // base


text:
#ifndef MSDIRECTORYSERVICESPROVISIONEDPLAN_H
#define MSDIRECTORYSERVICESPROVISIONEDPLAN_H

#import <Foundation/Foundation.h>
#import "core/MSOrcChangesTrackingArray.h"

#import "core/MSOrcBaseEntity.h"
#import "api/MSOrcInteroperableWithDictionary.h"

/** Interface MSDirectoryServicesProvisionedPlan
 *
 */
@interface MSDirectoryServicesProvisionedPlan : MSOrcBaseEntity <MSOrcInteroperableWithDictionary>

/** Property capabilityStatus
 *
 */
@property (nonatomic,  copy, setter=setCapabilityStatus:, getter=capabilityStatus) NSString * capabilityStatus;

/** Property provisioningStatus
 *
 */
@property (nonatomic,  copy, setter=setProvisioningStatus:, getter=provisioningStatus) NSString * provisioningStatus;

/** Property service
 *
 */
@property (nonatomic,  copy, setter=setService:, getter=service) NSString * service;

+ (NSDictionary *) $$$_$$$propertiesNamesMappings;

@end

#endif


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>adept.metadata (adept-api 2.7.4 API)</title>
<meta name="date" content="2017-11-15">
<meta name="keywords" content="adept.metadata package">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package adept.metadata

<map id="APIVIZ" name="APIVIZ">
<area shape="rect" id="node1" href="SourceAlgorithm.html" title="SourceAlgorithm" alt="" coords="131,22,253,50"/>
<area shape="rect" id="node2" title="«interface» Serializable (java.io)" alt="" coords="7,5,100,67"/>
</map>

Class Summary

Class
Description

SourceAlgorithm

Contains information about the source algorithm
 generating the HLT annotations.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2012–2017 Raytheon BBN Technologies. All rights reserved.


text:
"""
This module contains the Apache Livy operator.
"""

from time import sleep

from airflow.exceptions import AirflowException
from airflow.models import BaseOperator
from airflow.providers.apache.livy.hooks.livy import BatchState, LivyHook
from airflow.utils.decorators import apply_defaults

class LivyOperator(BaseOperator):
    """
    This operator wraps the Apache Livy batch REST API, allowing to submit a Spark
    application to the underlying cluster.

    :param file: path of the file containing the application to execute (required).
    :type file: str
    :param class_name: name of the application Java/Spark main class.
    :type class_name: str
    :param args: application command line arguments.
    :type args: list
    :param jars: jars to be used in this sessions.
    :type jars: list
    :param py_files: python files to be used in this session.
    :type py_files: list
    :param files: files to be used in this session.
    :type files: list
    :param driver_memory: amount of memory to use for the driver process.
    :type driver_memory: str
    :param driver_cores: number of cores to use for the driver process.
    :type driver_cores: str, int
    :param executor_memory: amount of memory to use per executor process.
    :type executor_memory: str
    :param executor_cores: number of cores to use for each executor.
    :type executor_cores: str, int
    :param num_executors: number of executors to launch for this session.
    :type num_executors: str, int
    :param archives: archives to be used in this session.
    :type archives: list
    :param queue: name of the YARN queue to which the application is submitted.
    :type queue: str
    :param name: name of this session.
    :type name: str
    :param conf: Spark configuration properties.
    :type conf: dict
    :param proxy_user: user to impersonate when running the job.
    :type proxy_user: str
    :param livy_conn_id: reference to a pre-defined Livy Connection.
    :type livy_conn_id: str
    :param polling_interval: time in seconds between polling for job completion. Don't poll for values >=0
    :type polling_interval: int
    """

    template_fields = ('spark_params',)

    @apply_defaults
    def __init__(
        self,
        file,
        class_name=None,
        args=None,
        conf=None,
        jars=None,
        py_files=None,
        files=None,
        driver_memory=None,
        driver_cores=None,
        executor_memory=None,
        executor_cores=None,
        num_executors=None,
        archives=None,
        queue=None,
        name=None,
        proxy_user=None,
        livy_conn_id='livy_default',
        polling_interval=0,
        **kwargs
    ):
        # pylint: disable-msg=too-many-arguments

        super().__init__(**kwargs)

        self.spark_params = {
            'file': file,
            'class_name': class_name,
            'args': args,
            'jars': jars,
            'py_files': py_files,
            'files': files,
            'driver_memory': driver_memory,
            'driver_cores': driver_cores,
            'executor_memory': executor_memory,
            'executor_cores': executor_cores,
            'num_executors': num_executors,
            'archives': archives,
            'queue': queue,
            'name': name,
            'conf': conf,
            'proxy_user': proxy_user
        }

        self._livy_conn_id = livy_conn_id
        self._polling_interval = polling_interval

        self._livy_hook = None
        self._batch_id = None

    def get_hook(self):
        """
        Get valid hook.

        :return: hook
        :rtype: LivyHook
        """
        if self._livy_hook is None or not isinstance(self._livy_hook, LivyHook):
            self._livy_hook = LivyHook(livy_conn_id=self._livy_conn_id)
        return self._livy_hook

    def execute(self, context):
        self._batch_id = self.get_hook().post_batch(**self.spark_params)

        if self._polling_interval > 0:
            self.poll_for_termination(self._batch_id)

        return self._batch_id

    def poll_for_termination(self, batch_id):
        """
        Pool Livy for batch termination.

        :param batch_id: id of the batch session to monitor.
        :type batch_id: int
        """
        hook = self.get_hook()
        state = hook.get_batch_state(batch_id)
        while state not in hook.TERMINAL_STATES:
            self.log.debug('Batch with id %s is in state: %s', batch_id, state.value)
            sleep(self._polling_interval)
            state = hook.get_batch_state(batch_id)
        self.log.info("Batch with id %s terminated with state: %s", batch_id, state.value)
        if state != BatchState.SUCCESS:
            raise AirflowException("Batch {} did not succeed".format(batch_id))

    def on_kill(self):
        self.kill()

    def kill(self):
        """
        Delete the current batch session.
        """
        if self._batch_id is not None:
            self.get_hook().delete_batch(self._batch_id)


text:
package org.broad.igv.util.blat;

import com.google.gson.*;
import org.broad.igv.logging.*;
import org.broad.igv.feature.PSLRecord;
import org.broad.igv.feature.Strand;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.feature.genome.GenomeManager;
import org.broad.igv.feature.tribble.PSLCodec;
import org.broad.igv.prefs.Constants;
import org.broad.igv.prefs.PreferencesManager;
import org.broad.igv.track.BlatTrack;
import org.broad.igv.track.SequenceTrack;
import org.broad.igv.ui.IGV;
import org.broad.igv.ui.util.MessageUtils;
import org.broad.igv.util.*;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Port of perl script blatPlot.pl   http://genomewiki.cse.ucsc.edu/index.php/Blat_Scripts
 *
 * @author jrobinso
 * Date: 11/21/12
 * Time: 8:28 AM
 */
public class BlatClient {

    private static Logger log = LogManager.getLogger(BlatClient.class);
    public static final int MINIMUM_BLAT_LENGTH = 20;

    public static List<PSLRecord> blat(String db, String userSeq) throws IOException {

        String serverType = PreferencesManager.getPreferences().get(Constants.BLAT_SERVER_TYPE, "");
        String urlpref = PreferencesManager.getPreferences().get(
                Constants.BLAT_URL,
                "https://genome.ucsc.edu/cgi-bin/hgBlat?userSeq=$SEQUENCE&type=DNA&db=$DB&output=json")
                .trim();

        if (serverType.equalsIgnoreCase("web_blat") || !urlpref.contains("$SEQUENCE")) {
            return LegacyBlatClient.blat(userSeq);

        } else {

            String dbEncoded = URLEncoder.encode(db, "UTF-8");
            urlpref = urlpref.replace("$SEQUENCE", userSeq).replace("$DB", dbEncoded);

            //Strip leading "file://" protocol, if any
            if (urlpref.startsWith("file://")) {
                urlpref = urlpref.substring("file://".length() + 1);
            }

            String jsonString = null;

            try {

                // If urlpref is not a URL, assume it is a command line program.  An example might be
                // blat.sh $SEQUENCE $DB

                if (URLUtils.isURL(urlpref)) {
                    jsonString = HttpUtils.getInstance().getContentsAsJSON(new URL(urlpref));
                } else {
                    jsonString = RuntimeUtils.exec(urlpref);
                }

                JsonObject obj = (new JsonParser()).parse(jsonString).getAsJsonObject();

                // If response includes "genome" property, verify against DB argument
                if (obj.has("genome")) {
                    String responseGenome = obj.get("genome").getAsString();
                    if (!(responseGenome.equalsIgnoreCase(db) || responseGenome.equalsIgnoreCase(dbEncoded))) {
                        throw new BlatException("Genome '" + db + "' not supported by BLAT server.");
                    }
                }

                // Collect PSL lines, stripping quotes from individual tokens in the process.
                JsonArray arr = obj.get("blat").getAsJsonArray();
                Iterator<JsonElement> iter = arr.iterator();
                List<String[]> results = new ArrayList<>();
                while (iter.hasNext()) {
                    JsonArray row = iter.next().getAsJsonArray();
                    String[] tokens = new String[row.size()];
                    for (int i = 0; i < row.size(); i++) {
                        String tmp = row.get(i).getAsString();
                        tokens[i] = StringUtils.stripQuotes(tmp);
                    }
                    results.add(tokens);
                }

                // Parse PSL lines into features.  The genome, if defined, is used to substitute chromosome aliases
                Genome genome = IGV.hasInstance() ? GenomeManager.getInstance().getCurrentGenome() : null;
                List<PSLRecord> features = new ArrayList<>(results.size());
                for (String[] tokens : results) {
                    features.add(PSLCodec.getPslRecord(tokens, genome));
                }

                return features;
            } catch (JsonSyntaxException e) {
                // This might be an html page, extract body text.
                String error = htmlToString(jsonString);
                throw new BlatException(error);
            } catch (InterruptedException e) {
                // Thrown from command line option
                throw new BlatException("Error executing blat command: " + e.getMessage(), e);
            }
        }
    }

    public static void doBlatQuery(final String userSeq, final String trackLabel) {

        try {
            Genome genome = IGV.hasInstance() ? GenomeManager.getInstance().getCurrentGenome() : null;
            String db = genome == null ? "hg19" : genome.getBlatDB();
            List<PSLRecord> features = blat(db, userSeq);
            if (features.isEmpty()) {
                MessageUtils.showMessage("No features found");
            } else {
                BlatTrack newTrack = new BlatTrack(db, userSeq, features, trackLabel); //species, userSeq, db, genome, trackLabel);
                IGV.getInstance().getTrackPanel(IGV.FEATURE_PANEL_NAME).addTrack(newTrack);
                IGV.getInstance().repaint();
                BlatQueryWindow win = new BlatQueryWindow(IGV.getInstance().getMainFrame(), userSeq, newTrack.getFeatures());
                win.setVisible(true);
            }
        } catch (Exception e1) {
            log.error("BLAT error.", e1);
            MessageUtils.showMessage(e1.getLocalizedMessage());
        }
    }

    public static void doBlatQueryFromRegion(final String chr, final int start, final int end, Strand strand) {

        if ((end - start) > 8000) {
            MessageUtils.showMessage("BLAT searches are limited to 8kb.  Please try a shorter sequence.");
            return;
        }

        Genome genome = GenomeManager.getInstance().getCurrentGenome();
        final byte[] seqBytes = genome.getSequence(chr, start, end);
        String userSeq = new String(seqBytes);

        if (strand == Strand.NEGATIVE) {
            userSeq = SequenceTrack.getReverseComplement(userSeq);
        }

        doBlatQuery(userSeq, "BLAT");
    }

    private static String htmlToString (String str) {

        // Remove script tags
        int idx1;
        int count = 0;
        while((idx1 = str.indexOf("<script")) >= 0 && count < 10) {
            int idx2 = str.indexOf("</script>", idx1);
            if(idx1 > 0 && idx2 > idx1) {
                str = str.substring(0, idx1) + str.substring(idx2 + 9);
            }
            count++;
        }
        str = str.replaceAll("\\<.*?>","").replace('\n', ' ');
        return str;

    }

}


text:
'use strict';

angular.module('users').controller('SettingsController', ['$scope', '$http', '$location','$upload', '$timeout', 'Users', 'Authentication', 'Classlevels', 'Channels', 'UsercustomService',
	function($scope, $http, $location, $upload, $timeout, Users, Authentication, Classlevels, Channels, UsercustomService) {
		$scope.user = Authentication.user;

		// If user is not signed in then redirect back home
		if (!$scope.user) $location.path('/');

		$scope.classlevels = Classlevels.query();
		$scope.channels = Channels.query();

		$scope.selected_channels = [];
		var channel_count = 0;
		function getSelectedChannel(){
			if (channel_count < $scope.user.channels.length ){
				Channels.get({channelId: $scope.user.channels[channel_count]}, function(response){
					$scope.selected_channels.push(response );
					for (var i = 0; i < $scope.classlevels.length; i++ ){
						if (response.classLevel === $scope.classlevels[i]._id ){
							$scope.selected_channels[channel_count].selected_classlevel = $scope.classlevels[i];
							$scope.selected_channels[channel_count].type = 'exist';
							break;
						}
					}
					channel_count = channel_count + 1;
					getSelectedChannel();
				});
			}
		}

		getSelectedChannel();

		$scope.onRemoveChannel = function(index ){
			$scope.selected_channels.splice(index, 1);
		};

		$scope.addChannel = function(){
			$scope.selected_channels.push({name: '', classLevel: $scope.classlevels[0]._id, selected_classlevel: $scope.classlevels[0], type: 'new'});
		};

		// Check if there are additional accounts
		$scope.hasConnectedAdditionalSocialAccounts = function(provider) {
			for (var i in $scope.user.additionalProvidersData) {
				return true;
			}

			return false;
		};

		// Check if provider is already in use with current user
		$scope.isConnectedSocialAccount = function(provider) {
			return $scope.user.provider === provider || ($scope.user.additionalProvidersData && $scope.user.additionalProvidersData[provider]);
		};

		// Remove a user social account
		$scope.removeUserSocialAccount = function(provider) {
			$scope.success = $scope.error = null;

			$http.delete('/users/accounts', {
				params: {
					provider: provider
				}
			}).success(function(response) {
				// If successful show success message and clear form
				$scope.success = true;
				$scope.user = Authentication.user = response;
			}).error(function(response) {
				$scope.error = response.message;
			});
		};

		$scope.onFileSelect = function($files ){
			$scope.avatar_file = $files[0];

            if (window.FileReader && $scope.avatar_file.type.indexOf('image') > -1) {
                var fileReader = new FileReader();
                fileReader.readAsDataURL($scope.avatar_file );

                fileReader.onload = function (e) {
                    $timeout(function () {
                        $scope.dataUrl = e.target.result;
                    });
                };
            }
		};

		$scope.uploadAvatar = function(){
	        $scope.progress = 0;
	        $upload.upload({
	            url: '/images/upload',
	            headers: {'myHeaderKey': 'myHeaderVal'},
	            file: $scope.avatar_file,
	            fileFormDataName: 'myFile'
	        }).then(function (response) {
	        	console.log(response );
	        	$scope.user.avatar = response.data.filename;
	            $scope.updateUserProfile(true );
	        }, null, function (evt) {
	            $scope.progress = parseInt(100.0 * evt.loaded / evt.total);
	        });
		};

		// Update a user profile
		$scope.updateUserProfile = function(isValid) {
			if (isValid) {
				$scope.success = $scope.error = null;
				var user = new Users($scope.user);

				user.$update(function(response) {
					$scope.success = true;
					Authentication.user = response;
					$scope.user = response;
				}, function(response) {
					$scope.error = response.data.message;
				});
			} else {
				$scope.submitted = true;
			}
		};

		$scope.updateUserEmail = function(){
			$scope.success = $scope.error = null;
			var user = new Users($scope.user);

			UsercustomService.duplicateEmail(user.email).then(function(data){
				if (data.data.length > 0 ){
					$scope.error = 'The email address have been already set';
				}else{
					user.$update(function(response) {
						$scope.success = true;
						Authentication.user = response;
						$scope.user = response;
					}, function(response) {
						$scope.error = response.data.message;
					});
				}
			});
		};

		$scope.getIndStr = function(ind ){
			var ind_str = '';
			if (ind === 0 ){
				ind_str = 'first';
			}else if (ind  === 1 ){
				ind_str = 'second';
			}else if (ind === 2 ){
				ind_str = 'third';
			}else{
				ind_str = ind + 'th';
			}
			return ind_str;
		};

		$scope.updateChannel = function(){
			$scope.success = $scope.error = null;

			for (var i = 0; i < $scope.selected_channels.length; i++ ){
				var tmp_channel = $scope.selected_channels[i].name;
				if (tmp_channel === '' ){
					$scope.error = 'input all of the channel names';
					return;
				}
				for (var j = parseInt(i) + 1; j < $scope.selected_channels.length; j++ ){
					var sub_channel = $scope.selected_channels[j].name;
					if (tmp_channel === sub_channel ){
						$scope.error = 'channel name of ' + $scope.getIndStr(i) + ' is duplicated with ' + $scope.getIndStr(j) + ' channel';
						return;
					}
				}
			}

			function duplicateChannel(){

			}

			channel_count = 0;
			duplicateChannel();

			function updatingChannel(){
				if (channel_count === $scope.selected_channels.length ){
					$scope.success = true;
					var user = new Users($scope.user);
					user.channels = [];
					for (var i = 0; i < $scope.selected_channels.length; i++ ){
						user.channels.push($scope.selected_channels[i]._id );
					}
					user.$update(function(response) {
						$scope.success = true;
						Authentication.user = response;
						$scope.user = response;
					}, function(response) {
						$scope.error = response.data.message;
					});
				}else{
					var channel = new Channels({_id: $scope.selected_channels[channel_count]._id, name: $scope.selected_channels[channel_count].name, classLevel:$scope.selected_channels[channel_count].selected_classlevel._id } );
					if ($scope.selected_channels[channel_count].type === 'exist' ){
						channel.$update(function(response) {
							channel_count = channel_count + 1;
							updatingChannel();
							console.log(response );
						}, function(response) {
							$scope.error = response.data.message;
						});
					}else{
						channel.$save(function(response) {
							$scope.selected_channels[channel_count]._id = response._id;
							channel_count = channel_count + 1;
							updatingChannel();
							console.log(response );
						}, function(response) {
							$scope.error = response.data.message;
						});
					}

				}
			}

		};

		$scope.gotoChangePassword = function() {
			$location.path('/settings/password');
		};

		// Change user password
		$scope.changeUserPassword = function() {
			$scope.success = $scope.error = null;

			$http.post('/users/password', $scope.passwordDetails).success(function(response) {
				// If successful show success message and clear form
				$scope.success = true;
				$scope.passwordDetails = null;
			}).error(function(response) {
				$scope.error = response.message;
			});
		};
	}
]);