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

namespace OpenTNF.Library.Model
{
    public interface ITnfNetworkReference
    {
        string PropertyOid { get; }
        int? NetworkReferenceType { get; }
        string NetworkElementRef { get; }
        int? ApplicableDirection { get; }
        int? ApplicableSide { get; }
        int? SeqNo { get; }
        string TurnOidLinearElementFrom { get; }
        int? TurnFromDirection { get; }
        string TurnOidLinearElementTo { get; }
        int? TurnToDirection { get; }
        double? Measure1 { get; }
        double? Measure2 { get; }
        bool? IsPreferred { get; }
        string Lanecode { get; }
        int? LinkRole { get; }
        bool? IsHost { get; }
    }

    public class TnfNetworkReference : ITnfNetworkReference
    {
        public string PropertyOid { get; set; }
        public int? NetworkReferenceType { get; set; }
        public string NetworkElementRef { get; set; }
        public int? ApplicableDirection { get; set; }
        public int? ApplicableSide { get; set; }
        public int? SeqNo { get; set; }
        public string TurnOidLinearElementFrom { get; set; }
        public int? TurnFromDirection { get; set; }
        public string TurnOidLinearElementTo { get; set; }
        public int? TurnToDirection { get; set; }
        public double? Measure1 { get; set; }
        public double? Measure2 { get; set; }
        public bool? IsPreferred { get; set; }
        public string Lanecode { get; set; }
        public int? LinkRole { get; set; }
        public bool? IsHost { get; set; }

        public override bool Equals(object obj)
        {
            if (obj is TnfNetworkReference)
            {
                var v = obj as TnfNetworkReference;

                if (PropertyOid == v.PropertyOid &&
                    NetworkReferenceType == v.NetworkReferenceType &&
                    NetworkElementRef == v.NetworkElementRef &&
                    ApplicableDirection == v.ApplicableDirection &&
                    ApplicableSide == v.ApplicableSide &&
                    SeqNo == v.SeqNo &&
                    TurnOidLinearElementFrom == v.TurnOidLinearElementFrom &&
                    TurnFromDirection == v.TurnFromDirection &&
                    TurnOidLinearElementTo == v.TurnOidLinearElementTo &&
                    TurnToDirection == v.TurnToDirection &&
                    Measure1 == v.Measure1 &&
                    Measure2 == v.Measure2 &&
                    IsPreferred == v.IsPreferred &&
                    Lanecode == v.Lanecode &&
                    LinkRole == v.LinkRole &&
                    IsHost == v.IsHost)
                {
                    return true;
                }
            }

            return false;
        }

        public override int GetHashCode()
        {
            return Hashing.RsHash(
                PropertyOid,
                NetworkReferenceType,
                NetworkElementRef,
                ApplicableDirection,
                ApplicableSide,
                SeqNo,
                TurnOidLinearElementFrom,
                TurnFromDirection,
                TurnOidLinearElementTo,
                TurnToDirection,
                Measure1,
                Measure2,
                IsPreferred,
                Lanecode,
                LinkRole,
                IsHost);
        }

        public override string ToString()
        {
            return String.Format(
                "TnfNetworkReference: PropertyOid = {0}, NetworkReferenceType = {1}, NetworkElementRef = {2}, " +
                "ApplicableDirection = {3}, ApplicableSide = {4}, SeqNo = {5}, TurnOidLinearElementFrom = {6}, TurnFromDirection = {7}, " +
                "TurnOidLinearElementTo = {8}, TurnToDirection = {9}, Measure1 = {10}, Measure2 = {11}, IsPreferred = {12}, " +
                "Lanecode = {13}, LinkRole = {14}, IsHost = {15}",
                PropertyOid,
                NetworkReferenceType,
                NetworkElementRef,
                ApplicableDirection,
                ApplicableSide,
                SeqNo,
                TurnOidLinearElementFrom,
                TurnFromDirection,
                TurnOidLinearElementTo,
                TurnToDirection,
                Measure1,
                Measure2,
                IsPreferred,
                Lanecode,
                LinkRole,
                IsHost);
        }
    }

    public class TnfNetworkReferenceManager : TableManager
    {
        public static string TnfNetworkReferenceTableName = "tnf_network_reference";

        public TnfNetworkReferenceManager(GeoPackageDatabase db) : base(db, TnfNetworkReferenceTableName, GetColumnInfos(),null)
        {
        }

        protected override string[] Constraints()
        {
            return new[]
                {
                    String.Format("CONSTRAINT fk_tnrm_po FOREIGN KEY (property_oid) REFERENCES {0}(oid)",TnfPropertyManager.TnfPropertyTableName),
                };
        }

        protected override string[] Indices()
        {
            return new[]
            {
                String.Format("CREATE INDEX IDX_tnf_network_reference_property_oid ON {0}({1})", TnfNetworkReferenceTableName, "property_oid"),
                String.Format("CREATE INDEX IDX_tnf_network_reference_network_element_ref ON {0}({1})", TnfNetworkReferenceTableName, "network_element_ref")
            };
        }

        protected override string[] Triggers()
        {
            return new[]
                {
                    @"CREATE TRIGGER ""tnf_network_reference_insert1""
BEFORE INSERT ON ""tnf_network_reference""
FOR EACH ROW BEGIN
SELECT RAISE(ABORT, 'insert on table ''tnf_network_reference''
 violates constraint: ''applicable_direction'' must be between -1 and 1.')
WHERE (NEW.applicable_direction NOT BETWEEN -1 AND 1);
END;",
                    @"CREATE TRIGGER ""tnf_network_reference_update1""
BEFORE UPDATE OF ""applicable_direction"" ON ""tnf_network_reference""
FOR EACH ROW BEGIN
SELECT RAISE(ABORT, 'update on table ''tnf_network_reference''
 violates constraint: ''applicable_direction'' must be between -1 and 1.')
WHERE (NEW.applicable_direction NOT BETWEEN -1 AND 1);
END;",
                    @"CREATE TRIGGER ""tnf_network_reference_insert2""
BEFORE INSERT ON ""tnf_network_reference""
FOR EACH ROW BEGIN
SELECT RAISE(ABORT, 'insert on table ''tnf_network_reference''
 violates constraint: ''applicable_side'' must be between -1 and 3.')
WHERE (NEW.applicable_side NOT BETWEEN -1 AND 3);
END;",
                    @"CREATE TRIGGER ""tnf_network_reference_update2""
BEFORE UPDATE OF ""applicable_side"" ON ""tnf_network_reference""
FOR EACH ROW BEGIN
SELECT RAISE(ABORT, 'update on table ''tnf_network_reference''
 violates constraint: ''applicable_side'' must be between -1 and 3.')
WHERE (NEW.applicable_side NOT BETWEEN -1 AND 3);
END;",
                    @"CREATE TRIGGER ""tnf_network_reference_insert3""
BEFORE INSERT ON ""tnf_network_reference""
FOR EACH ROW BEGIN
SELECT RAISE(ABORT, 'insert on table ''tnf_network_reference''
 violates constraint: ''turn_oid_linear_element_from'' must be set when
 ''network_reference_type'' = 64.')
WHERE (NEW.network_reference_type = 64 AND NEW.turn_oid_linear_element_from IS NULL);
END;",
                    @"CREATE TRIGGER ""tnf_network_reference_update3""
BEFORE UPDATE OF ""turn_oid_linear_element_from"" ON ""tnf_network_reference""
FOR EACH ROW BEGIN
SELECT RAISE(ABORT, 'update on table ''tnf_network_reference''
 violates constraint: ''turn_oid_linear_element_from'' must be set when
 ''network_reference_type'' = 64.')
WHERE (NEW.network_reference_type = 64 AND NEW.turn_oid_linear_element_from IS NULL);
END;"
                };
        }

        private static ColumnInfo[] GetColumnInfos()
        {
            return new[]
            {
                new ColumnInfo
                {
                    Name = "property_oid",
                    SqlType = "TEXT NOT NULL",
                    DataType = Type.GetType("System.String")
                },
                new ColumnInfo
                {
                    Name = "network_reference_type",
                    SqlType = "INTEGER NOT NULL",
                    DataType = Type.GetType("System.Int32")
                },
                new ColumnInfo
                {
                    Name = "network_element_ref",
                    SqlType = "TEXT NOT NULL",
                    DataType = Type.GetType("System.String")
                },
                new ColumnInfo
                {
                    Name = "applicable_direction",
                    SqlType = "INTEGER",
                    DataType = Type.GetType("System.Int32")
                },
                new ColumnInfo
                {
                    Name = "applicable_side",
                    SqlType = "INTEGER",
                    DataType = Type.GetType("System.Int32")
                },
                new ColumnInfo
                {
                    Name = "seq_no",
                    SqlType = "INTEGER",
                    DataType = Type.GetType("System.Int32")
                },
                new ColumnInfo
                {
                    Name = "turn_oid_linear_element_from",
                    SqlType = "TEXT",
                    DataType = Type.GetType("System.String")
                },
                new ColumnInfo
                {
                    Name = "turn_from_direction",
                    SqlType = "INTEGER",
                    DataType = Type.GetType("System.Int32")
                },
                new ColumnInfo
                {
                    Name = "turn_oid_linear_element_to",
                    SqlType = "TEXT",
                    DataType = Type.GetType("System.String")
                },
                new ColumnInfo
                {
                    Name = "turn_to_direction",
                    SqlType = "INTEGER",
                    DataType = Type.GetType("System.Int32")
                },
                new ColumnInfo
                {
                    Name = "measure1",
                    SqlType = "DOUBLE",
                    DataType = Type.GetType("System.Double")
                },
                new ColumnInfo
                {
                    Name = "measure2",
                    SqlType = "DOUBLE",
                    DataType = Type.GetType("System.Double")
                },
                new ColumnInfo
                {
                    Name = "is_preferred",
                    SqlType = "INTEGER",
                    DataType = Type.GetType("System.Boolean")
                },
                new ColumnInfo
                {
                    Name = "lanecode",
                    SqlType = "TEXT",
                    DataType = Type.GetType("System.String")
                },
                new ColumnInfo
                {
                    Name = "link_role",
                    SqlType = "INTEGER",
                    DataType = Type.GetType("System.Int32")
                },
                new ColumnInfo
                {
                    Name = "is_host",
                    SqlType = "INTEGER",
                    DataType = Type.GetType("System.Boolean")
                }
            };
        }

        public void Add(TnfNetworkReference tnfNetworkReference)
        {
            Add(new object[]
                {
                    tnfNetworkReference.PropertyOid,
                    tnfNetworkReference.NetworkReferenceType,
                    tnfNetworkReference.NetworkElementRef,
                    tnfNetworkReference.ApplicableDirection,
                    tnfNetworkReference.ApplicableSide,
                    tnfNetworkReference.SeqNo,
                    tnfNetworkReference.TurnOidLinearElementFrom,
                    tnfNetworkReference.TurnFromDirection,
                    tnfNetworkReference.TurnOidLinearElementTo,
                    tnfNetworkReference.TurnToDirection,
                    tnfNetworkReference.Measure1,
                    tnfNetworkReference.Measure2,
                    tnfNetworkReference.IsPreferred,
                    tnfNetworkReference.Lanecode,
                    tnfNetworkReference.LinkRole,
                    tnfNetworkReference.IsHost
                });
        }

        public List<TnfNetworkReference> Get(int maxResults)
        {
            return Get(ReadObject, maxResults);
        }

        public List<TnfNetworkReference> Get(string propertyOid)
        {
            var tnfList = new List<TnfNetworkReference>();

            using (var command = Db.Command)
            {
                command.CommandText =
                    string.Format(
                        "SELECT * FROM {0} WHERE property_oid = '{1}'",
                        TnfNetworkReferenceTableName, propertyOid);

                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        tnfList.Add(ReadObject(reader));
                    }
                }
            }

            return tnfList;
        }

        public List<TnfNetworkReference> GetPage(int offset, int limit)
        {
            return GetPage(ReadObject, offset, limit);
        }

        private static TnfNetworkReference ReadObject(IDataRecord reader)
        {
            var tnfNetworkReference = new TnfNetworkReference();

            tnfNetworkReference.PropertyOid = reader["property_oid"].FromDbString();
            tnfNetworkReference.NetworkReferenceType = reader["network_reference_type"].ToInt32();
            tnfNetworkReference.NetworkElementRef = reader["network_element_ref"].FromDbString();
            tnfNetworkReference.ApplicableDirection = reader["applicable_direction"].ToInt32();
            tnfNetworkReference.ApplicableSide = reader["applicable_side"].ToInt32();
            tnfNetworkReference.SeqNo = reader["seq_no"].ToInt32();
            tnfNetworkReference.TurnOidLinearElementFrom = reader["turn_oid_linear_element_from"].FromDbString();
            tnfNetworkReference.TurnFromDirection = reader["turn_from_direction"].ToInt32();
            tnfNetworkReference.TurnOidLinearElementTo = reader["turn_oid_linear_element_to"].FromDbString();
            tnfNetworkReference.TurnToDirection = reader["turn_to_direction"].ToInt32();
            tnfNetworkReference.Measure1 = reader["measure1"].ToDouble();
            tnfNetworkReference.Measure2 = reader["measure2"].ToDouble();
            tnfNetworkReference.IsPreferred = reader["is_preferred"].ToBoolean();
            tnfNetworkReference.Lanecode = reader["lanecode"].FromDbString();
            tnfNetworkReference.LinkRole = reader["link_role"].ToInt32();
            tnfNetworkReference.IsHost = reader["is_host"].ToBoolean();

            return tnfNetworkReference;
        }
    }
}


text:
using System;
using MbUnit.Framework;

namespace Lix.Commons.Tests
{
    [AssemblyFixture]
    public class AssemblySetUps
    {
        [FixtureSetUp]
        public void SetUp()
        {
            AppDomain.CurrentDomain.SetData("DataDirectory", AppDomain.CurrentDomain.BaseDirectory);
        }

        [SetUp]
        public void TestSetUp()
        {
            LixObjectFactory.Initialize();
        }

        [TearDown]
        public void TestTearDown()
        {
            LixObjectFactory.Reset();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/*
   Concepts and parts of this file have been contributed by Scott (skute).
 */

/**
 * @file    chevents.c
 * @brief   Events code.
 *
 * @addtogroup events
 * @details Event Flags, Event Sources and Event Listeners.
 *
Operation mode

 *          Each thread has a mask of pending events inside its
 *          @p thread_t structure.
 *          Operations defined for events:
 *          - Wait, the invoking thread goes to sleep until a certain
 *            AND/OR combination of events become pending.
 *          - Clear, a mask of events is cleared from the pending
 *            events, the cleared events mask is returned (only the
 *            events that were actually pending and then cleared).
 *          - Signal, an events mask is directly ORed to the mask of the
 *            signaled thread.
 *          - Broadcast, each thread registered on an Event Source is
 *            signaled with the events specified in its Event Listener.
 *          - Dispatch, an events mask is scanned and for each bit set
 *            to one an associated handler function is invoked. Bit masks are
 *            scanned from bit zero upward.
 *          .
 *          An Event Source is a special object that can be "broadcasted" by
 *          a thread or an interrupt service routine. Broadcasting an Event
 *          Source has the effect that all the threads registered on the
 *          Event Source will be signaled with an events mask.

 *          An unlimited number of Event Sources can exists in a system and
 *          each thread can be listening on an unlimited number of
 *          them.
 * @pre     In order to use the Events APIs the @p CH_CFG_USE_EVENTS option must be
 *          enabled in @p chconf.h.
 * @post    Enabling events requires 1-4 (depending on the architecture)
 *          extra bytes in the @p thread_t structure.
 * @{
 */

#include "ch.h"

#if CH_CFG_USE_EVENTS || defined(__DOXYGEN__)

/*===========================================================================*/
/* Module local definitions.                                                 */
/*===========================================================================*/

/*===========================================================================*/
/* Module exported variables.                                                */
/*===========================================================================*/

/*===========================================================================*/
/* Module local types.                                                       */
/*===========================================================================*/

/*===========================================================================*/
/* Module local variables.                                                   */
/*===========================================================================*/

/*===========================================================================*/
/* Module local functions.                                                   */
/*===========================================================================*/

/*===========================================================================*/
/* Module exported functions.                                                */
/*===========================================================================*/

/**
 * @brief   Registers an Event Listener on an Event Source.
 * @details Once a thread has registered as listener on an event source it
 *          will be notified of all events broadcasted there.
 * @note    Multiple Event Listeners can specify the same bits to be ORed to
 *          different threads.
 *
 * @param[in] esp       pointer to the  @p event_source_t structure
 * @param[in] elp       pointer to the @p event_listener_t structure
 * @param[in] events    events to be ORed to the thread when
 *                      the event source is broadcasted
 * @param[in] wflags    mask of flags the listening thread is interested in
 *
 * @api
 */
void chEvtRegisterMaskWithFlags(event_source_t *esp,
                                event_listener_t *elp,
                                eventmask_t events,
                                eventflags_t wflags) {

  chDbgCheck((esp != NULL) && (elp != NULL));

  chSysLock();
  elp->el_next     = esp->es_next;
  esp->es_next     = elp;
  elp->el_listener = currp;
  elp->el_events   = events;
  elp->el_flags    = 0;
  elp->el_wflags   = wflags;
  chSysUnlock();
}

/**
 * @brief   Unregisters an Event Listener from its Event Source.
 * @note    If the event listener is not registered on the specified event
 *          source then the function does nothing.
 * @note    For optimal performance it is better to perform the unregister
 *          operations in inverse order of the register operations (elements
 *          are found on top of the list).
 *
 * @param[in] esp       pointer to the  @p event_source_t structure
 * @param[in] elp       pointer to the @p event_listener_t structure
 *
 * @api
 */
void chEvtUnregister(event_source_t *esp, event_listener_t *elp) {
  event_listener_t *p;

  chDbgCheck((esp != NULL) && (elp != NULL));

  p = (event_listener_t *)esp;
  chSysLock();
  while (p->el_next != (event_listener_t *)esp) {
    if (p->el_next == elp) {
      p->el_next = elp->el_next;
      break;
    }
    p = p->el_next;
  }
  chSysUnlock();
}

/**
 * @brief   Clears the pending events specified in the events mask.
 *
 * @param[in] events    the events to be cleared
 * @return              The pending events that were cleared.
 *
 * @api
 */
eventmask_t chEvtGetAndClearEvents(eventmask_t events) {
  eventmask_t m;

  chSysLock();

  m = currp->p_epending & events;
  currp->p_epending &= ~events;

  chSysUnlock();
  return m;
}

/**
 * @brief   Adds (OR) a set of events to the current thread, this is
 *          @b much faster than using @p chEvtBroadcast() or @p chEvtSignal().
 *
 * @param[in] events    the events to be added
 * @return              The current pending events.
 *
 * @api
 */
eventmask_t chEvtAddEvents(eventmask_t events) {

  chSysLock();

  events = (currp->p_epending |= events);

  chSysUnlock();
  return events;
}

/**
 * @brief   Signals all the Event Listeners registered on the specified Event
 *          Source.
 * @details This function variants ORs the specified event flags to all the
 *          threads registered on the @p event_source_t in addition to the
 *          event flags specified by the threads themselves in the
 *          @p event_listener_t objects.
 * @post    This function does not reschedule so a call to a rescheduling
 *          function must be performed before unlocking the kernel. Note that
 *          interrupt handlers always reschedule on exit so an explicit
 *          reschedule must not be performed in ISRs.
 *
 * @param[in] esp       pointer to the @p event_source_t structure
 * @param[in] flags     the flags set to be added to the listener flags mask
 *
 * @iclass
 */
void chEvtBroadcastFlagsI(event_source_t *esp, eventflags_t flags) {
  event_listener_t *elp;

  chDbgCheckClassI();
  chDbgCheck(esp != NULL);

  elp = esp->es_next;
  while (elp != (event_listener_t *)esp) {
    elp->el_flags |= flags;
    /* When flags == 0 the thread will always be signaled because the
       source does not emit any flag.*/
    if ((flags == 0) || ((elp->el_flags & elp->el_wflags) != 0))
      chEvtSignalI(elp->el_listener, elp->el_events);
    elp = elp->el_next;
  }
}

/**
 * @brief   Returns the flags associated to an @p event_listener_t.
 * @details The flags are returned and the @p event_listener_t flags mask is
 *          cleared.
 *
 * @param[in] elp       pointer to the @p event_listener_t structure
 * @return              The flags added to the listener by the associated
 *                      event source.
 *
 * @api
 */
eventflags_t chEvtGetAndClearFlags(event_listener_t *elp) {
  eventflags_t flags;

  chSysLock();

  flags = elp->el_flags;
  elp->el_flags = 0;

  chSysUnlock();
  return flags;
}

/**
 * @brief   Adds a set of event flags directly to the specified @p thread_t.
 *
 * @param[in] tp        the thread to be signaled
 * @param[in] events    the events set to be ORed
 *
 * @api
 */
void chEvtSignal(thread_t *tp, eventmask_t events) {

  chDbgCheck(tp != NULL);

  chSysLock();
  chEvtSignalI(tp, events);
  chSchRescheduleS();
  chSysUnlock();
}

/**
 * @brief   Adds a set of event flags directly to the specified @p thread_t.
 * @post    This function does not reschedule so a call to a rescheduling
 *          function must be performed before unlocking the kernel. Note that
 *          interrupt handlers always reschedule on exit so an explicit
 *          reschedule must not be performed in ISRs.
 *
 * @param[in] tp        the thread to be signaled
 * @param[in] events    the events set to be ORed
 *
 * @iclass
 */
void chEvtSignalI(thread_t *tp, eventmask_t events) {

  chDbgCheckClassI();
  chDbgCheck(tp != NULL);

  tp->p_epending |= events;
  /* Test on the AND/OR conditions wait states.*/
  if (((tp->p_state == CH_STATE_WTOREVT) &&
       ((tp->p_epending & tp->p_u.ewmask) != 0)) ||
      ((tp->p_state == CH_STATE_WTANDEVT) &&
       ((tp->p_epending & tp->p_u.ewmask) == tp->p_u.ewmask))) {
    tp->p_u.rdymsg = MSG_OK;
    chSchReadyI(tp);
  }
}

/**
 * @brief   Signals all the Event Listeners registered on the specified Event
 *          Source.
 * @details This function variants ORs the specified event flags to all the
 *          threads registered on the @p event_source_t in addition to the
 *          event flags specified by the threads themselves in the
 *          @p event_listener_t objects.
 *
 * @param[in] esp       pointer to the @p event_source_t structure
 * @param[in] flags     the flags set to be added to the listener flags mask
 *
 * @api
 */
void chEvtBroadcastFlags(event_source_t *esp, eventflags_t flags) {

  chSysLock();
  chEvtBroadcastFlagsI(esp, flags);
  chSchRescheduleS();
  chSysUnlock();
}

/**
 * @brief   Returns the flags associated to an @p event_listener_t.
 * @details The flags are returned and the @p event_listener_t flags mask is
 *          cleared.
 *
 * @param[in] elp       pointer to the @p event_listener_t structure
 * @return              The flags added to the listener by the associated
 *                      event source.
 *
 * @iclass
 */
eventflags_t chEvtGetAndClearFlagsI(event_listener_t *elp) {
  eventflags_t flags;

  flags = elp->el_flags;
  elp->el_flags = 0;

  return flags;
}

/**
 * @brief   Invokes the event handlers associated to an event flags mask.
 *
 * @param[in] events    mask of events to be dispatched
 * @param[in] handlers  an array of @p evhandler_t. The array must have size
 *                      equal to the number of bits in eventmask_t.
 *
 * @api
 */
void chEvtDispatch(const evhandler_t *handlers, eventmask_t events) {
  eventid_t eid;

  chDbgCheck(handlers != NULL);

  eid = 0;
  while (events) {
    if (events & EVENT_MASK(eid)) {
      chDbgAssert(handlers[eid] != NULL, "null handler");
      events &= ~EVENT_MASK(eid);
      handlers[eid](eid);
    }
    eid++;
  }
}

#if CH_CFG_OPTIMIZE_SPEED || !CH_CFG_USE_EVENTS_TIMEOUT || defined(__DOXYGEN__)
/**
 * @brief   Waits for exactly one of the specified events.
 * @details The function waits for one event among those specified in
 *          @p events to become pending then the event is cleared and returned.
 * @note    One and only one event is served in the function, the one with the
 *          lowest event id. The function is meant to be invoked into a loop in
 *          order to serve all the pending events.

 *          This means that Event Listeners with a lower event identifier have
 *          an higher priority.
 *
 * @param[in] events    events that the function should wait
 *                      for, @p ALL_EVENTS enables all the events
 * @return              The mask of the lowest event id served and cleared.
 *
 * @api
 */
eventmask_t chEvtWaitOne(eventmask_t events) {
  thread_t *ctp = currp;
  eventmask_t m;

  chSysLock();

  if ((m = (ctp->p_epending & events)) == 0) {
    ctp->p_u.ewmask = events;
    chSchGoSleepS(CH_STATE_WTOREVT);
    m = ctp->p_epending & events;
  }
  m &= -m;
  ctp->p_epending &= ~m;

  chSysUnlock();
  return m;
}

/**
 * @brief   Waits for any of the specified events.
 * @details The function waits for any event among those specified in
 *          @p events to become pending then the events are cleared and
 *          returned.
 *
 * @param[in] events    events that the function should wait
 *                      for, @p ALL_EVENTS enables all the events
 * @return              The mask of the served and cleared events.
 *
 * @api
 */
eventmask_t chEvtWaitAny(eventmask_t events) {
  thread_t *ctp = currp;
  eventmask_t m;

  chSysLock();

  if ((m = (ctp->p_epending & events)) == 0) {
    ctp->p_u.ewmask = events;
    chSchGoSleepS(CH_STATE_WTOREVT);
    m = ctp->p_epending & events;
  }
  ctp->p_epending &= ~m;

  chSysUnlock();
  return m;
}

/**
 * @brief   Waits for all the specified events.
 * @details The function waits for all the events specified in @p events to
 *          become pending then the events are cleared and returned.
 *
 * @param[in] events    events that the function should wait
 *                      for, @p ALL_EVENTS requires all the events
 * @return              The mask of the served and cleared events.
 *
 * @api
 */
eventmask_t chEvtWaitAll(eventmask_t events) {
  thread_t *ctp = currp;

  chSysLock();

  if ((ctp->p_epending & events) != events) {
    ctp->p_u.ewmask = events;
    chSchGoSleepS(CH_STATE_WTANDEVT);
  }
  ctp->p_epending &= ~events;

  chSysUnlock();
  return events;
}
#endif /* CH_CFG_OPTIMIZE_SPEED || !CH_CFG_USE_EVENTS_TIMEOUT */

#if CH_CFG_USE_EVENTS_TIMEOUT || defined(__DOXYGEN__)
/**
 * @brief   Waits for exactly one of the specified events.
 * @details The function waits for one event among those specified in
 *          @p events to become pending then the event is cleared and returned.
 * @note    One and only one event is served in the function, the one with the
 *          lowest event id. The function is meant to be invoked into a loop
 *          in order to serve all the pending events.

 *          This means that Event Listeners with a lower event identifier have
 *          an higher priority.
 *
 * @param[in] events    events that the function should wait
 *                      for, @p ALL_EVENTS enables all the events
 * @param[in] time      the number of ticks before the operation timeouts,
 *                      the following special values are allowed:
 *                      - @a TIME_IMMEDIATE immediate timeout.
 *                      - @a TIME_INFINITE no timeout.
 *                      .
 * @return              The mask of the lowest event id served and cleared.
 * @retval 0            if the operation has timed out.
 *
 * @api
 */
eventmask_t chEvtWaitOneTimeout(eventmask_t events, systime_t time) {
  thread_t *ctp = currp;
  eventmask_t m;

  chSysLock();

  if ((m = (ctp->p_epending & events)) == 0) {
    if (TIME_IMMEDIATE == time) {
      chSysUnlock();
      return (eventmask_t)0;
    }
    ctp->p_u.ewmask = events;
    if (chSchGoSleepTimeoutS(CH_STATE_WTOREVT, time) < MSG_OK) {
      chSysUnlock();
      return (eventmask_t)0;
    }
    m = ctp->p_epending & events;
  }
  m &= -m;
  ctp->p_epending &= ~m;

  chSysUnlock();
  return m;
}

/**
 * @brief   Waits for any of the specified events.
 * @details The function waits for any event among those specified in
 *          @p events to become pending then the events are cleared and
 *          returned.
 *
 * @param[in] events    events that the function should wait
 *                      for, @p ALL_EVENTS enables all the events
 * @param[in] time      the number of ticks before the operation timeouts,
 *                      the following special values are allowed:
 *                      - @a TIME_IMMEDIATE immediate timeout.
 *                      - @a TIME_INFINITE no timeout.
 *                      .
 * @return              The mask of the served and cleared events.
 * @retval 0            if the operation has timed out.
 *
 * @api
 */
eventmask_t chEvtWaitAnyTimeout(eventmask_t events, systime_t time) {
  thread_t *ctp = currp;
  eventmask_t m;

  chSysLock();

  if ((m = (ctp->p_epending & events)) == 0) {
    if (TIME_IMMEDIATE == time) {
      chSysUnlock();
      return (eventmask_t)0;
    }
    ctp->p_u.ewmask = events;
    if (chSchGoSleepTimeoutS(CH_STATE_WTOREVT, time) < MSG_OK) {
      chSysUnlock();
      return (eventmask_t)0;
    }
    m = ctp->p_epending & events;
  }
  ctp->p_epending &= ~m;

  chSysUnlock();
  return m;
}

/**
 * @brief   Waits for all the specified events.
 * @details The function waits for all the events specified in @p events to
 *          become pending then the events are cleared and returned.
 *
 * @param[in] events    events that the function should wait
 *                      for, @p ALL_EVENTS requires all the events
 * @param[in] time      the number of ticks before the operation timeouts,
 *                      the following special values are allowed:
 *                      - @a TIME_IMMEDIATE immediate timeout.
 *                      - @a TIME_INFINITE no timeout.
 *                      .
 * @return              The mask of the served and cleared events.
 * @retval 0            if the operation has timed out.
 *
 * @api
 */
eventmask_t chEvtWaitAllTimeout(eventmask_t events, systime_t time) {
  thread_t *ctp = currp;

  chSysLock();

  if ((ctp->p_epending & events) != events) {
    if (TIME_IMMEDIATE == time) {
      chSysUnlock();
      return (eventmask_t)0;
    }
    ctp->p_u.ewmask = events;
    if (chSchGoSleepTimeoutS(CH_STATE_WTANDEVT, time) < MSG_OK) {
      chSysUnlock();
      return (eventmask_t)0;
    }
  }
  ctp->p_epending &= ~events;

  chSysUnlock();
  return events;
}
#endif /* CH_CFG_USE_EVENTS_TIMEOUT */

#endif /* CH_CFG_USE_EVENTS */

/** @} */


text:
package com.github.cojac.models;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;

import com.github.cojac.InstrumentationStats;
import com.github.cojac.utils.ReflectionUtils;

public final class Reactions {
    //-------------------------------------------------------
    // These fields are used by reflection - Do not inline, do not make final
    private static boolean filtering;

    public static InstrumentationStats stats;

    public static ReactionType theReactionType=ReactionType.PRINT;
    public static String theLogFilename="cojac_log.txt";
    public static String theCallback="dummyCallback";
    //-------------------------------------------------------

    public static final AtomicBoolean react = new AtomicBoolean(true);

    private Reactions() {
        throw new AssertionError();
    }

    //Public to enable to display stats at the end of the application
    public static final ConcurrentMap<String, Long> EVENTS = new ConcurrentHashMap<String, Long>(25);

    //TODO: check whether we can get rid of first/last parameter of react()
    //      quite sure that "yes, we can"!
    public static void react(int reaction, String message, String logFileName) {
        switch (ReactionType.get(reaction)) {
            case PRINT:
                printOverflow(message);
                break;
            case PRINT_SMALLER:
                printOverflowSmaller(message);
                break;
            case LOG:
                logOverflow(message, logFileName);
                break;
            case LOG_SMALLER:
                logOverflowSmaller(message, logFileName);
                break;
            case EXCEPTION:
                throwOverflow(message);
                break;
            case CALLBACK:
                callbackOverflow(message, theCallback);
                break;
        }
    }

    private static boolean passesFilter(String location) {  //BAPST TODO: review use of 'filtering'
        Long old = EVENTS.putIfAbsent(location, 1L);

        if (old != null) {
            EVENTS.put(location, old + 1);
        }

        if (filtering && old == null) {
            return true;
        } else if (filtering) {
            return false;
        }

        if (stats!=null) stats.notifyChange(location);

        return true;
    }

    private static int reasonableIndex(StackTraceElement[] t) {
        int i = 0;
        while(true) {
            if (i==t.length-1) break;
            String s=t[i].toString();
            if (!s.startsWith("com.github.cojac.models") &&
                !t[1].getMethodName().startsWith("cojacCheck")) break;
            i++;
        }
        return i;
    }

    // identifier must match Methods.PRINT definition
    public static void printOverflow(String instructionName) {
        if (!react.get())
            return;
        StackTraceElement[] t = new Throwable().getStackTrace();

        int i = reasonableIndex(t); // 1;

        String location = "COJAC: " + instructionName + ' ' + t[i++].toString();

        if (passesFilter(location)) {
            System.err.println(location);
            i=0;
            do {
                System.err.print('\t');
                System.err.println(t[i++].toString());
            } while (i < t.length);
        }
    }

    // identifier must match Methods.PRINT_SMALLER definition
    public static void printOverflowSmaller(String instructionName) {
        if (!react.get())
            return;
        StackTraceElement[] t = new Throwable().getStackTrace();

        int i = reasonableIndex(t);

        String location = "COJAC: " + instructionName + ' ' + t[i].toString();

        if (passesFilter(location)) {
            System.err.println(location);
        }
    }

    // identifier must match Methods.LOG definition
    public static void logOverflow(String instructionName, String logFileName) {
        if (!react.get())
            return;
        StackTraceElement[] t = new Throwable().getStackTrace();

        int i = reasonableIndex(t);

        String location = "COJAC: " + instructionName + ' ' + t[i++].toString();

        if (passesFilter(location)) {
            BufferedWriter out = null;
            try {
                out = new BufferedWriter(new FileWriter(logFileName, true));

                out.write(location);
                out.newLine();
                i=0;
                do {
                    out.write('\t');
                    out.write(t[i++].toString());
                    out.newLine();
                } while (i < t.length);

                out.newLine();
            } catch (Exception e) {
                System.err.print("COJAC: Error while logging: ");
                System.err.println(e.getMessage());
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        System.err.print("COJAC: Error while logging: ");
                        System.err.println(e.getMessage());
                    }
                }
            }
        }
    }

    // identifier must match Methods.LOG_SMALLER definition
    public static void logOverflowSmaller(String instructionName, String logFileName) {
        if (!react.get())
            return;
        StackTraceElement[] t = new Throwable().getStackTrace();

        int i = reasonableIndex(t);

        String location = "COJAC: " + instructionName + ' ' + t[i].toString();

        if (passesFilter(location)) {
            try {
                BufferedWriter out = new BufferedWriter(new FileWriter(logFileName, true));

                out.write(location);
                out.newLine();
                out.close();
            } catch (Exception e) {
                System.err.print("COJAC: Error while logging: ");
                System.err.println(e.getMessage());
            }
        }
    }

    // identifier must match Methods.THROW definition
    public static void throwOverflow(String instructionName) {
        if (!react.get())
            return;
        StackTraceElement[] t = new Throwable().getStackTrace();

        int i = reasonableIndex(t);

        String location = "COJAC: " + instructionName + ' ' + t[i].toString();

        if (passesFilter(location)) {
            throw new ArithmeticException("COJAC: " + instructionName);
        }
    }

    // There is a very nasty dependence between the Cojac Eclipse Plugin
    // ch.eiafr.ecojac_core.AnnontationMgr.getRelevantElt()
    // and the precise path leading to the invocation of the callback... F. Bapst
    public static void callbackOverflow(String instructionName, String callbackName) {
        ReflectionUtils.invokeCallback(callbackName, instructionName);
    }

    public static void react(String message) {
        react(theReactionType.ordinal(), message, theLogFilename);
    }
}


text:
If you want to listen for interal `react-redux-grid` Actions, you can import them and add them to your own reducers.

```js
import { ActionTypes } from 'react-redux-grid';

switch (action.type) {
    case ActionTypes.SET_LOADING_STATE:
        // handle new loading state for grid
}
```


text:
package uk.gov.hmrc.ct.ct600.v3

import uk.gov.hmrc.ct.box._
import uk.gov.hmrc.ct.ct600.v3.retriever.RepaymentsBoxRetriever
import uk.gov.hmrc.ct.box.ValidatableBox._

case class B925(value: String) extends CtBoxIdentifier("sort code")
with CtString with Input with ValidatableBox[RepaymentsBoxRetriever] {

  override def validate(boxRetriever: RepaymentsBoxRetriever): Set[CtValidation] = {
      validateAllFilledOrEmptyStringsForBankDetails(boxRetriever, "B925") ++
      validateStringByRegex("B925", this, SortCodeValidChars)
  }
}


text:
import _ from 'underscore';
import Plottable from 'plottable';

export const scale = new Plottable.Scales.Time();

function scaleDomainFromRange(range) {
  const max = range.end;
  const min = new Date(range.end.getTime() - range.duration*1000);
  return {min, max};
}

function createSetRangeAction(domain) {
  return {
    type: 'MODIFY_TIME_SCALE',
    start: domain.min,
    end: domain.max,
  };
}

export function syncScaleWithStore(store, options = {}) {
  const getDomain = options.scaleDomainFromRange || scaleDomainFromRange;
  const createAction = options.createSetRangeAction || createSetRangeAction;
  let dirty = false;
  const unsub = store.subscribe(() => {
    if (dirty) {
      return;
    }
    const domain = getDomain(store.getState().range);
    if (domain.min.getTime() === scale.domainMin().getTime() &&
        domain.max.getTime() === scale.domainMax().getTime()) {
      return;
    }
    scale.domain([domain.min, domain.max]);
  });
  const dispatchScaleChange = _.debounce(() => {
    const end = new Date(Math.round(scale.domainMax().getTime()/1000)*1000);
    const start = new Date(Math.round(scale.domainMin().getTime()/1000)*1000);
    dirty = false;
    store.dispatch(createAction({min: start, max: end}));
  }, 500);
  const onUpdate = () => {
    const storeDomain = scaleDomainFromRange(store.getState().range);
    if (storeDomain.min.getTime() === scale.domainMin().getTime() &&
        storeDomain.max.getTime() === scale.domainMax().getTime()) {
      return;
    }
    dirty = true;
    dispatchScaleChange();
  };
  scale.onUpdate(onUpdate);
  return () => {
    unsub();
    scale.offUpdate(onUpdate);
  };
}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
    android:id="@+id/dialog_feedback_app">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Email"
        android:id="@+id/txtemail" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/editText" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Your Feedback"
        android:id="@+id/txtmessage" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textMultiLine"
        android:ems="10"
        android:id="@+id/editText2"
        android:layout_weight="0.41" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send"
        android:id="@+id/btnsendfeedback" />
</LinearLayout>


text:
@implementation IRDatePickerDescriptor

+ (NSString *) componentName
{
    return typeDatePickerKEY;
}
#if TARGET_OS_IPHONE
+ (Class) componentClass
{
    return [IRDatePicker class];
}

+ (Class) builderClass
{
    return [IRDatePickerBuilder class];
}

+ (void) addJSExportProtocol
{
    class_addProtocol([UIDatePicker class], @protocol(UIDatePickerExport));
}
#endif

- (id) initDescriptorWithDictionary:(NSDictionary *)aDictionary
{
    self = [super initDescriptorWithDictionary:aDictionary];
    if (self) {
        NSNumber *number;
        NSString *string;

#if TARGET_OS_IPHONE
        // datePickerMode
        string = aDictionary[NSStringFromSelector(@selector(datePickerMode))];
        self.datePickerMode = [IRBaseDescriptor datePickerModeFromString:string];
#endif

        // date
        string = aDictionary[NSStringFromSelector(@selector(date))];
        self.date = [IRBaseDescriptor dateWithISO8601String:string];

        // minimumDate
        string = aDictionary[NSStringFromSelector(@selector(minimumDate))];
        self.minimumDate = [IRBaseDescriptor dateWithISO8601String:string];

        // maximumDate
        string = aDictionary[NSStringFromSelector(@selector(maximumDate))];
        self.maximumDate = [IRBaseDescriptor dateWithISO8601String:string];

        // countDownDuration
        number = aDictionary[NSStringFromSelector(@selector(countDownDuration))];
        if (number) {
            self.countDownDuration = (NSTimeInterval)[number floatValue];
        } else {
            self.countDownDuration = 0;
        }

        // minuteInterval
        number = aDictionary[NSStringFromSelector(@selector(minuteInterval))];
        if (number) {
            self.minuteInterval = [number integerValue];
        } else {
            self.minuteInterval = 0;
        }
    }
    return self;
}

- (void) extendImagePathsArray:(NSMutableArray *)imagePaths
                 appDescriptor:(IRAppDescriptor *)appDescriptor
{

}

@end


text:
package de.brockhaus.m2m.aspect;

public class SecurityAspect {

}


text:
/**
 * @fileoverview Gulp tasks to check the licenses of Blockly dependencies.
 */

const jsgl = require('js-green-licenses');

function checkLicenses() {
  const checker = new jsgl.LicenseChecker();
  checker.setDefaultHandlers();
  return checker.checkLocalDirectory('.');
};

module.exports = {
  // Manually-invokable targets, with prequisites where required.
  checkLicenses: checkLicenses
};


text:
define(["./_base/kernel", "./has", "require", "./has!host-browser?./domReady", "./_base/lang"], function(dojo, has, require, domReady, lang){
	// module:
	//		dojo/ready
	// note:
	//		This module should be unnecessary in dojo 2.0

	var
		// truthy if DOMContentLoaded or better (e.g., window.onload fired) has been achieved
		isDomReady = 0,

		// a function to call to cause onLoad to be called when all requested modules have been loaded
		requestCompleteSignal,

		// The queue of functions waiting to execute as soon as dojo.ready conditions satisfied
		loadQ = [],

		// prevent recursion in onLoad
		onLoadRecursiveGuard = 0,

		handleDomReady = function(){
			isDomReady = 1;
			dojo._postLoad = dojo.config.afterOnLoad = true;
			if(loadQ.length){
				requestCompleteSignal(onLoad);
			}
		},

		// run the next function queued with dojo.ready
		onLoad = function(){
			if(isDomReady && !onLoadRecursiveGuard && loadQ.length){
				//guard against recursions into this function
				onLoadRecursiveGuard = 1;
				var f = loadQ.shift();
					try{
						f();
					}
						// FIXME: signal the error via require.on
					finally{
						onLoadRecursiveGuard = 0;
					}
				onLoadRecursiveGuard = 0;
				if(loadQ.length){
					requestCompleteSignal(onLoad);
				}
			}
		};

	require.on("idle", onLoad);
	requestCompleteSignal = function(){
		if(require.idle()){
			onLoad();
		} // else do nothing, onLoad will be called with the next idle signal
	};

	var ready = dojo.ready = dojo.addOnLoad = function(priority, context, callback){
		// summary:
		//		Add a function to execute on DOM content loaded and all requested modules have arrived and been evaluated.
		//		In most cases, the `domReady` plug-in should suffice and this method should not be needed.
		// priority: Integer?
		//		The order in which to exec this callback relative to other callbacks, defaults to 1000
		// context: Object?|Function
		//		The context in which to run execute callback, or a callback if not using context
		// callback: Function?
		//		The function to execute.
		//
		// example:
		//	Simple DOM and Modules ready syntax
		//	|	require(["dojo/ready"], function(ready){
		//	|		ready(function(){ alert("Dom ready!"); });
		//	|	});
		//
		// example:
		//	Using a priority
		//	|	require(["dojo/ready"], function(ready){
		//	|		ready(2, function(){ alert("low priority ready!"); })
		//	|	});
		//
		// example:
		//	Using context
		//	|	require(["dojo/ready"], function(ready){
		//	|		ready(foo, function(){
		//	|			// in here, this == foo
		//	|		});
		//	|	});
		//
		// example:
		//	Using dojo/hitch style args:
		//	|	require(["dojo/ready"], function(ready){
		//	|		var foo = { dojoReady: function(){ console.warn(this, "dojo dom and modules ready."); } };
		//	|		ready(foo, "dojoReady");
		//	|	});

		var hitchArgs = lang._toArray(arguments);
		if(typeof priority != "number"){
			callback = context;
			context = priority;
			priority = 1000;
		}else{
			hitchArgs.shift();
		}
		callback = callback ?
			lang.hitch.apply(dojo, hitchArgs) :
			function(){
				context();
			};
		callback.priority = priority;
		for(var i = 0; i < loadQ.length && priority >= loadQ[i].priority; i++){}
		loadQ.splice(i, 0, callback);
		requestCompleteSignal();
	};

	has.add("dojo-config-addOnLoad", 1);
	if(has("dojo-config-addOnLoad")){
		var dca = dojo.config.addOnLoad;
		if(dca){
			ready[(lang.isArray(dca) ? "apply" : "call")](dojo, dca);
		}
	}

	if(has("dojo-sync-loader") && dojo.config.parseOnLoad && !dojo.isAsync){
		ready(99, function(){
			if(!dojo.parser){
				dojo.deprecated("Add explicit require(['dojo/parser']);", "", "2.0");
				require(["dojo/parser"]);
			}
		});
	}

	if(has("host-browser")){
		domReady(handleDomReady);
	}else{
		handleDomReady();
	}

	return ready;
});


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.Avs.Models
{
    /// <summary> Port Mirroring Status. </summary>
    public readonly partial struct PortMirroringProfileStatus : IEquatable<PortMirroringProfileStatus>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="PortMirroringProfileStatus"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public PortMirroringProfileStatus(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string SuccessValue = "SUCCESS";
        private const string FailureValue = "FAILURE";

        /// <summary> SUCCESS. </summary>
        public static PortMirroringProfileStatus Success { get; } = new PortMirroringProfileStatus(SuccessValue);
        /// <summary> FAILURE. </summary>
        public static PortMirroringProfileStatus Failure { get; } = new PortMirroringProfileStatus(FailureValue);
        /// <summary> Determines if two <see cref="PortMirroringProfileStatus"/> values are the same. </summary>
        public static bool operator ==(PortMirroringProfileStatus left, PortMirroringProfileStatus right) => left.Equals(right);
        /// <summary> Determines if two <see cref="PortMirroringProfileStatus"/> values are not the same. </summary>
        public static bool operator !=(PortMirroringProfileStatus left, PortMirroringProfileStatus right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="PortMirroringProfileStatus"/>. </summary>
        public static implicit operator PortMirroringProfileStatus(string value) => new PortMirroringProfileStatus(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is PortMirroringProfileStatus other && Equals(other);
        /// <inheritdoc />
        public bool Equals(PortMirroringProfileStatus other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
from base_map.models.shapes import *
from base_map.models.sites import *
from django.contrib.gis.db import models
from django.contrib.gis.geos import *
from django.contrib.gis.measure import D

class Admin(ShapeMixin, models.Model):
	name = models.CharField(max_length=100, default="")
	region_type = models.CharField(max_length=100, default="")
	region_parent = models.ForeignKey("self", blank=True, null=True, on_delete=models.SET_NULL)
	_shape = generic.GenericRelation(Shape, content_type_field='content_type', object_id_field='object_id')
	objects = GeoInheritanceManager()

	class Meta:
		ordering = ['name']
		app_label = 'web_app'

	def __unicode__(self):
		return self.name

class Landmark(ShapeMixin, models.Model):
	PLACE_CHOICES = (
		('church', 'Church'),
		('mosque', 'Mosque'),
		('school', 'School'),
		('bar', 'Bar'),
		('shop', 'Shop'),
		('hospital', 'Hospital'),
		('hotel', 'Hotel'),
		('restaurant', 'Restaurant'),
		('other', 'Other'),
	)
	name = models.CharField(max_length=500)
	place_type = models.CharField(max_length=50)
	date_added = models.DateTimeField(auto_now_add=True)
	_shape = generic.GenericRelation(Shape, content_type_field='content_type', object_id_field='object_id')
	objects = GeoInheritanceManager()

	class Meta:
		ordering = ['name']
		app_label = 'web_app'

	def __unicode__(self):
		return self.name


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->

<!DOCTYPE cache PUBLIC "-//GemStone Systems, Inc.//GemFire Declarative Cache 7.0//EN" "http://www.gemstone.com/dtd/cache7_0.dtd">
<cache>
  <region-attributes id="ORDER_ATTS" data-policy="partition">
      <partition-attributes redundant-copies="1" local-max-memory="100" total-max-memory="500" total-num-buckets="113" colocated-with="Customer"/>
  </region-attributes>
  <region name="Customer">
    <region-attributes data-policy="partition">
      <partition-attributes redundant-copies="1" local-max-memory="100" total-max-memory="500" total-num-buckets="113" />
    </region-attributes>
  </region>
  <region name="Order" refid="ORDER_ATTS">
  </region>
</cache>


text:
Package.describe("Telescope i18n package");

Package.on_use(function (api) {
	api.use(['ui'], 'client');
  api.add_files(['i18n.js'], ['client', 'server']);
	api.export('i18n');
});


text:
package org.cytoscape.keggscape.internal.task;

import java.io.IOException;
import java.net.URL;

import org.cytoscape.task.read.LoadNetworkURLTaskFactory;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.work.AbstractTask;
import org.cytoscape.work.TaskIterator;
import org.cytoscape.work.TaskMonitor;

public class ExpandPathwayTask extends AbstractTask {

	private final LoadNetworkURLTaskFactory loadNetworkURLTaskFactory;
	private final URL url;
	private final String pathwayName;
	private final String pathwayID;

	private final CyNetworkView parentView;

	private final VisualMappingManager vmm;

	public ExpandPathwayTask(final LoadNetworkURLTaskFactory loadNetworkURLTaskFactory, URL url, String pathwayName,
			String mapID, final CyNetworkView parentView, VisualMappingManager vmm) {
		this.url = url;
		this.pathwayID = mapID;
		this.pathwayName = pathwayName;
		this.loadNetworkURLTaskFactory = loadNetworkURLTaskFactory;
		this.parentView = parentView;
		this.vmm = vmm;
	}

	@Override
	public void run(TaskMonitor taskMonitor) throws Exception {
		taskMonitor.setTitle("Expanding Map Node");
		taskMonitor.setStatusMessage("Downloading Pathway (" + pathwayName + " " + pathwayID + ") from KEGG...");
		taskMonitor.setProgress(-1.0);

		try {
			final VisualStyle originalStyle = vmm.getVisualStyle(parentView);
			TaskIterator it = loadNetworkURLTaskFactory.loadCyNetworks(url);
			it.append(new UpdateStyleTask(parentView, vmm, originalStyle));
			this.insertTasksAfterCurrentTask(it);
			taskMonitor.setProgress(1.0d);
		} catch (Exception e) {
			if(e instanceof IllegalStateException) {
				throw new IOException("Could not expand pathway:\n" + "KEGG database does not have KGML file for pathway "
					+ pathwayID + ".", e);
			} else {
				throw e;
			}
		}
	}

}


text:
@interface DDReceiveGroupMemberChangedAPI : DDUnrequestSuperAPI

@end


text:
const fs    = require('fs');
const utils = require('haraka-utils');

exports.hook_data = (next, connection) => {
    // enable mail body parsing
    connection.transaction.parse_body = true;
    next();
}

exports.hook_data_post = function (next, connection) {
    if (!connection.relaying) {
        return next();
    }

    const recip = (this.config.get('block_me.recipient') || '').toLowerCase();
    const senders = this.config.get('block_me.senders', 'list');

    const self = this;

    // Make sure only 1 recipient
    if (connection.transaction.rcpt_to.length != 1) {
        return next();
    }

    // Check recipient is the right one
    if (connection.transaction.rcpt_to[0].address().toLowerCase() != recip) {
        return next();
    }

    // Check sender is in list
    const sender = connection.transaction.mail_from.address();
    if (!utils.in_array(sender, senders)) {
        return next(DENY, "You are not allowed to block mail, " + sender);
    }

    // Now extract the "From" from the body...
    const to_block = extract_from_line(connection.transaction.body);
    if (!to_block) {
        connection.logerror(this, "No sender found in email");
        return next();
    }

    connection.loginfo(this, "Blocking new sender: " + to_block);

    connection.transaction.notes.block_me = 1;

    // add to mail_from.blocklist
    fs.open('./config/mail_from.blocklist', 'a', (err, fd) => {
        if (err) {
            connection.logerror(self, "Unable to append to mail_from.blocklist: " + err);
            return;
        }
        fs.write(fd, to_block + "\n", null, 'UTF-8', (err2, written) => {
            fs.close(fd);
        });
    });

    next();
}

exports.hook_queue = (next, connection) => {
    if (connection.transaction.notes.block_me) {
        // pretend we queued this mail
        return next(OK);
    }

    next();
}

// Example: From: 	Site Tucano Gold <contato@tucanogold.com.br>
function extract_from_line (body) {
    const matches = body.bodytext.match(/\bFrom:[^<\n]*<([^>\n]*)>/);
    if (matches) {
        return matches[1];
    }

    for (let i=0,l=body.children.length; i < l; i++) {
        const from = extract_from_line(body.children[i]);
        if (from) {
            return from;
        }
    }

    return null;
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:orientation="vertical" tools:context=".MainActivity"
    android:background="@drawable/background">

    <TextView android:text="@string/registering_message" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/informationTextView"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:gravity="center"/>

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/registrationProgressBar"
        android:layout_gravity="center"/>

</LinearLayout>


text:
ACCEPTED

#### According to
World Register of Marine Species

#### Published in
Arch. Microbiol. 177: 368

#### Original name
null

### Remarks
null


text:
UL.mainMenu a
{
/*background: url('../../../../Images/Layout/BottomLeftCorner.gif') left bottom no-repeat;*/
text-decoration: none;
}

DIV.mainSubmenu UL.mainMenu
{
margin-left: 0;
}

DIV.mainSubmenu UL.mainMenu LI a span
{
padding: 4 10 4 10;
}

DIV.mainSubmenu UL.mainMenu a span
{
font-weight: normal;
font-size: 9pt;
padding-right: 0px;
}

DIV.mainSubmenu UL.mainMenu a, DIV.mainSubmenu UL.mainMenu a span
{
display: block;
float: none;
width: 100%;
}

UL.mainMenu a span
{
cursor:hand;
padding-right: 10px;
height:0;
font-weight: bolder;
font-family:Arial Black, Gadget, sans-serif;
text-transform:uppercase;
}

UL.mainMenu a, UL.mainMenu a span
{
display: block;
float: left;
width: 80px;
}

/* Hide from IE5-Mac */
/*UL.mainMenu a, UL.mainMenu a span
{
float: none;
}*/
/* End hide */

UL.mainMenu li
{
font-size:10pt;
float: left;
margin-left: 0;
}

/*fills*/

UL.mainMenu a span
{
border:solid 1pt transparent;
}

UL.mainMenu a:hover span
{
border:solid 1pt blue;
background-color: #CFD6E8;
color:#003366;
/*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='../../../../Images/Layout/gradient_topBottom_edges.png');*/
}

UL.mainMenu a
{
color: white;
background-color: transparent;
border:solid 1pt transparent;
}

UL.mainMenu a:hover
{
color: white;
background-position:center;
/*background-color: silver;*/
/*filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale, src='../../../../Images/Layout/gradient_topBottom_edges.png');*/
}

UL.mainMenu .tab.selected a
{
color: white;
background-color: #003366;
font-weight: bolder;
}


text:
package cz.brmlab.yodaqa.analysis.ansscore;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.FeatureStructure;
import org.apache.uima.fit.util.FSCollectionFactory;
import org.apache.uima.jcas.JCas;
import org.apache.uima.jcas.cas.FSArray;

import cz.brmlab.yodaqa.model.CandidateAnswer.*;
import cz.brmlab.yodaqa.model.AnswerHitlist.Answer;
import cz.brmlab.yodaqa.model.SearchResult.CandidateAnswer;

/**
 * A CandidateAnswer feature vector.  I.e. a single, fixed array where each
 * index represents one feature and the indices are stable between answers.
 *
 * TODO: We should instead build a feature _map_.  That'd simplify a lot
 * of cruft.
 *
 * Originally, this class has been intended mainly as an interface between
 * answer features and machine learned models. However, we also use it
 * whenever we need to manipulate a set of features at once - when initializing
 * a feature set and when merging feature sets of different answers. */

public class AnswerFV {
	/* XXX: This actually still prevents auto-generated features. */
	public static String labels[] = {
		"occurences", "resultRR", "resultLogScore", "passageLogScore",
			"propertyScore", "propertyGloVeScore",
		"originPsg", "originPsgFirst",
		"originPsgByClueToken", "originPsgByCluePhrase", "originPsgByClueSV",
			"originPsgByClueNE", "originPsgByClueLAT",
			"originPsgByClueSubject", "originPsgByClueSubjectNE",
			"originPsgByClueSubjectToken", "originPsgByClueSubjectPhrase",
			"originPsgByClueNgram", "originPsgByClueConcept", "originPsgByAbstractClue",
			"originPsgByConceptSourceRR", "originPsgByConceptLabelRR", "originPsgByConceptScore",
		"originPsgNP", "originPsgNE", "originPsgNPByLATSubj",
			"originPsgBIO",
		"originPsgSurprise",
		"originDocTitle",
		"originBingSnippet",
		"originDBpOntology", "originDBpONoClue",
		"originDBpOClueToken", "originDBpOCluePhrase", "originDBpOClueSV",
			"originDBpOClueNE", "originDBpOClueLAT",
			"originDBpOClueSubject", "originDBpOClueSubjectNE",
			"originDBpOClueSubjectToken", "originDBpOClueSubjectPhrase",
			"originDBpOClueNgram", "originDBpOClueConcept",
			"originDBpOConceptSourceRR", "originDBpOConceptLabelRR", "originDBpOConceptScore",
		"originDBpProperty", "originDBpPNoClue",
		"originDBpPClueToken", "originDBpPCluePhrase", "originDBpPClueSV",
			"originDBpPClueNE", "originDBpPClueLAT",
			"originDBpPClueSubject", "originDBpPClueSubjectNE",
			"originDBpPClueSubjectToken", "originDBpPClueSubjectPhrase",
			"originDBpPClueNgram", "originDBpPClueConcept",
			"originDBpPConceptSourceRR", "originDBpPConceptLabelRR", "originDBpPConceptScore",
		"originFreebaseOntology",
			"originFreebaseSpecific", "originFreebaseBranched",
			"originFreebaseWitnessMid", "originFreebaseWitnessLabel",
			"originFBONoClue",
		"originFBOClueToken", "originFBOCluePhrase", "originFBOClueSV",
			"originFBOClueNE", "originFBOClueLAT",
			"originFBOClueSubject", "originFBOClueSubjectNE",
			"originFBOClueSubjectToken", "originFBOClueSubjectPhrase",
			"originFBOClueNgram", "originFBOClueConcept",
			"originFBOConceptSourceRR", "originFBOConceptLabelRR", "originFBOConceptScore",
		"originConcept",
			"originConceptBySubject", "originConceptByLAT", "originConceptByNE",
			"originConceptSourceRR", "originConceptLabelRR", "originConceptScore",
		"originMultiple",
		"psgDistClueToken", "psgDistCluePhrase", "psgDistClueSV",
			"psgDistClueNE", "psgDistClueLAT",
			"psgDistClueSubject", "psgDistClueSubjectNE",
			"psgDistClueSubjectToken", "psgDistClueSubjectPhrase",
			"psgDistClueNgram", "psgDistClueConcept",
			"psgDistConceptSourceRR", "psgDistConceptLabelRR", "psgDistConceptScore",
		"bioScore",
		"noTyCor", "LATANone",
                "spWordNet", "LATQNoWordNet", "LATANoWordNet",
		"tyCorPassageSp", "tyCorPassageDist", "tyCorPassageInside",
		"simpleScore",
		"answerFocusNone", "answerFocusWhole",
		"LATNE", "LATDBpType", "LATDBpWNType", "LATQuantity", "LATQuantityCD",
			"LATWnInstance", "LATDBpOntology", "LATDBpProperty", "LATFBOntology",
		"tyCorSpQHit", "tyCorSpAHit", "tyCorSpNoHit", "tyCorSpQAHit", "tyCorSpMultiHit",
		"tyCorANE", "tyCorADBp", "tyCorADBpWN", "tyCorAQuantity", "tyCorAQuantityCD",
			"tyCorAWnInstance", "tyCorADBpOntology", "tyCorADBpProperty", "tyCorAFBOntology",
		"clOCMatchScore", "clOCPrefixedScore", "clOCPrefixingScore", "clOCSuffixedScore",
			"clOCSuffixingScore", "clOCSubstredScore", "clOCSubstringScore",
			"clOCMetaMatchScore",
		"clOMatchScore", "clOPrefixedScore", "clOPrefixingScore", "clOSuffixedScore",
			"clOSuffixingScore", "clOSubstredScore", "clOSubstringScore",
			"clOMetaMatchScore",
		"evdPrefixedScore", "evdPrefixingScore", "evdSuffixedScore", "evdSuffixingScore",
			"evdSubstredScore", "evdSubstringScore",
		"topAnswer", "solrHitsEv", "solrAHitsEv", "solrHitsANormEv", "solrMaxScoreEv",
			"solrHitsMaxScoreEv",
		"phase0Score", "phase1Score",
		"questionClassABBR", "questionClassDESC", "questionClassENTY",
	    "questionClassHUM", "questionClassLOC", "questionClassNUM"
	};

	protected double values[]; // the feature value
	protected boolean isSet[]; // whether the feature is set
	protected AnswerStats astats;

	public AnswerFV() {
		values = new double[labels.length];
		isSet = new boolean[labels.length];
	}

	public AnswerFV(FSArray fsarray) {
		this();

		if (fsarray == null)
			return;
		for (FeatureStructure fs : fsarray.toArray()) {
			AnswerFeature af = (AnswerFeature) fs;
			if (setFeature(af.getName(), af.getValue())) {
				int index = featureIndex(af.getName());
				throw new RuntimeException("Duplicate answer feature " + labels[index] + "=" + values[index] + " in " + fsarray);
			}
		}
	}

	public AnswerFV(AnswerInfo ai) {
		this(ai.getFeatures());
	}

	public AnswerFV(CandidateAnswer ca) {
		this(ca.getFeatures());
	}

	public AnswerFV(Answer a) {
		this(a.getFeatures());
	}

	public AnswerFV(Answer a, AnswerStats astats_) {
		this(a);
		astats = astats_;
	}

	/** Return a list of values. Note that for model input, you should
	 * rather use getFV(). */
	public double[] getValues() {
		return values;
	}

	public boolean[] getIsSet() {
		return isSet;
	}

	public static String[] getFeatures() {
		// XXX: Rename to getLabels()
		return labels;
	}

	public static int featureIndex(String label) throws ArrayIndexOutOfBoundsException {
		int idx = ArrayUtils.indexOf(labels, label);
		if (idx == -1) {
			throw new ArrayIndexOutOfBoundsException(label);
		}
		return idx;
	}

	/** Produce a feature vector. For each value, this vector includes:
	 *
	 * - the feature value, as set
	 * - the feature value, normalized (centered to mean at zero, rescaled
	 *   to unit SD)
	 * - indicator element that is 0 if the feature is set, 1 otherwise
	 *   (so that omission of a feature can be taken as a signal by itself)
	 *
	 * More may appear in the future. */
	public double[] getFV() {
		double[] fv = new double[labels.length * 3];
		for (int i = 0; i < labels.length; i++) {
			fv[i*3] = values[i];
			if (astats != null && astats.sd[i] != 0) {
				fv[i*3 + 1] = (values[i] - astats.mean[i]) / astats.sd[i];
			} else {
				fv[i*3 + 1] = 0.0;
			}
			fv[i*3 + 2] = isSet[i] ? 0.0 : 1.0;
		}
		return fv;
	}

	/** Produce a label vector corresponding to the feature vector,
	 * as returned by getFV(). */
	public static String[] getFVLabels() {
		String[] FVlabels = new String[labels.length * 3];
		for (int i = 0; i < labels.length; i++) {
			FVlabels[i*3] = "@" + labels[i];
			FVlabels[i*3 + 1] = "%" + labels[i];
			FVlabels[i*3 + 2] = "!" + labels[i];
		}
		return FVlabels;
	}

	/** Set a given feature to a value.  Return whether the feature
	 * has already been set before. */
	public boolean setFeature(String f, double value) {
		int index = featureIndex(f);
		assert(index >= 0);

		boolean hasBeenSet = isSet[index];

		values[index] = value;
		isSet[index] = true;

		return hasBeenSet;
	}

	public double getFeatureValue(String f) {
		return values[featureIndex(f)];
	}
	public boolean isFeatureSet(String f) {
		return isSet[featureIndex(f)];
	}

	/** Merge the a2fv AnswerFV to this AnswerFV.  Individual features
	 * may have various policy of how this is done - averaging, max,
	 * sum, ...  By default, features are maxed, though. */
	public void merge(AnswerFV a2fv) {
		double[] a2values = a2fv.getValues();
		boolean[] a2isSet = a2fv.getIsSet();

		for (int i = 0; i < labels.length; i++) {
			if (!a2isSet[i]) {
				if (isSet[i] && values[i] < 0) {
					/* Unset value wins over
					 * negative value. */
					isSet[i] = false;
					values[i] = 0;
				}
				continue;
			}
			if (!isSet[i]) {
				if (a2values[i] >= 0) {
					/* Set the value only
					 * if non-negative. */
					isSet[i] = true;
					values[i] = a2values[i];
				}
				continue;
			}
			/* Actual feature merge.  XXX: Fancier mechanism
			 * than a brute-force if. */
			if (labels[i].equals(AF.Occurences)) {
				values[i] += a2values[i];
			} else {
				if (a2values[i] > values[i])
					values[i] = a2values[i];
			}
		}
	}

	/** Produce a FSArray of UIMA objects representing the set FV
	 * features. */
	public FSArray toFSArray(JCas jcas)
			throws AnalysisEngineProcessException {
		List<AnswerFeature> aflist = new LinkedList<AnswerFeature>();

		for (int i = 0; i < labels.length; i++) {
			if (!isSet[i])
				continue;

			AnswerFeature f = new AnswerFeature(jcas);
			f.setName(labels[i]);
			f.setValue(values[i]);
			f.addToIndexes();
			aflist.add(f);
		}

		return FSCollectionFactory.createFSArray(jcas, aflist);
	}
}


text:
Getting myself familiar familiar with all design patterns by implementing them.

Design patterns are taken from: https://sourcemaking.com/design_patterns


text:
<?php

namespace Yeb\Libraries;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Redirect;
use Request;
use Response;
use Session;

class ExceptionsHandler
{

	protected $exception;
	protected $httpCode;
	protected $title;
	protected $message;
	protected $type = 'danger';
	protected $redirect = '/';

	public function __construct(\Exception $exception, $httpCode)
	{
		if (\App::runningInConsole()) { // no cli
			return;
		}

		$this->exception = $exception;
		$this->httpCode  = $httpCode;
		$this->title     = __('Un problème est survenu');
	}

	public function handle()
	{
		$e =& $this->exception;

		if ($e instanceof ModelNotFoundException) {
			$this->title  = __('Le groupe ou la ressource demandé n\'existe plus.');

		} else if ($e instanceof \ValidationException) {
			$this->forceFriendly = true;
			$this->title = __('Oops! Il y a quelques erreurs :');

			foreach ($e->getMessages() as $error) {
				$this->message.= '
'.$error.'
';
			}
			$this->message = '
'.$this->message.'
';

			$this->redirect = 'back';
		}

		return $this->response();
	}

// protected methods
// ------------------------------------------------
	protected function response()
	{
		if ( !DEBUG or isset($this->forceFriendly) ) {
			return $this->redirect();
		}

		return null;
	}

	protected function missing()
	{
		$controller = new \Yeb\Laravel\PageController(true);

		return \Response::make($controller->callAction('render404', [404]));
	}

	protected function redirect()
	{
		$path =& $this->redirect;

		if ($path === 'back') {
			return Redirect::back();
		}

		// prevent infinite loop redirection
		return Redirect::to(Request::is($path) ? '/' : $path);
	}

}


text:
自定义EditText,提供插入图片的接口,给大家提供一个参考,大家可以自己完善里面的功能,加上捕获EditText键盘事件就可以实现一个完整的支持表情图片的EditText(类似QQ聊天)
提供一个小思路:删除图片,其实就是重置EditText文本. 添加图片用SpannableString ImageSpan
关键代码:
```
SpannableString ss = new SpannableString(getText().toString()+"[smile]");
Drawable d = getResources().getDrawable(id);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, getText().length(),getText().length()+"[smile]".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
setText(ss);
```


text:
ActiveRecord::Schema.define(version: 2017_03_17_143452) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "hstore"
  enable_extension "pg_trgm"
  enable_extension "plpgsql"

  create_table "artists", id: :serial, force: :cascade do |t|
    t.string "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "slug"
    t.hstore "links"
    t.text "description"
    t.string "image_file_id"
  end

  create_table "episodes", id: :serial, force: :cascade do |t|
    t.string "name"
    t.string "eventbrite_url"
    t.string "mixcloud_url"
    t.string "facebook_url"
    t.datetime "starts_at"
    t.datetime "ends_at"
    t.datetime "published_at"
    t.text "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "slug"
    t.string "eventbrite_event_id"
    t.string "audio_file_id"
    t.string "flyer_file_id"
    t.string "youtube_id"
    t.datetime "audio_transcoded_at"
    t.string "short_link_url"
    t.string "video_url"
    t.boolean "featured"
  end

  create_table "friendly_id_slugs", id: :serial, force: :cascade do |t|
    t.string "slug", null: false
    t.integer "sluggable_id", null: false
    t.string "sluggable_type", limit: 50
    t.string "scope"
    t.datetime "created_at"
    t.index ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true
    t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type"
    t.index ["sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_id"
    t.index ["sluggable_type"], name: "index_friendly_id_slugs_on_sluggable_type"
  end

  create_table "performances", id: :serial, force: :cascade do |t|
    t.integer "artist_id"
    t.integer "episode_id"
    t.datetime "starts_at"
    t.datetime "ends_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "audio_file_id"
    t.datetime "audio_transcoded_at"
    t.string "video_url"
    t.string "image_id"
    t.boolean "featured"
    t.index ["artist_id"], name: "index_performances_on_artist_id"
    t.index ["episode_id"], name: "index_performances_on_episode_id"
  end

  create_table "subscribers", id: :serial, force: :cascade do |t|
    t.string "name"
    t.string "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "users", id: :serial, force: :cascade do |t|
    t.string "name", default: "", null: false
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer "sign_in_count", default: 0, null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet "current_sign_in_ip"
    t.inet "last_sign_in_ip"
    t.string "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string "unconfirmed_email"
    t.integer "failed_attempts", default: 0, null: false
    t.string "unlock_token"
    t.datetime "locked_at"
    t.boolean "is_admin", default: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "slug"
    t.index ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
    t.index ["unlock_token"], name: "index_users_on_unlock_token", unique: true
  end

  add_foreign_key "performances", "artists"
  add_foreign_key "performances", "episodes"
end


text:
class AliFemtoEvent;
class AliFemtoTrack;
class AliFemtoV0;
class AliFemtoKink;
class AliFemtoPair; // Gael 12/04/02
class TH1D;
class TH2D;
class TList;
#include "AliFemtoString.h"
#include "AliFemtoParticleCollection.h"
#include "AliFemtoCutMonitor.h"

class AliFemtoCutMonitorParticlePtPDG : public AliFemtoCutMonitor{

public:
  AliFemtoCutMonitorParticlePtPDG();
  AliFemtoCutMonitorParticlePtPDG(const char *aName, float aMass);
  AliFemtoCutMonitorParticlePtPDG(const AliFemtoCutMonitorParticlePtPDG &aCut);
  virtual ~AliFemtoCutMonitorParticlePtPDG();

  AliFemtoCutMonitorParticlePtPDG& operator=(const AliFemtoCutMonitorParticlePtPDG& aCut);

  virtual AliFemtoString Report();
  virtual void Fill(const AliFemtoEvent* aEvent) {AliFemtoCutMonitor::Fill(aEvent);}
  virtual void Fill(const AliFemtoTrack* aTrack);
  virtual void Fill(const AliFemtoV0* aV0) {AliFemtoCutMonitor::Fill(aV0);}
  virtual void Fill(const AliFemtoKink* aKink) {AliFemtoCutMonitor::Fill(aKink);}
  virtual void Fill(const AliFemtoPair* aPair) {AliFemtoCutMonitor::Fill(aPair);}
  virtual void Fill(const AliFemtoParticleCollection* aCollection) {AliFemtoCutMonitor::Fill(aCollection);}
  virtual void Fill(const AliFemtoEvent* aEvent,const AliFemtoParticleCollection* aCollection)
  {AliFemtoCutMonitor::Fill(aEvent, aCollection);}
  virtual void Fill(const AliFemtoParticleCollection* aCollection1,const AliFemtoParticleCollection* aCollection2) {AliFemtoCutMonitor::Fill(aCollection1, aCollection2);}

  void Write();

  virtual TList *GetOutputList();

private:
  TH2D *fPtPDG;    // Rapidity vs. Pt monitor
  TH2D *fPtOrigin;    // Particle origin vs Pt
  TH2D *ftpcHist;  // TPC histogram
  TH1D *fPtGoodPi; // Good pions
  TH1D *fPrimaryPtGoodPi; // Good primary pions
  TH1D *fPtFakePi; // Fake pions
  TH1D *fPtGoodK;  // Good kaons
  TH1D *fPrimaryPtGoodK;  // Good primary kaons
  TH1D *fPtFakeK;  // Fake kaons
  TH1D *fPtGoodP;  // Good protons
  TH1D *fPrimaryPtGoodP;  // Good primary protons
  TH1D *fPtFakeP;  // Fake protons
  TH1D *fPtRPi;    // Pions pt
  TH1D *fPtRK;     // Kaons pt
  TH1D *fPtRP;     // Protons pt

  TH1D *fPtContP;  // Contamination protons
  TH1D *fPtContPi; // Contamination pions
  TH1D *fPtContMup;// Contamination muons
  TH1D *fPtContElp;// Contamination electrons

  //TH2D *fYPhi;   // Rapidity cs. Phi monitor
  //TH2D *fPtPhi;  // Pt vs. Phi monitor
  //TH2D *fEtaPhi; // Pseudorapidity vs. Phi monitor
  //TH2D *fEtaPt;  // Pseudorapidity vs. Pt monitor
  float fMass;   // Mass hypothesis
};

#endif


text:
# laravel-elixir-handlebars
Laravel Elixir Handlebars extension.

It provides a simple way to pre-compile your Handlebars templates without the need to modify default Blade's delimiters `{{ }}`. It performs faster than using client compilation and plays nice with existing Laravel views.

### Install
`$ npm install laravel-elixir-handlebars --save-dev`

### Usage
```javascript
var elixir = require('laravel-elixir');

require('laravel-elixir-handlebars');

elixir(function (mix) {

    // Handlebar templates
    mix.templates([
        // Will search in 'resources/views/templates'
        'templates/**/*.hbs'

      //and compile where you want:
    ],'resources/assets/js/templates.js');
});
```

### Including it in your project
```javascript
//Just join your scripts as usual
mix.scripts([
    'jquery/dist/jquery.js',
    'bootstrap/dist/js/bootstrap.js',
    // ...
    // ... other scripts ...
    // ...
    'handlebars/handlebars.runtime.js' // <- don't forget to add me
    'templates.js', // <- put me right before your main script
    'my_script.js' // <- Now I can use templates! Yay!
], 'public/js/scripts.js');

//And version it if you like
mix.version(['js/scripts.js']);
```

Now you can just use the templates in your js files normally:

`Handlebars.templates.my_template(foo, bar);`


text:
package com.chicm.cmraft.core;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.chicm.cmraft.common.Configuration;
import com.chicm.cmraft.common.ServerInfo;
import com.chicm.cmraft.log.RaftLog;
import com.chicm.cmraft.protobuf.generated.RaftProtos.AppendEntriesResponse;
import com.chicm.cmraft.protobuf.generated.RaftProtos.CollectVoteResponse;
import com.chicm.cmraft.protobuf.generated.RaftProtos.RaftLogEntry;
import com.google.common.base.Preconditions;
import com.google.protobuf.ServiceException;

public class NodeConnectionManager {
  static final Log LOG = LogFactory.getLog(NodeConnectionManager.class);
  private Configuration conf;
  private Map<ServerInfo, NodeConnection> connections;
  private RaftNode raftNode;

  public NodeConnectionManager(Configuration conf, RaftNode node) {
    this.conf = conf;
    this.raftNode = node;
    initServerList();
  }

  private void initServerList() {
    connections = new ConcurrentHashMap<>();

    for (ServerInfo remote : getRaftNode().getRemoteServers()) {
      NodeConnection client = new DefaultNodeConnection(conf, remote);
      connections.put(remote, client);
    }
  }

  public RaftNode getRaftNode() {
    return raftNode;
  }

  public Set<ServerInfo> getRemoteServers() {
    return connections.keySet();
  }

  public void beatHeart(long term, ServerInfo leaderId, long leaderCommit,
      long prevLogIndex, long prevLogTerm) {
    appendEntries(term, leaderId, leaderCommit, prevLogIndex, prevLogTerm,
      new ArrayList<RaftLogEntry>(), 0);

  }

  public void appendEntries(RaftLog logMgr, long lastApplied) {
    int nServers = getRemoteServers().size();
    if(nServers <= 0) {
      return;
    }

    ExecutorService executor = Executors.newFixedThreadPool(nServers,
      new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
          Thread t = new Thread(r);
          t.setName(getRaftNode().getName() + "-AsyncRpcCaller" + (byte)System.currentTimeMillis());
          return t;
        }
    });

    for(ServerInfo server: getRemoteServers()) {
      NodeConnection conn = connections.get(server);
      long startIndex = logMgr.getFollowerMatchIndex(server) + 1;

      LOG.info(getRaftNode().getName() + ": SENDING appendEntries Request TO: " + server);
      Thread t = new Thread(new AsynchronousAppendEntriesWorker(getRaftNode(), conn, getRaftNode().getRaftLog(),
        getRaftNode().getServerInfo(), getRaftNode().getCurrentTerm(), logMgr.getCommitIndex(), startIndex-1,
        logMgr.getLogTerm(startIndex-1), logMgr.getLogEntries(startIndex, lastApplied), lastApplied));
      t.setDaemon(true);
      executor.execute(t);
    }
  }

  private void appendEntries(long term, ServerInfo leaderId, long leaderCommit,
      long prevLogIndex, long prevLogTerm, List<RaftLogEntry> entries, long maxIndex) {
    Preconditions.checkNotNull(entries);

    int nServers = getRemoteServers().size();
    if(nServers <= 0) {
      return;
    }

    ExecutorService executor = Executors.newFixedThreadPool(nServers,
      new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
          Thread t = new Thread(r);
          t.setName(getRaftNode().getName() + "-AsyncRpcCaller" + (byte)System.currentTimeMillis());
          return t;
        }
    });

    for(ServerInfo server: getRemoteServers()) {
      NodeConnection connection = connections.get(server);
      LOG.debug(getRaftNode().getName() + ": SENDING appendEntries Request TO: " + server);
      Thread t = new Thread(new AsynchronousAppendEntriesWorker(getRaftNode(), connection, getRaftNode().getRaftLog(), getRaftNode().getServerInfo(), term,
        leaderCommit, prevLogIndex, prevLogTerm, entries, maxIndex));
      t.setDaemon(true);
      executor.execute(t);
    }
  }

  public void collectVote(long term, long lastLogIndex, long lastLogTerm) {
    int nServers = getRemoteServers().size();
    if(nServers <= 0) {
      return;
    }
    ExecutorService executor = Executors.newFixedThreadPool(nServers,
      new ThreadFactory() {
        @Override
        public Thread newThread(Runnable r) {
          Thread t = new Thread(r);
          t.setName(getRaftNode().getName() + "-AsyncRpcCaller" + (byte)System.currentTimeMillis());
          return t;
        }
    });

    for(ServerInfo server: getRemoteServers()) {
      NodeConnection conn = connections.get(server);
      LOG.debug(getRaftNode().getName() + ": SENDING COLLECTVOTE Request TO: " + server);
      Thread t = new Thread(new AsynchronousVoteWorker(getRaftNode(), conn, getRaftNode().getServerInfo(), term,
        lastLogIndex, lastLogTerm));
      t.setDaemon(true);
      executor.execute(t);
    }
  }

  class AsynchronousVoteWorker implements Runnable {
    private ServerInfo candidate;
    private long term;
    private long lastLogIndex;
    private long lastLogTerm;
    private RaftNode node;
    private NodeConnection connection;

    public AsynchronousVoteWorker(RaftNode node, NodeConnection connnection, ServerInfo thisServer, long term,
        long lastLogIndex, long lastLogTerm) {
      this.connection = connnection;
      this.node = node;
      this.candidate = thisServer;
      this.term = term;
      this.lastLogIndex = lastLogIndex;
      this.lastLogTerm = lastLogTerm;
    }

    @Override
    public void run () {
      CollectVoteResponse response = null;
      try {
        response = connection.collectVote(candidate, term, lastLogIndex, lastLogTerm);
        if(response != null && response.getGranted()) {
          node.voteReceived(ServerInfo.copyFrom(response.getFromHost()), response.getTerm());
        } else if( response == null) {
          LOG.error("RPC failed, response == null");
        } else if(response.getGranted() == false) {
          LOG.info(node.getName() + "VOTE REJECTED BY " + response.getFromHost().getHostName()
            + ":" + response.getFromHost().getPort());
        }
      } catch(Exception e) {
        LOG.error("RPC: collectVote failed: from " + getRaftNode().getName() +
          ", to: " + connection.getRemoteServer() + ": " + e.getMessage());
      }
    }
  }

  class AsynchronousAppendEntriesWorker implements Runnable {
    private ServerInfo leader;
    private long term;
    private long leaderCommit;
    private long prevLogIndex;
    private long prevLogTerm;
    private List<RaftLogEntry> entries;
    private long maxIndex;
    private RaftNode node;
    private NodeConnection connection;
    private RaftLog logManager;

    public AsynchronousAppendEntriesWorker(RaftNode node, NodeConnection connection, RaftLog logMgr, ServerInfo thisServer, long term,
        long leaderCommit, long prevLogIndex, long prevLogTerm, List<RaftLogEntry> entries, Long maxIndex) {
      this.connection = connection;
      this.node = node;
      this.logManager = logMgr;
      this.leader = thisServer;
      this.term = term;
      this.leaderCommit = leaderCommit;
      this.prevLogIndex = prevLogIndex;
      this.prevLogTerm = prevLogTerm;
      this.entries = entries;
      this.maxIndex = maxIndex;
    }

    @Override
    public void run () {
      try {
        AppendEntriesResponse response = connection.appendEntries(term, leader, leaderCommit, prevLogIndex, prevLogTerm, entries);

        if(response != null && entries != null && logManager != null) {
          logManager.onAppendEntriesResponse(connection.getRemoteServer(), response.getTerm(),
            response.getSuccess(), maxIndex);
        }
      } catch(Exception e) {
        LOG.error("RPC: collectVote failed: from " + getRaftNode().getName() +
          ", to: " + connection.getRemoteServer(), e);
      }
    }
  }
}


text:
export class SampleModule {
  constructor(/* put injections here */) {
  }

  public getHelloText(): string {
    return 'Hello from the controller!';
  }
}


text:
module Signaling
  class ResourceInvalid < StandardError
    attr_reader :record

    def initialize(record)
      @record = record
      super()
    end
  end
end


text:
greenspun
=========

> Any sufficiently complicated C or Fortran program contains an ad hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.
- Philip Greenspun

This package contains a collection of useful lisp functionality and data structures for inclusion in complex Go programs which might need to comply with Greenspun's 10th Law.


text: docker run -v %~dp0:/output -w /magick -it magick-net-linux /bin/bash


text:
{% comment %}
*
*   This include lets you loop through a collection to list
*   all entries in that collection.
*
*   If you set »published: false« in front matter of a collection page
*   the page gots filtered out via unless
*
*   Example: {% include list-collection.html collection='wordpress' %}
*
{% endcomment %}

  {% for page in site.[include.collection] %}
    {% unless page.published == false %}

{{ page.title }}

    {% endunless %}
  {% endfor %}


text:
layout: post
title:  "java bei uberspace"
meta:   java, uberspace
---
als erinnerung für mich

{% highlight bash %}
JAVA_HOME=$HOME/bin/jre1.7.0/
export JAVA_HOME=$JAVA_HOME
export PATH=$PATH:$JAVA_HOME/bin
{% endhighlight %}

dabei ist ein standard jre in `~/bin` entpackt


text:
PATH=/sbin:/bin:/usr/bin:/usr/sbin:/
export PATH

termfile=/tmp/sysinst.term

# Check if we are on a framebuffer or on serial console and default
# the terminal type accordingly.
# There is no /var/db/dev.cdb, so sysctl might not map the devicename properly;
# ttyE0 is 90,0 -> 0x5a00
case $(sysctl -nx kern.consdev) in
 002f000000000000)
    TERM=wsvt25
    ;;
 *)
    if [ -r ${termfile} ]; then
	. ${termfile}
    else
	TERM=vt220
    fi
    ;;
esac

export TERM
HOME=/
export HOME
BLOCKSIZE=1k
export BLOCKSIZE
EDITOR=ed
export EDITOR
SHELL=/bin/sh
export SHELL

umask 022

stty newcrt werase ^W intr ^C kill ^U erase ^?
if [ $TERM != "wsvt25" ]; then
	cat << "EOM"

You are using a serial console, we do not know your terminal emulation.
Please select one, typical values are:

	vt100
	ansi
	xterm

EOM
	echo -n "Terminal type (just hit ENTER for '$TERM'): "
	read ans
	if [ -n "$ans" ];then
	    TERM=$ans
	fi
fi

# run the installation or upgrade script.
cd /
cmd=./sysinst

while [ -n "${cmd}" ]
do
	${cmd}
	if [ $? = 4 ]; then
		echo "Oops, something went wrong - we will try again"
		exit
	else
		if [ -n "$(jobs)" ]; then
			tput clear
			echo "You have stopped sysinst, return to it by" \
				"typing 'exit' or ^D."
			${SHELL} -i
			cmd="fg"
		else
			cmd=""
		fi
	fi
done

# remember terminal type, now that we know it for sure
echo "TERM=${TERM}" > ${termfile}
echo
echo "To return to the installer, quit this shell by typing 'exit' or ^D."
exec ${SHELL}


text:
package cgeo.geocaching.maps.routing;

import cgeo.geocaching.utils.Log;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;

import androidx.annotation.Nullable;

class AbstractServiceConnection implements ServiceConnection {
    protected android.os.IInterface routingService;
    private Runnable onServiceConnectedCallback = null;

    AbstractServiceConnection(final @Nullable Runnable onServiceConnectedCallback) {
        this.onServiceConnectedCallback = onServiceConnectedCallback;
    }

    @Override
    public void onServiceConnected(final ComponentName className, final IBinder service) {
        Log.d("connection to brouter established");
        if (null != onServiceConnectedCallback) {
            onServiceConnectedCallback.run();
        }
    }

    @Override
    public void onServiceDisconnected(final ComponentName className) {
        Log.d("connection to brouter disconnected");
        this.onServiceConnectedCallback = null;
        routingService = null;
    }

    public boolean isConnected() {
        return routingService != null;
    }

    @Nullable
    public String getTrackFromParams(final Bundle params) {
        return null;
    }

}


text:
<!-- HTML Document -->

<div class="bbn-overlay">
  <bbn-multipart :source="items"
                 @success="success"
                 :closable="true"/>
</div>