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

namespace Sandboxable.Microsoft.WindowsAzure.Storage.Table.Protocol
{
    using Sandboxable.Microsoft.WindowsAzure.Storage.Core.Util;
    using Sandboxable.Microsoft.WindowsAzure.Storage.Shared.Protocol;
    using System.IO;
    using System.Net;

    /// <summary>
    /// Provides a set of methods for parsing a response stream from the Table service.
    /// </summary>
    public static class TableHttpWebResponseParsers
    {
        /// <summary>
        /// Gets the request ID from the response.
        /// </summary>
        /// <param name="response">The web response.</param>
        /// <returns>A unique value associated with the request.</returns>
        public static string GetRequestId(HttpWebResponse response)
        {
            return Response.GetRequestId(response);
        }

        /// <summary>
        /// Reads service properties from a stream.
        /// </summary>
        /// <param name="inputStream">The stream from which to read the service properties.</param>
        /// <returns>The service properties stored in the stream.</returns>
        public static ServiceProperties ReadServiceProperties(Stream inputStream)
        {
            return HttpResponseParsers.ReadServiceProperties(inputStream);
        }

        /// <summary>
        /// Reads service stats from a stream.
        /// </summary>
        /// <param name="inputStream">The stream from which to read the service stats.</param>
        /// <returns>The service stats stored in the stream.</returns>
        public static ServiceStats ReadServiceStats(Stream inputStream)
        {
            return HttpResponseParsers.ReadServiceStats(inputStream);
        }

        /// <summary>
        /// Reads the share access policies from a stream in XML.
        /// </summary>
        /// <param name="inputStream">The stream of XML policies.</param>
        /// <param name="permissions">The permissions object to which the policies are to be written.</param>
        public static void ReadSharedAccessIdentifiers(Stream inputStream, TablePermissions permissions)
        {
            CommonUtility.AssertNotNull("permissions", permissions);

            HttpResponseParsers.ReadSharedAccessIdentifiers(permissions.SharedAccessPolicies, new TableAccessPolicyResponse(inputStream));
        }
    }
}


text:
module Tarona
  module Game
    class HudSupport
      # Sends short information about entity when it is requested through
      # `Tardvig::GameIO`
      #
      # It responds to the `entity_info_request` event with attributes: `id`
      # (Entity's identificator).
      # It sends back the `entity_info_show` with some entity's attributes
      # (keys are original names of the attributes).
      #
      # You must set attributes below using `Tardvig::Command` interface to
      # start this command.
      # @!attribute [r] act
      #   @return [Tarona::Action] current act.
      # @!attribute [r] session
      #   @return [#[]] information about current game state.
      # @see Tarona::PrManager
      class EntityInfo < Tarona::PrManager
        # Attributes of Entity which will be send if they exist.
        ATTRIBUTES = [:name, :hp, :max_hp, :energy, :max_energy].freeze

        private

        def job_type
          :entity_info
        end

        def job(msg)
          entity = get_entity msg[:id]
          attrs = attributes(entity)
          @act.io.happen :entity_info_show, attrs unless attrs.empty?
        end

        def get_entity(id)
          map = @session[:act_inf][:landscape]
          index = @session[:act_inf][:entities_index]
          Tarona::Action::PlaceEntity.find map, index, id
        end

        def attributes(entity)
          result = {}
          ATTRIBUTES.each do |attr_name|
            next unless entity.respond_to? attr_name
            result[attr_name] = entity.send attr_name
          end
          result
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
"""
Methods for performing binary set operations on IndexSets.

"direct" methods refer to building a new 2d array of locations that is the
result of a binary set operation. They are always lexicographically sorted
and contain only unique rows. These methods return nothing else.

"contrib" methods also build the final locations, but they additionally
provide information that indicates which locations from the parent IndexSets
contributed to the result. This is used for merging the data associated with
the input IndexSets.

"indirect" Like contrib, these provide the final result locations and extra
information. Indirect gives the locations in the final array that come from
a given IndexSet. They are the size of the final array with the number of
True values equal to the number of values in the IndexSet.
"""
import numpy as np
import numba
from concurrent.futures import ThreadPoolExecutor

from ...settings import parse_chunk_args
from ...chunk import gen_cochunks
from ...indexset import IndexSet, concat_sorted_nonoverlapping
from ...flags import SORTED, UNIQUE, DATA_DEFAULT
from ...data import all_short_circuit_merges
from ...encoding import compatible_encoding

from .intersection_contrib import intersection_contrib_
from .intersection_direct import intersection_direct_
from ...data import merge_data_direct

@numba.njit(nogil=True)
def intersection_(a, b, MERGE=None):
    """ Find the locations common to both a and b, merging data if necessary.

    Arguments
    ---------
    a, b : IndexSet instances
    MERGE : array of uint8 | None
        Per-dimension flag indicating how to merge data from locations present
        in both IndexSets. This affects the resulting data even if one of the
        inputs has None for data.

        `MERGE` may have a single value, in which case the merge action is
        applied to all data columns, or have a length equal to the number of
        data columns, each data column is merged according to the
        corresponding flag. This argument must be an array.

    Returns
    -------
    IndexSet with the coordinates that are in both a and b. Data in the
    overlap will be merged according to MERGE flags.

    Notes
    -----
    The following flags are can be used in the MERGE array:
    * 2 DATA_NANSUM
        Add all data in corresponding locations, treating NaNs as zero
    * 3 DATA_SUM
        Add all data in corresponding locations, propagating NaNs.
    * 4 DATA_NANMAX
        Take the maximum contributing datum for each location, ignoring
        NaN values. If all contributors are NaN, the result is NaN.
    * 5 DATA_MAX
        Take the maximum datum at each location, propagating NaNs. If any
        contributing data are NaN, then the result is NaN
    * 6 DATA_NANMIN
        Take the minimum contributing datum for each location, ignoring
        NaN values. If all contributors are NaN, the result is NaN.
    * 7 DATA_MIN
        Take the minimum datum at each location, propagating NaNs. If any
        contributing data are NaN, then the result is NaN
    * 8 DATA_NANFIRST
        Find the first non-NaN data from the contributing IndexSets, in
        order of their input. If all data are NaN, then the result is NaN.
    * 10 DATA_NANLAST
        Find the last non-NaN data from the contributing IndexSets, in
        order of their input. If all data are NaN, then the result is NaN.

    The default merge mode is _BLAHB_DATA_FIRST will be applied if None
    is given instead of an array.
    """
    if a.is_empty:
        return a
    elif b.is_empty:
        return b

    if MERGE is None:
        MERGE = np.array([DATA_DEFAULT], dtype=np.uint8)

    ndim = a.ndim
    assert ndim == b.ndim

    if (a.data is not None) and (b.data is not None):
        # Both data are present

        if compatible_encoding(a, b):
            take_a, take_b = intersection_contrib_(
              a._loc.view(np.uint32), b._loc.view(np.uint32))
            c = a.take(take_a)
        else:
            take_a, take_b = intersection_contrib_(a.loc, b.loc)
            c = IndexSet(a.loc[take_a], UNIQUE | SORTED)

        data = a.data[take_a]
        data = merge_data_direct(b.data, take_b, data, MERGE)
        c.data = data

    elif a.data is None and b.data is None:
        # Both have no data, result has None data
        # We should use the direct method with the smallest footprint
        if b.n < a.n:
            a, b = b, a

        if compatible_encoding(a, b):
            take_a, take_b = intersection_contrib_(
              a._loc.view(np.uint32), b._loc.view(np.uint32))
            c = a.take(take_a)
        else:
            take_a = intersection_direct_(a.loc, b.loc)
            c = IndexSet(a.loc[take_a], UNIQUE | SORTED)
        c._data = None

    else:
        # Exactly one of `a` or `b` has data: make `a` the one with data
        if b.data is not None:
            a, b = b, a  # a is now the one with data

        if compatible_encoding(a, b):
            take_a = intersection_direct_(
                a._loc.view(np.uint32), b._loc.view(np.uint32))
            c = a.take(take_a)
        else:
            take_a = intersection_direct_(a.loc, b.loc)
            c = IndexSet(a.loc[take_a], UNIQUE | SORTED)

        if all_short_circuit_merges(MERGE):
            c._data = None
        else:
            data = a.data[take_a]
            # Take a will be ignored because b.data is None
            data = merge_data_direct(b.data, take_a, data, MERGE)
            if data is None:
                c._data = None
            else:
                c.data = data

    return c

@numba.njit(nogil=True)
def intersection_multi_(MERGE, *indexsets):
    """Find the pixelsets common to any of the input objects.

    Arguments
    ---------
    MERGE : None | uint8 array of MERGE flags
    *indexsets : Variable number of IndexSet objects.

    Returns
    -------
    The union of the locations in all input IndexSets.

    Notes
    -----
    `MERGE` is the first argument, this order differs from both
    `intersection` and `intersection_`.

    This function will be recompiled every time it is called with a new number
    of IndexSets.
    """
    n = len(indexsets)
    if n == 0:
        raise ValueError("must have at least 1 input.")
    elif n == 1:
        return indexsets[0]

    result = indexsets[0]
    for i in range(1, n):
        if result.n == 0:
            return result
        result = intersection_(result, indexsets[i], MERGE)
    return result

def intersection(objs, MERGE=None, **chunk_args):
    """Merge the locations and data common to all IndexSets.

    Arguments
    ---------
    objs : sequence of IndexSet objects
    MERGE : array of uint8
        See `union_` documentation for more details.
    **chunk_args : Options to control chunk size and parallelization.
        Can be some of the following optional arguments:
        * n_workers - Number of worker threads to map chunked operations onto.
        This value will be passed to concurrent.futures.ThreadPoolExecutor as
        the `max_workers` argument.
        * max_chunk_size - Maximum number of locations
        * min_chunk_size - Minimum number of locations
        * n_chunks - Minimum number of chunks to break an IndexSet into.

    Returns
    -------
    The set union of the rows in `objs`. Any data present is merged according
    to the MERGE flags provided.
    """
    n_workers, n_chunks, min_chunk_sz, max_chunk_sz = parse_chunk_args(
        **chunk_args)

    intersection_fn = lambda objs: intersection_multi_(MERGE, *objs)

    # Do not chunk
    if n_chunks == n_workers == 1 and max(o.n for o in objs) <= max_chunk_sz:
        return intersection_fn(objs)

    filter_chunk = lambda x: x.n > 0
    _gen = gen_cochunks(objs, filter_chunk=filter_chunk, **chunk_args)
    if n_workers == 1:  # Chunk but do not use threads
        indexsets = tuple(map(intersection_fn, _gen))
    else:  # Chunk but do not use threads
        with ThreadPoolExecutor(max_workers=n_workers) as thread_pool:
            indexsets = tuple(thread_pool.map(intersection_fn, _gen))

    return concat_sorted_nonoverlapping(indexsets)


text:
![](https://nexus.lab.fiware.org/static/badges/statuses/deprecated.svg)

> This repository is now archived and subsequent works will be carried out the
> in [Smart data models](https://github.com/smart-data-models) repositories.

As an alternative or extension to traditional interactive points (shopping
malls, museums, airports, etc.), a Smart Point of Interaction use technologies
such as Bluetooth Low Energy or Wi-Fi to bring new interactions to user's
devices (smartphones, wearables, etc.).

A smart point of interaction is composed mainly by two entities:

-   "Smart Point of Interaction": defines an interactive point which provides
    information, entertainment or co-creation tools to citizens. Optionally it
    can reference a related smart city asset with enriched interaction provided
    by this technology.
-   "Smart Spot": a set of resources related to a physical device and the
    technology to provide a Smart Point of Interaction.

Next illustration shows the data model architecture:


text:
<html>
<body>

Support for managing of Operating System events through the Admin API.

</body>
</html>


text:
<?php

namespace Puli\Manager\Tests\Server;

/**
 * @since  1.0
 * @author Bernhard Schussek <bschussek@gmail.com>
 */
class PackageFileServerManagerLoadedTest extends PackageFileServerManagerUnloadedTest
{
    protected function populateDefaultManager()
    {
        parent::populateDefaultManager();

        // Load the servers
        $this->serverManager->getServers();
    }
}


text:
/*! \file raw_buffer.h
 *  \brief Container-like class for wrapped malloc/free.
 */

#pragma once

#include <thrust/detail/device/internal_allocator.h>
#include <thrust/iterator/detail/normal_iterator.h>
#include <thrust/iterator/iterator_traits.h>
#include <memory>

namespace thrust
{

// forward declaration of device_malloc_allocator
template<typename T> class device_malloc_allocator;

namespace detail
{

// forward declaration of normal_iterator
template<typename> class normal_iterator;

template<typename T, typename Space>
  struct choose_raw_buffer_allocator
    : eval_if<
        // catch any_space_tag and output an error
        is_convertible<Space, thrust::any_space_tag>::value,

        void,

        eval_if<
          // XXX this check is technically incorrect: any could convert to host
          is_convertible<Space, thrust::host_space_tag>::value,

          identity_< std::allocator<T> >,

          // XXX add backend-specific allocators here?

          eval_if<
            // XXX this check is technically incorrect: any could convert to device
            is_convertible<Space, thrust::device_space_tag>::value,

            identity_< thrust::detail::device::internal_allocator<T> >,

            void
          >
        >
      >
{};

template<typename T, typename Space>
  class raw_buffer
{
  public:
    typedef typename choose_raw_buffer_allocator<T,Space>::type allocator_type;
    typedef T                                                   value_type;
    typedef typename allocator_type::pointer                    pointer;
    typedef typename allocator_type::const_pointer              const_pointer;
    typedef typename allocator_type::reference                  reference;
    typedef typename allocator_type::const_reference            const_reference;
    typedef typename std::size_t                                size_type;
    typedef typename allocator_type::difference_type            difference_type;

    typedef normal_iterator<pointer>                            iterator;
    typedef normal_iterator<const_pointer>                      const_iterator;

    explicit raw_buffer(size_type n);

    template<typename InputIterator>
    raw_buffer(InputIterator first, InputIterator last);

    ~raw_buffer(void);

    size_type size(void) const;

    iterator begin(void);

    const_iterator begin(void) const;

    const_iterator cbegin(void) const;

    iterator end(void);

    const_iterator end(void) const;

    const_iterator cend(void) const;

    reference operator[](size_type n);

    const_reference operator[](size_type n) const;

  protected:
    allocator_type m_allocator;

    iterator m_begin, m_end;

  private:
    // disallow assignment
    raw_buffer &operator=(const raw_buffer &);
}; // end raw_buffer

template<typename T>
  class raw_omp_device_buffer
    : public raw_buffer<T, thrust::detail::omp_device_space_tag >
{
  private:
    typedef raw_buffer<T, thrust::detail::omp_device_space_tag > super_t;

  public:
    explicit raw_omp_device_buffer(typename super_t::size_type n):super_t(n){}

    template<typename InputIterator>
    raw_omp_device_buffer(InputIterator first, InputIterator last):super_t(first,last){}
}; // end raw_omp_device_buffer

template<typename T>
  class raw_cuda_device_buffer
    : public raw_buffer<T, thrust::detail::cuda_device_space_tag >
{
  private:
    typedef raw_buffer<T, thrust::detail::cuda_device_space_tag > super_t;

  public:
    explicit raw_cuda_device_buffer(typename super_t::size_type n):super_t(n){}

    template<typename InputIterator>
    raw_cuda_device_buffer(InputIterator first, InputIterator last):super_t(first,last){}
}; // end raw_cuda_device_buffer

template<typename T>
  class raw_host_buffer
    : public raw_buffer<T, thrust::host_space_tag >
{
  private:
    typedef raw_buffer<T, thrust::host_space_tag > super_t;

  public:
    explicit raw_host_buffer(typename super_t::size_type n):super_t(n){}

    template<typename InputIterator>
    raw_host_buffer(InputIterator first, InputIterator last):super_t(first,last){}
}; // end raw_host_buffer

// XXX eliminate this when we do ranges for real
template<typename Iterator>
  class iterator_range
{
  public:
    iterator_range(Iterator first, Iterator last)
      : m_begin(first), m_end(last) {}

    Iterator begin(void) const { return m_begin; }
    Iterator end(void) const { return m_end; }

  private:
    Iterator m_begin, m_end;
};

// if the space of Iterator1 is convertible to Iterator2, then just make a shallow
// copy of the range.  else, use a raw_buffer
template<typename Iterator1, typename Iterator2>
  struct move_to_space_base
    : public eval_if<
        is_convertible<
          typename thrust::iterator_space<Iterator1>::type,
          typename thrust::iterator_space<Iterator2>::type
        >::value,
        identity_<
          iterator_range<Iterator1>
        >,
        identity_<
          raw_buffer<
            typename thrust::iterator_value<Iterator1>::type,
            typename thrust::iterator_space<Iterator2>::type
          >
        >
      >
{};

template<typename Iterator1, typename Iterator2>
  class move_to_space
    : public move_to_space_base<
        Iterator1,
        Iterator2
      >::type
{
  typedef typename move_to_space_base<Iterator1,Iterator2>::type super_t;

  public:
    move_to_space(Iterator1 first, Iterator1 last)
      : super_t(first, last) {}
};

} // end detail

} // end thrust

#include <thrust/detail/raw_buffer.inl>


text:
package org.snia.cdmiserver.dao.filesystem;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snia.cdmiserver.dao.CdmiObjectDao;
import org.snia.cdmiserver.dao.DomainDao;
import org.snia.cdmiserver.model.CdmiObject;
import org.snia.cdmiserver.model.Domain;

public class DomainDaoImpl implements DomainDao {

  private static final Logger LOG = LoggerFactory.getLogger(DomainDaoImpl.class);

  private String baseDirectoryName;

  private CdmiObjectDao cdmiObjectDao;

  public String getBaseDirectoryName() {
    return baseDirectoryName;
  }

  public void setBaseDirectoryName(String baseDirectoryName) {
    this.baseDirectoryName = baseDirectoryName;
  }

  public CdmiObjectDao getCdmiObjectDao() {
    return cdmiObjectDao;
  }

  public void setCdmiObjectDao(CdmiObjectDao cdmiObjectDao) {
    this.cdmiObjectDao = cdmiObjectDao;
  }

  @Override
  public CdmiObject createByPath(String path, Domain domainRequest) {
    LOG.debug("create domain {} {}", path.trim(), domainRequest.toString());
    // TODO
    return null;
  }

  @Override
  public void deleteByPath(String path) {
    LOG.debug("delete domain {}", path.trim());
    // TODO
  }

  @Override
  public CdmiObject findByObjectId(String objectId) {
    return cdmiObjectDao.getCdmiObject(objectId);
  }

  @Override
  public CdmiObject findByPath(String path) {
    LOG.debug("path is {}", path);
    return (Domain) cdmiObjectDao.getCdmiObjectByPath(path.trim());
  }

  @Override
  public CdmiObject updateByPath(String path, Domain domain, String[] requestedFields) {
    // TODO Auto-generated method stub
    return null;
  }
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TFOI.menus
{
    /// <summary>
    /// Interaction logic for PageBosses.xaml
    /// </summary>
    public partial class PageBosses : Page
    {
        public PageBosses()
        {
            InitializeComponent();
        }

        string selectedBoss;
        DropShadowEffect glowSelected;

        private void Grid_Loaded(object sender, RoutedEventArgs e)
        {
            glowSelected = new DropShadowEffect();
            glowSelected.ShadowDepth = 0;
            glowSelected.BlurRadius = 15;
            glowSelected.Color = Colors.Red;

            foreach (var boss in Bosses.List)
            {
                var icon = new Image();

                if (boss.Name == "Haunt 2") //quick & dirty
                    boss.Name = "The Forsaken";

                icon.ToolTip = boss.Name + Environment.NewLine + boss.Text;

                icon.Name = "_" + boss.Id;
                icon.Tag = "HP: " + boss.HP;
                icon.Stretch = Stretch.None;
                icon.Source = Stuff.BitmapToImageSource(boss.Icon);

                bossPanel.Children.Add(icon);
                icon.MouseLeftButtonDown += new MouseButtonEventHandler(icon_MouseLeftButtonDown);
            }

            PopulateStats();        //query the db every time you navigate to the page to refresh the stats
        }

        private void icon_MouseLeftButtonDown(object sender, RoutedEventArgs e)
        {
            int timesDefeatedByBoss = 0;

            System.Windows.Controls.Image image = sender as System.Windows.Controls.Image;      //boss logo stuff
            textBossInfo.Text = image.Tag.ToString();
            bossNameLogo.Source = Stuff.BitmapToImageSource(Bosses.List.Find(x => x.Id == image.Name.TrimStart('_')).NameLogo);

            foreach (Image boss in bossPanel.Children)
                boss.Effect = null;

            image.Effect = glowSelected;

            selectedBoss = image.Name.TrimStart('_');                               //get the boss id
            Database.SelectBoss(dataGrid, selectedBoss);                            //and run the query with it

            if (Database.dataTable.Rows.Count == 1)
                timesFought.Text = "FOUGHT " + Database.dataTable.Rows.Count.ToString() + " TIME";
            else
                timesFought.Text = "FOUGHT " + Database.dataTable.Rows.Count.ToString() + " TIMES";

            foreach (DataRow value in Database.dataTable2.Rows)                     ////////// THIS IS THE UTILITY DATATABLE //////////
            {
                if (value != null)                                                      //shit happens
                    if (!string.IsNullOrEmpty((string)value.ItemArray[6]))              //KilledBy
                        if ((string)value.ItemArray[6] == selectedBoss)                 //defeated by the selected boss in that run?
                            timesDefeatedByBoss++;
            }

            if (timesDefeatedByBoss == 0 && Database.dataTable.Rows.Count > 0)
                winRate.Text = "100% WINRATE!";
            else if (Database.dataTable.Rows.Count == 0)
                winRate.Text = string.Empty;
            else
                winRate.Text = (((Database.dataTable.Rows.Count - timesDefeatedByBoss) / Database.dataTable.Rows.Count) * 100f).ToString("0") + "% WIN RATE"; //(encounters-defeats=wins)/encounters=win rate
        }

        private void PopulateStats()
        {
            string bossListDefeated = string.Empty;
            string bossListNemeses = string.Empty;

            Database.SelectAll();

            foreach (DataRow value in Database.dataTable2.Rows)
            {
                if (!string.IsNullOrEmpty((string)value.ItemArray[5]))          //bosses
                    bossListDefeated += (string)value.ItemArray[5] + ',';

                if (!string.IsNullOrEmpty((string)value.ItemArray[6]))          //nemeses
                    bossListNemeses += (string)value.ItemArray[6] + ',';
            }

            var top5DefeatedList = Stuff.SortTopBosses(bossListDefeated, 5);
            foreach (var boss in top5DefeatedList)
            {
                var icon = new Image();
                icon.Stretch = Stretch.None;
                icon.ToolTip = boss.Name + Environment.NewLine + "Times fought: " + boss.TimesFought.ToString();
                icon.Source = Stuff.BitmapToImageSource(boss.Icon);
                top5Defeated.Children.Add(icon);
            }

            var top5NemesesList = Stuff.SortTopBosses(bossListNemeses, 5);
            foreach (var boss in top5NemesesList)
            {
                var icon = new Image();
                icon.Stretch = Stretch.None;
                icon.ToolTip = boss.Name + Environment.NewLine + "Times you GIT REK: " + boss.TimesFought.ToString();
                icon.Source = Stuff.BitmapToImageSource(boss.Icon);
                top5Nemeses.Children.Add(icon);
            }
        }

        private void back_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MainWindow.mainWindow.mainWindowFrame.GoBack();
        }
        private void back_MouseEnter(object sender, MouseEventArgs e)
        {
            back_.Visibility = Visibility.Visible;
        }
        private void back_MouseLeave(object sender, MouseEventArgs e)
        {
            back_.Visibility = Visibility.Hidden;
        }
    }
}


text:
"use strict";
require("requirish")._(module);
/* jslint */
/*global require,describe, it, before, after */
var should = require("should");

var server_engine = require("lib/server/server_engine");
var NodeClass = require("lib/datamodel/nodeclass").NodeClass;

var DataType = require("lib/datamodel/variant").DataType;
var Variant = require("lib/datamodel/variant").Variant;

var AttributeIds = require("lib/services/read_service").AttributeIds;
var AddressSpace = require("lib/address_space/address_space").AddressSpace;
var _ = require("underscore");
var path = require("path");
var assert = require("better-assert");
var util = require("util");

var generate_address_space = require("lib/address_space/load_nodeset2").generate_address_space;

var checkSelectClauses = require("lib/tools/tools_event_filter").checkSelectClauses;
var extractEventFields = require("lib/tools/tools_event_filter").extractEventFields;

var StatusCodes = require("lib/datamodel/opcua_status_code").StatusCodes;
var subscription_service = require("lib/services/subscription_service");
var SimpleAttributeOperand = subscription_service.SimpleAttributeOperand;

describe("testing Events  ", function () {

    var addressSpace;
    var eventType;
    before(function (done) {
        addressSpace = new AddressSpace();
        var xml_file = path.join(__dirname,"../../lib/server/mini.Node.Set2.xml");
        require("fs").existsSync(xml_file).should.be.eql(true);
        generate_address_space(addressSpace, xml_file, function (err) {
            eventType = addressSpace.addEventType({browseName: "MyEventType"});
            done(err);
        });
    });
    after(function(){
        addressSpace.dispose();
        addressSpace = null;
        eventType = null;
    });

    it("should create a new EventType", function () {
        eventType.browseName.toString().should.eql("MyEventType");
    });

    var EventEmitter = require("events").EventEmitter;

    function Observer() {
    }

    util.inherits(Observer, EventEmitter);

    it("should raise a new EventType", function (done) {

        var serverObject = addressSpace.findNode("Server");
        serverObject.browseName.toString().should.eql("Server");

        var eventType = addressSpace.findEventType("MyEventType");

        var observer = new Observer();

        observer.on_event = function (evtData) {

            console.log(" EVENT RECEIVED :", evtData.sourceName.value);
            evtData.sourceName.dataType.should.eql(DataType.String);

            done();
        };

        serverObject.once("event", observer.on_event.bind(observer));

        serverObject.raiseEvent(eventType, {
            sourceName: {dataType: "String", value: "Hello"},
            sourceNode: {dataType: "NodeId", value: serverObject.nodeId},
            message: {dataType: "String", value: "Hello World"}
        });

    });

    // select clause
    var subscription_service = require("lib/services/subscription_service");
    it("should extract EventData from an select clause", function () {

        var baseEventType = addressSpace.findEventType("BaseEventType");

        var eventFilter = new subscription_service.EventFilter({

            selectClauses: [ // SimpleAttributeOperand
                {
                    // This parameter restricts the operand to instances of the TypeDefinitionNode or
                    //  one of its subtypes
                    typeId: baseEventType.nodeId,
                    browsePath: [
                        {name: "EventId"}
                    ],
                    attributeId: AttributeIds.Value,
                    indexRange: null
                },
                {typeId: baseEventType.nodeId,browsePath: [{name: "SourceNode"}], attributeId: AttributeIds.Value},
                {typeId: baseEventType.nodeId,browsePath: [{name: "SourceName"}], attributeId: AttributeIds.Value},
                {typeId: baseEventType.nodeId,browsePath: [{name: "ReceiveTime"}], attributeId: AttributeIds.Value}
            ],
            whereClause: []
        });
        eventFilter.selectClauses[0].should.be.instanceof(SimpleAttributeOperand);

        var auditEventType = addressSpace.findEventType("AuditEventType");
        //xx var auditEventInstance =  auditEventType.instantiate({browseName: "Instantiation"});
        // if (eventFilter.selectClauses.length===0) {return 0;}
        var selectClauseResults = checkSelectClauses(auditEventType, eventFilter.selectClauses);

        selectClauseResults.length.should.eql(eventFilter.selectClauses.length);
        console.log(selectClauseResults);

        var eventFields = extractEventFields(auditEventType, eventFilter.selectClauses,{__nodes:{}});
        eventFields.length.should.eql(eventFilter.selectClauses.length);

        var eventFieldList = new subscription_service.EventFieldList({
            clientHandle: 1,
            eventFields: /* Array<Variant> */ eventFields
        });
        //xx console.log("xxxx ",eventField.toString());

    });

    it("should filter an event", function (done) {

        var serverObject = addressSpace.findNode("Server");
        serverObject.browseName.toString().should.eql("Server");

        var eventType = addressSpace.findEventType("MyEventType");

        var eventFilter = new subscription_service.EventFilter({
            selectClauses: [ // SimpleAttributeOperand
                {
                    // This parameter restricts the operand to instances of the TypeDefinitionNode or
                    //  one of its subtypes
                    typeId: null,
                    browsePath: [
                        {name: "EventId"}
                    ],
                    attributeId: AttributeIds.Value,
                    indexRange: null
                },
                {browsePath: [{name: "SourceNode"}], attributeId: AttributeIds.Value},
                {browsePath: [{name: "SourceName"}], attributeId: AttributeIds.Value},
                {browsePath: [{name: "ReceiveTime"}], attributeId: AttributeIds.Value}
            ],
            whereClause: []
        });

        var rTime = new Date(1789,6,14);

        var data = {
            sourceName: {dataType: "String", value: "Hello"},
            sourceNode: {dataType: "NodeId", value: serverObject.nodeId},
            message: {dataType: "String", value: "Hello World"},
            receiveTime: {dataType: "DateTime",value: rTime}
        };
        var eventData = addressSpace.constructEventData(eventType,data);

        var eventFields = extractEventFields(eventType,eventFilter.selectClauses,eventData);

        // make sure all event fields are Variant
        eventFields.forEach(function(e){
            e.should.instanceOf(Variant);
        });

        eventFields.length.should.eql(4);
        eventFields.forEach(function(f){ return console.log( f.toString());});

        eventFields[1].value.should.eql(serverObject.nodeId); // sourceNode
        eventFields[2].value.should.eql("Hello");
        eventFields[2].dataType.should.eql(DataType.String); // sourceName
        eventFields[3].dataType.should.eql(DataType.DateTime);

        console.log(" EVENT RECEIVED :", eventData.sourceName.value);
        done();

    });

    //     Area1
    //       |
    //       | hasNotifier
    //     Tank1
    //    /    \
    //   /      \ hasEventSource
    //  Pump   TempSensor
    //
    it("should bubble events up",function(){

        var area1 = addressSpace.createNode({
            nodeClass:   NodeClass.Object,
            browseName:  "Area1",
            organisedBy: "Objects"
        });
        area1.browseName.name.should.eql("Area1");

        var tank1 = addressSpace.createNode({
            nodeClass:   NodeClass.Object,
            browseName:  "Tank1",
            componentOf: area1,
            notifierOf:  area1
        });
        tank1.browseName.name.should.eql("Tank1");

        var pump = addressSpace.createNode({
            nodeClass:     NodeClass.Object,
            browseName:    "Pump",
            componentOf:   tank1,
            eventSourceOf: tank1,
            eventNotifier: 1
        });
        var pumpStartEventType = addressSpace.addEventType({browseName: "PumpStartEventType"});
        pumpStartEventType.browseName.toString().should.eql("PumpStartEventType");
        pumpStartEventType.subtypeOfObj.browseName.toString().should.eql("BaseEventType");

        var receivers = [];
        function spyFunc(object,data) {
            var self =this;
            console.log("object ",self.browseName.toString(), " received Event");
            receivers.push(self.browseName.toString());
        }
        var server = addressSpace.findNode("Server");

        server.on("event",spyFunc.bind(server));
        pump.on("event",spyFunc.bind(pump));
        tank1.on("event",spyFunc.bind(tank1));
        area1.on("event",spyFunc.bind(area1));

        var eventData = {};
        pump.raiseEvent(pumpStartEventType,eventData);

        receivers.should.eql([
            "Server","Pump","Tank1","Area1"
        ])

    });

});


text:
//*********************************************************//
//    Copyright (c) Microsoft. All rights reserved.
//
//    Apache 2.0 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.
//
//*********************************************************//

using System;
using System.Windows.Forms;

namespace Microsoft.NodejsTools.Project {
    public partial class NewFileNameForm : Form {
        public NewFileNameForm(string initialFileName) {
            InitializeComponent();
            TextBox.Text = initialFileName;
        }

        public TextBox TextBox {
            get {
                return textBox;
            }
        }

        private void TextBox_TextChanged(object sender, EventArgs e) {
            if (TextBox.Text.Trim().Length == 0) {
                okButton.Enabled = false;
            } else {
                okButton.Enabled = true;
            }
        }
    }
}


text:
package com.corejsf;

import java.beans.FeatureDescriptor;
import java.util.Iterator;
import javax.el.ELContext;
import javax.el.ELResolver;
import javax.faces.component.UIComponent;

public class ComponentIdResolver extends ELResolver {
   public Object getValue(ELContext context, Object base, Object property) {
      if (base instanceof UIComponent && property instanceof String) {
         UIComponent r = ((UIComponent) base).findComponent((String) property);
         if (r != null) {
            context.setPropertyResolved(true);
            return r;
         }
      }
      return null;
   }

   public Class<?> getType(ELContext context, Object base, Object property) {
      if (base instanceof UIComponent && property instanceof String) {
         context.setPropertyResolved(true);
         return UIComponent.class;
      }
      return null;
   }

   public void setValue(ELContext context, Object base, Object property,
         Object value) {
   }

   public boolean isReadOnly(ELContext context, Object base,
         Object property) {
      if (base instanceof UIComponent && property instanceof String) {
         context.setPropertyResolved(true);
         return true;
      }
      return false;
   }

   public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context,
         Object base) {
      return null;
   }

   public Class<?> getCommonPropertyType(ELContext context, Object base) {
      if (base instanceof UIComponent)
         return String.class;
      return null;
   }
}


text:
<resources>
    <style name="MyAppTheme" parent="AppTheme">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorLight</item>
    </style>

    <!-- Test translucent -->
    <color name="colorDim">#80000000</color>
    <style name="MyDialog">
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:backgroundDimEnabled">true</item>
    </style>
</resources>


text:
import events from 'events';

export function InputHandler() {
  const input = document.createElement('input');

  input.setAttribute('type', 'text');

  return input;
}

export default function renderer(element) {
  const canvas = document.createElement('canvas');
  const context = canvas.getContext('2d');
  const emitter = new events.EventEmitter();
  const input = InputHandler();

  let width, height;

  function resizeToFill() {
    width = canvas.width = element.offsetWidth;
    height = canvas.height = element.offsetHeight;
    return [width, height];
  }

  // Call this function with the new state every time something
  // changes.
  function render(state) {
    if(canvas.width !== width || canvas.height !== height) {
      resizeToFill();
      emitter.emit('resize', width, height);
    }

    // ..........................
    // state specific render code
    // ..........................
    const c = context;

    c.clearRect(0, 0, width, height);

    state.players.forEach(player => {
      // draw a player
    });

    state.fx.forEach(fx => {
      // draw some fx, e.g. a bullet
    });
    // ..............................
    // end state specific render code
    // ..............................
  }

  input.addEventListener('keydown' ({ which }) => {
    emitter.emit('keydown', which);
  });

  input.addEventListener('keyup' ({ which }) => {
    emitter.emit('keyup', which);
  });

  // make sure canvas fills available space
  resizeToFill();

  // add the canvas and the input handler
  element.appendChild(canvas);
  element.appendChild(input);

  // expose on as public method
  render.on = emitter.on.bind(emitter);

  return render;
}


text:
package programming.coconvariant

/**
  * Created by i311352 on 27/03/2017.
  */
//https://blog.codecentric.de/en/2015/03/scala-type-system-parameterized-types-variances-part-1/
abstract class Fruit { def name: String }

class Orange extends Fruit { def name = "Orange" }

class Apple extends Fruit { def name = "Apple" }

abstract class Box {

  def fruit: Fruit

  def contains(aFruit: Fruit) = fruit.name.equals(aFruit.name)
}

class OrangeBox(orange: Orange) extends Box {
  def fruit: Orange = orange
}

class AppleBox(apple: Apple) extends Box {
  def fruit: Apple = apple
}

class BoxT[+F <: Fruit](aFruit: F) {

  def fruit: F = aFruit

  def contains(aFruit: Fruit) = fruit.name == aFruit.name
}

object convariant extends App {

  var appleBox = new BoxT[Apple](new Apple)

  var orangeBox = new BoxT[Orange](new Orange)

  var box: BoxT[Fruit] = new BoxT[Apple](new Apple)

  var apple = new Apple
  var boxs: Box = new AppleBox(apple)
  println("box contains an $boxs.fruit.name")

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Lisp Machine</title>
  <link rel="stylesheet" href="./style.css">

    EdenApple - a Lisp Machine

	<button id="run" type="button">

</button>

  by emliunix


text:
using comhost::clsid_map_entry;
using comhost::clsid_map;

#if defined(_WIN32)

// COM entry points are defined without the __declspec(dllexport) attribute.
// The issue here is that the compiler will throw an error regarding linkage
// redefinion. The solution here is to the use a .def file on Windows.
#define COM_API extern "C"

#else

#define COM_API SHARED_API

#endif // _WIN32

//
// See ComActivator class in System.Private.CoreLib
//
struct com_activation_context
{
    GUID class_id;
    GUID interface_id;
    const pal::char_t *assembly_path;
    const pal::char_t *assembly_name;
    const pal::char_t *type_name;
    void **class_factory_dest;
};

using com_delegate_fn = int(STDMETHODCALLTYPE*)(com_activation_context*);

namespace
{
    int get_com_delegate(hostfxr_delegate_type del_type, pal::string_t *app_path, com_delegate_fn *delegate)
    {
        return load_fxr_and_get_delegate(
            del_type,
            [app_path](const pal::string_t& host_path, pal::string_t* config_path_out)
            {
                // Strip the comhost suffix to get the 'app' and config
                size_t idx = host_path.rfind(_X(".comhost.dll"));
                assert(idx != pal::string_t::npos);

                pal::string_t app_path_local{ host_path };
                app_path_local.replace(app_path_local.begin() + idx, app_path_local.end(), _X(".dll"));
                *app_path = std::move(app_path_local);

                pal::string_t config_path_local { host_path };
                config_path_local.replace(config_path_local.begin() + idx, config_path_local.end(), _X(".runtimeconfig.json"));
                *config_path_out = std::move(config_path_local);

                return StatusCode::Success;
            },
            delegate
        );
    }

    void report_com_error_info(const GUID& guid, pal::string_t errs)
    {
        ICreateErrorInfo *cei;
        if (!errs.empty() && SUCCEEDED(::CreateErrorInfo(&cei)))
        {
            if (SUCCEEDED(cei->SetGUID(guid)))
            {
                if (SUCCEEDED(cei->SetDescription((LPOLESTR)errs.c_str())))
                {
                    IErrorInfo *ei;
                    if (SUCCEEDED(cei->QueryInterface(__uuidof(ei), (void**)&ei)))
                    {
                        ::SetErrorInfo(0, ei);
                        ei->Release();
                    }
                }
            }

            cei->Release();
        }
    }
}

COM_API HRESULT STDMETHODCALLTYPE DllGetClassObject(
    _In_ REFCLSID rclsid,
    _In_ REFIID riid,
    _Outptr_ LPVOID FAR* ppv)
{
    // Check if the CLSID map contains a mapping
    clsid_map map;
    RETURN_HRESULT_IF_EXCEPT(map = comhost::get_clsid_map());

    clsid_map::const_iterator iter = map.find(rclsid);
    if (iter == std::end(map))
        return CLASS_E_CLASSNOTAVAILABLE;

    HRESULT hr;
    pal::string_t app_path;
    com_delegate_fn act;
    {
        trace::setup();
        reset_redirected_error_writer();

        error_writer_scope_t writer_scope(redirected_error_writer);

        int ec = get_com_delegate(hostfxr_delegate_type::hdt_com_activation, &app_path, &act);
        if (ec != StatusCode::Success)
        {
            report_com_error_info(rclsid, std::move(get_redirected_error_string()));
            return __HRESULT_FROM_WIN32(ec);
        }
    }

    // Query the CLR for the type

    IUnknown *classFactory = nullptr;
    com_activation_context cxt
    {
        rclsid,
        riid,
        app_path.c_str(),
        iter->second.assembly.c_str(),
        iter->second.type.c_str(),
        (void**)&classFactory
    };
    RETURN_IF_FAILED(act(&cxt));
    assert(classFactory != nullptr);

    hr = classFactory->QueryInterface(riid, ppv);
    classFactory->Release();
    return hr;
}

COM_API HRESULT STDMETHODCALLTYPE DllCanUnloadNow(void)
{
    return S_FALSE;
}

#if defined(_WIN32)

namespace
{
    const WCHAR ClsidKeyFmt[] = _X("SOFTWARE\\Classes\\CLSID\\%s");
    const WCHAR ProgIDKeyFmt[] = _X("SOFTWARE\\Classes\\%s");

    struct OleStr : public std::unique_ptr<std::remove_pointer<LPOLESTR>::type, decltype(&::CoTaskMemFree)>
    {
        OleStr(_In_z_ LPOLESTR raw)
            : std::unique_ptr<std::remove_pointer<LPOLESTR>::type, decltype(&::CoTaskMemFree)>(raw, ::CoTaskMemFree)
        { }
    };

    struct RegKey : public std::unique_ptr<std::remove_pointer<HKEY>::type, decltype(&::RegCloseKey)>
    {
        RegKey(_In_ HKEY raw)
            : std::unique_ptr<std::remove_pointer<HKEY>::type, decltype(&::RegCloseKey)>(raw, ::RegCloseKey)
        { }
    };

    // Removes the key and all sub-keys
    HRESULT RemoveRegistryKey(_In_z_ LPCWSTR regKeyPath)
    {
        assert(regKeyPath != nullptr);

        LSTATUS res;

        // Handle sub keys
        {
            HKEY toDeleteRaw;
            res = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, regKeyPath, 0, KEY_READ | KEY_WRITE, &toDeleteRaw);
            if (ERROR_FILE_NOT_FOUND == res)
            {
                return S_OK;
            }
            else if (ERROR_SUCCESS != res)
            {
                return __HRESULT_FROM_WIN32(res);
            }

            RegKey toDelete{ toDeleteRaw };
            res = ::RegDeleteTreeW(toDelete.get(), nullptr);
            if (ERROR_SUCCESS != res)
                return __HRESULT_FROM_WIN32(res);
        }

        res = ::RegDeleteKeyW(HKEY_LOCAL_MACHINE, regKeyPath);
        if (ERROR_SUCCESS != res)
            return __HRESULT_FROM_WIN32(res);

        return S_OK;
    }

    HRESULT RemoveProgId(_In_ const comhost::clsid_map_entry &entry)
    {
        if (entry.progid.empty())
            return S_OK;

        HRESULT hr;

        WCHAR regKeyPath[1024];
        ::swprintf_s(regKeyPath, ProgIDKeyFmt, entry.progid.c_str());

        // Remove ProgID key
        RETURN_IF_FAILED(RemoveRegistryKey(regKeyPath));

        return S_OK;
    }

    HRESULT RemoveClsid(_In_ const comhost::clsid_map_entry &entry)
    {
        HRESULT hr;

        LPOLESTR clsidAsStrRaw;
        RETURN_IF_FAILED(::StringFromCLSID(entry.clsid, &clsidAsStrRaw));

        OleStr clsidAsStr{ clsidAsStrRaw };

        WCHAR regKeyPath[1024];
        ::swprintf_s(regKeyPath, ClsidKeyFmt, clsidAsStr.get());

        // Remove CLSID key
        RETURN_IF_FAILED(RemoveRegistryKey(regKeyPath));
        RETURN_IF_FAILED(RemoveProgId(entry));

        return S_OK;
    }

    HRESULT RegisterProgId(_In_ const comhost::clsid_map_entry &entry, _In_z_ LPOLESTR clsidAsStr)
    {
        assert(!entry.progid.empty() && clsidAsStr != nullptr);

        WCHAR regKeyProgIdPath[1024];
        ::swprintf_s(regKeyProgIdPath, ProgIDKeyFmt, entry.progid.c_str());

        HKEY regKeyRaw;
        DWORD disp;
        LSTATUS res = ::RegCreateKeyExW(
            HKEY_LOCAL_MACHINE,
            regKeyProgIdPath,
            0,
            REG_NONE,
            REG_OPTION_NON_VOLATILE,
            (KEY_READ | KEY_WRITE),
            nullptr,
            &regKeyRaw,
            &disp);
        if (res != ERROR_SUCCESS)
            return __HRESULT_FROM_WIN32(res);

        RegKey regKey{ regKeyRaw };

        // Set the default value for the ProgID to be the type name
        // This value is only used for user consumption and has no
        // functional impact.
        res = ::RegSetValueExW(
            regKey.get(),
            nullptr,
            0,
            REG_SZ,
            reinterpret_cast<const BYTE*>(entry.type.c_str()),
            static_cast<DWORD>(sizeof(entry.type.size() + 1) * sizeof(entry.type[0])));
        if (res != ERROR_SUCCESS)
            return __HRESULT_FROM_WIN32(res);

        WCHAR regKeyProgIdClsidPath[ARRAYSIZE(regKeyProgIdPath) * 2];
        ::swprintf_s(regKeyProgIdClsidPath, L"%s\\CLSID", regKeyProgIdPath);

        HKEY regProgIdClsidRaw;
        res = ::RegCreateKeyExW(
            HKEY_LOCAL_MACHINE,
            regKeyProgIdClsidPath,
            0,
            REG_NONE,
            REG_OPTION_NON_VOLATILE,
            (KEY_READ | KEY_WRITE),
            nullptr,
            &regProgIdClsidRaw,
            &disp);
        if (res != ERROR_SUCCESS)
            return __HRESULT_FROM_WIN32(res);

        regKey.reset(regProgIdClsidRaw);

        // The value for the key is the CLSID
        res = ::RegSetValueExW(
            regKey.get(),
            nullptr,
            0,
            REG_SZ,
            reinterpret_cast<const BYTE*>(clsidAsStr),
            static_cast<DWORD>(::wcslen(clsidAsStr) + 1) * sizeof(clsidAsStr[0]));
        if (res != ERROR_SUCCESS)
            return __HRESULT_FROM_WIN32(res);

        return S_OK;
    }

    HRESULT RegisterClsid(_In_ const comhost::clsid_map_entry &entry, _In_opt_z_ const WCHAR *threadingModel)
    {
        HRESULT hr;

        // Remove the CLSID in case it exists and has undesirable settings
        RETURN_IF_FAILED(RemoveClsid(entry));

        LPOLESTR clsidAsStrRaw;
        RETURN_IF_FAILED(::StringFromCLSID(entry.clsid, &clsidAsStrRaw));

        OleStr clsidAsStr{ clsidAsStrRaw };

        WCHAR regKeyClsidPath[1024];
        ::swprintf_s(regKeyClsidPath, ClsidKeyFmt, clsidAsStr.get());

        HKEY regKeyRaw;
        DWORD disp;
        LSTATUS res = ::RegCreateKeyExW(
            HKEY_LOCAL_MACHINE,
            regKeyClsidPath,
            0,
            REG_NONE,
            REG_OPTION_NON_VOLATILE,
            (KEY_READ | KEY_WRITE),
            nullptr,
            &regKeyRaw,
            &disp);
        if (res != ERROR_SUCCESS)
            return __HRESULT_FROM_WIN32(res);

        RegKey regKey{ regKeyRaw };

        // Set the default value for all COM host servers
        const WCHAR defServerName[] = _X("CoreCLR COMHost Server");
        res = ::RegSetValueExW(
            regKey.get(),
            nullptr,
            0,
            REG_SZ,
            reinterpret_cast<const BYTE*>(defServerName),
            static_cast<DWORD>(sizeof(defServerName) * sizeof(defServerName[0])));
        if (res != ERROR_SUCCESS)
            return __HRESULT_FROM_WIN32(res);

        WCHAR regKeyServerPath[ARRAYSIZE(regKeyClsidPath) * 2];
        ::swprintf_s(regKeyServerPath, L"%s\\InProcServer32", regKeyClsidPath);

        HKEY regServerKeyRaw;
        res = ::RegCreateKeyExW(
            HKEY_LOCAL_MACHINE,
            regKeyServerPath,
            0,
            REG_NONE,
            REG_OPTION_NON_VOLATILE,
            (KEY_READ | KEY_WRITE),
            nullptr,
            &regServerKeyRaw,
            &disp);
        if (res != ERROR_SUCCESS)
            return __HRESULT_FROM_WIN32(res);

        regKey.reset(regServerKeyRaw);

        HMODULE mod;
        if (FALSE == ::GetModuleHandleExW(
            (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT),
            reinterpret_cast<LPCWSTR>(&RegisterClsid),
            &mod))
        {
            return HRESULT_FROM_WIN32(::GetLastError());
        }

        pal::string_t modPath;
        if (!pal::get_own_module_path(&modPath))
            return E_UNEXPECTED;

        // The default value for the key is the path to the DLL
        res = ::RegSetValueExW(
            regKey.get(),
            nullptr,
            0,
            REG_SZ,
            reinterpret_cast<const BYTE*>(modPath.data()),
            static_cast<DWORD>(modPath.size() + 1) * sizeof(modPath[0]));
        if (res != ERROR_SUCCESS)
            return __HRESULT_FROM_WIN32(res);

        // Set the threading model if provided
        if (threadingModel != nullptr)
        {
            res = ::RegSetValueExW(
                regKey.get(),
                _X("ThreadingModel"),
                0,
                REG_SZ,
                reinterpret_cast<const BYTE*>(threadingModel),
                static_cast<DWORD>(::wcslen(threadingModel) + 1) * sizeof(threadingModel[0]));
            if (res != ERROR_SUCCESS)
                return __HRESULT_FROM_WIN32(res);
        }

        // Check if a Prog ID is defined
        if (!entry.progid.empty())
        {
            // Register the ProgID in the CLSID key
            WCHAR regKeyProgIdPath[ARRAYSIZE(regKeyClsidPath) * 2];
            ::swprintf_s(regKeyProgIdPath, L"%s\\ProgID", regKeyClsidPath);

            HKEY regProgIdKeyRaw;
            res = ::RegCreateKeyExW(
                HKEY_LOCAL_MACHINE,
                regKeyProgIdPath,
                0,
                REG_NONE,
                REG_OPTION_NON_VOLATILE,
                (KEY_READ | KEY_WRITE),
                nullptr,
                &regProgIdKeyRaw,
                &disp);
            if (res != ERROR_SUCCESS)
                return __HRESULT_FROM_WIN32(res);

            regKey.reset(regProgIdKeyRaw);

            // The default value for the key is the ProgID
            res = ::RegSetValueExW(
                regKey.get(),
                nullptr,
                0,
                REG_SZ,
                reinterpret_cast<const BYTE*>(entry.progid.c_str()),
                static_cast<DWORD>(entry.progid.size() + 1) * sizeof(entry.progid[0]));
            if (res != ERROR_SUCCESS)
                return __HRESULT_FROM_WIN32(res);

            RETURN_IF_FAILED(RegisterProgId(entry, clsidAsStr.get()));
        }

        return S_OK;
    }
}

COM_API HRESULT STDMETHODCALLTYPE DllRegisterServer(void)
{
    // Step 0: Initialize logging
    trace::setup();
    reset_redirected_error_writer();
    error_writer_scope_t writer_scope(redirected_error_writer);

    // Step 1: Get CLSID mapping
    clsid_map map;
    RETURN_HRESULT_IF_EXCEPT(map = comhost::get_clsid_map());

    trace::info(_X("Registering %d CLSIDs"), (int)map.size());

    HRESULT hr;
    pal::string_t app_path;
    com_delegate_fn reg;
    RETURN_IF_FAILED(get_com_delegate(hostfxr_delegate_type::hdt_com_register, &app_path, &reg));

    com_activation_context cxt
    {
        GUID_NULL,
        GUID_NULL,  // Must be GUID_NULL
        app_path.c_str(),
        nullptr,
        nullptr,
        nullptr     // Must be nullptr
    };

    // Step 2: Register each CLSID
    for (clsid_map::const_reference p : map)
    {
        // Register the CLSID in registry
        RETURN_IF_FAILED(RegisterClsid(p.second, _X("Both")));

        // Call user-defined register function
        cxt.class_id = p.first;
        cxt.assembly_name = p.second.assembly.c_str();
        cxt.type_name = p.second.type.c_str();
        RETURN_IF_FAILED(reg(&cxt));
    }

    return S_OK;
}

COM_API HRESULT STDMETHODCALLTYPE DllUnregisterServer(void)
{
    // Step 0: Initialize logging
    trace::setup();
    reset_redirected_error_writer();
    error_writer_scope_t writer_scope(redirected_error_writer);

    // Step 1: Get CLSID mapping
    clsid_map map;
    RETURN_HRESULT_IF_EXCEPT(map = comhost::get_clsid_map());

    trace::info(_X("Unregistering %d CLSIDs"), (int)map.size());

    HRESULT hr;
    pal::string_t app_path;
    com_delegate_fn unreg;
    RETURN_IF_FAILED(get_com_delegate(hostfxr_delegate_type::hdt_com_unregister, &app_path, &unreg));

    com_activation_context cxt
    {
        GUID_NULL,
        GUID_NULL,  // Must be GUID_NULL
        app_path.c_str(),
        nullptr,
        nullptr,
        nullptr     // Must be nullptr
    };

    // Step 2: Unregister each CLSID
    for (clsid_map::const_reference p : map)
    {
        // Call user-defined unregister function
        cxt.class_id = p.first;
        cxt.assembly_name = p.second.assembly.c_str();
        cxt.type_name = p.second.type.c_str();
        RETURN_IF_FAILED(unreg(&cxt));

        // Unregister the CLSID from registry
        RETURN_IF_FAILED(RemoveClsid(p.second));
    }

    return S_OK;
}

#endif // _WIN32


text:
STEN: Statistical Toolbox for Electrical Neuroimaging
=====================================================

[![GitHub issues](https://img.shields.io/github/issues/jknebel/STEN.svg)](https://github.com/jknebel/STEN/issues/)
[![GitHub pull-requests](https://img.shields.io/github/issues-pr/jknebel/STEN.svg)](https://github.com/jknebel/STEN/pulls/)
[![GitHub contributors](https://img.shields.io/github/contributors/jknebel/STEN.svg)](https://GitHub.com/jknebel/STEN/graphs/contributors/)
[![GitHub Commits](https://github-basic-badges.herokuapp.com/commits/jknebel/STEN.svg)](https://github.com/jknebel/STEN/commits/master)
[![GitHub size](https://github-size-badge.herokuapp.com/jknebel/STEN.svg)](https://github.com/jknebel/STEN/archive/master.zip)
[![GitHub HitCount](http://hits.dwyl.io/jknebel/STEN.svg)](http://hits.dwyl.io/jknebel/STEN)

<img align="right" height="290" src="STEN_logo.png">STEN is an open source software toolbox based on Python and R that can be used to compute statistics on several measures of electro- and magnetoencephalographic (EEG and MEG) signals.

STEN enables the sample-point and sensor-wise analysis of EEG and MEG data, but also at the level of Global Field Power (GFP) and distributed neural source estimations (e.g. LAURA or LORETA) by means of parametric and non-parametric (bootstrapping) repeated measure ANOVAs, ANCOVAs and regression analyses. Correction thresholds for temporal and spatial auto-correlations in the data can be individually adjusted.

The currently available STEN toolbox is a beta version. All statistical computations and their outcomes have been extensively validated. However, some minor bugs at the visualization level still need to be fixed.

The most commonly used input data for STEN so far are evoked potential files with header (.eph files), i.e. ASCII files (plain metrics files with header) that have been produced with our partner software [CarTool](https://sites.google.com/site/fbmlab/cartool). STEN produces outputs in the .eph format.

Citation
--------

[![doi.org/10.5281/zenodo.1164151](https://zenodo.org/badge/doi/10.5281/zenodo.1164151.svg)](http://doi.org/10.5281/zenodo.1164151)

If you used the STEN toolbox in your project, please cite as: Knebel, Jean-François, & Notter, Michael Philipp. (2018, February 1). STEN 2.0: Statistical Toolbox for Electrical Neuroimaging. *Zenodo*. [https://doi.org/10.5281/zenodo.1164151](https://doi.org/10.5281/zenodo.1164151).

Additionally, add the following sentence in the Acknowledgments section:

*The STEN toolbox (https://doi.org/10.5281/zenodo.1164151 has been programmed by Jean-François Knebel and Michael Notter, from the Laboratory for Investigative Neurophysiology (the LINE), Lausanne, Switzerland, and is supported by the Center for Biomedical Imaging (CIBM) of Geneva and Lausanne and by National Center of Competence in Research project "SYNAPSY – The Synaptic Bases of Mental Disease"; project no. 51AU40_125759.*

Installation
------------

The easiest way to install STEN is to use conda to create the necessary python environment to run STEN:

1. If you haven't yet, get conda on your system: https://conda.io/miniconda.html
2. Download the `environment.yml` file from: https://github.com/jknebel/STEN/blob/master/environment.yml
3. Open up a conda terminal (or any other terminal), and create a new conda environment with the following command: `conda env create --name sten --file /path/to/file/environment.yml`

Et voilà, STEN is on your system. Now to run STEN, you first need to activate the right conda environment. So, again, open a conda terminal and run the following command:

- Windows: activate sten
- macOS and Linux: source activate sten

Now that you're in the right environment, start STEN with the following command:

`ipython --c "import sten; sten.gui()"`

License information
-------------------

STEN toolbox is a statistical toolbox for EEG anlysis at scalp, GFP and brain scale using R 2.11 and Enthought based on Cartool software files
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

The full license is in the file ``LICENSE``. The image of the brain in the logo was created with [MRIcroGL])> and the font used is called Ethnocentric Regular, created and licensed by Ray Larabie (http://typodermicfonts.com/).

Acknowledgments
---------------
Gholam Rezaee Mohammad Mehdi (CHUV, Lausanne, Switzerland) and Prof. Stephan Morgenthaler (EPFL, Lausanne, Switzerland) provided substantial advice on statistical issues and the R software. The team of the LINE (www.unil.ch/line) helped and still help by testing STEN and reporting bugs.


text:
/
#define SH_GPIO_11                      (11)           /* Green */
#define SH_GPIO_25                      (25)           /* Yellow */
#define AUTO_CONNECTION_TIMEOUT_COUNT   (50)           /* 5 Sec */

#define CC3200_MDNS_NAME  "CC3200._audio._udp.local"

// Application specific status/error codes
typedef enum{
    // Choosing -0x7D0 to avoid overlap w/ host-driver's error codes
    LAN_CONNECTION_FAILED = -0x7D0,
    INTERNET_CONNECTION_FAILED = LAN_CONNECTION_FAILED - 1,
    DEVICE_NOT_IN_STATION_MODE = INTERNET_CONNECTION_FAILED - 1,

    STATUS_CODE_MAX = -0xBB8
}e_AppStatusCodes;

//*****************************************************************************
//                 GLOBAL VARIABLES -- Start
//*****************************************************************************
extern tUDPSocket g_UdpSock;
extern OsiTaskHandle g_NetworkTask;
extern unsigned char g_loopback;
volatile unsigned long  g_ulStatus = 0;//SimpleLink Status
unsigned long  g_uiIpAddress = 0; //Device IP address
unsigned char  g_ucConnectionSSID[SSID_LEN_MAX+1]; //Connection SSID
unsigned char  g_ucConnectionBSSID[BSSID_LEN_MAX]; //Connection BSSID

//*****************************************************************************
//                 GLOBAL VARIABLES -- End
//*****************************************************************************

//*****************************************************************************
//
//! mDNS_Task function
//!
//! \param  None
//!
//! \return None
//!
//*****************************************************************************
void mDNS_Task()
{
    int lRetValmDNS;
    unsigned int pAddr;
    unsigned long usPort;
    unsigned short     ulTextLen = 200;
    char cText[201];

    //UnRegister mDNS Service if done Previously
    lRetValmDNS = sl_NetAppMDNSUnRegisterService((signed char *)CC3200_MDNS_NAME,
                              strlen(CC3200_MDNS_NAME));

    while(1)
    {
        lRetValmDNS = 1;

        //Read mDNS service.
        while(lRetValmDNS)
        {
            ulTextLen = 200;
            lRetValmDNS = sl_NetAppDnsGetHostByService((signed char *) \
                                    CC3200_MDNS_NAME,
                                    strlen((const char *)CC3200_MDNS_NAME),
                                    SL_AF_INET,(unsigned long *)&pAddr,&usPort,
                                    &ulTextLen,(signed char *)&cText[0]);
        }
        if(lRetValmDNS == 0 && (pAddr!=INVALID_CLIENT_ADDRESS) && \
                                                 (pAddr!=g_uiIpAddress))
        {
             //Speaker Detected - Add Client
             g_UdpSock.Client.sin_family = AF_INET;
             g_UdpSock.Client.sin_addr.s_addr = htonl(pAddr);
             g_UdpSock.Client.sin_port = htons(usPort);
             g_UdpSock.iClientLength = sizeof(g_UdpSock.Client);

             g_loopback = 0;

        }

             MAP_UtilsDelay(80*1000*100);
    }
}

//*****************************************************************************
// SimpleLink Asynchronous Event Handlers -- Start
//*****************************************************************************

//*****************************************************************************
//
//! \brief The Function Handles WLAN Events
//!
//! \param[in]  pWlanEvent - Pointer to WLAN Event Info
//!
//! \return None
//!
//*****************************************************************************
void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
{
    if(pWlanEvent == NULL)
    {
        UART_PRINT("Null pointer\n\r");
        LOOP_FOREVER();
    }
    switch(pWlanEvent->Event)
    {
        case SL_WLAN_CONNECT_EVENT:
        {
            SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);

            //
            // Information about the connected AP (like name, MAC etc) will be
            // available in 'slWlanConnectAsyncResponse_t'
            // Applications can use it if required
            //
            //  slWlanConnectAsyncResponse_t *pEventData = NULL;
            // pEventData = &pWlanEvent->EventData.STAandP2PModeWlanConnected;
            //

            // Copy new connection SSID and BSSID to global parameters
            memcpy(g_ucConnectionSSID,pWlanEvent->EventData.
                   STAandP2PModeWlanConnected.ssid_name,
                   pWlanEvent->EventData.STAandP2PModeWlanConnected.ssid_len);
            memcpy(g_ucConnectionBSSID,
                   pWlanEvent->EventData.STAandP2PModeWlanConnected.bssid,
                   SL_BSSID_LENGTH);

            UART_PRINT("[WLAN EVENT] STA Connected to the AP: %s , "
                       "BSSID: %x:%x:%x:%x:%x:%x\n\r",
                      g_ucConnectionSSID,g_ucConnectionBSSID[0],
                      g_ucConnectionBSSID[1],g_ucConnectionBSSID[2],
                      g_ucConnectionBSSID[3],g_ucConnectionBSSID[4],
                      g_ucConnectionBSSID[5]);
        }
        break;

        case SL_WLAN_DISCONNECT_EVENT:
        {
            slWlanConnectAsyncResponse_t*  pEventData = NULL;

            CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);
            CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED);

            pEventData = &pWlanEvent->EventData.STAandP2PModeDisconnected;

            // If the user has initiated 'Disconnect' request,
            //'reason_code' is SL_USER_INITIATED_DISCONNECTION
            if(SL_USER_INITIATED_DISCONNECTION == pEventData->reason_code)
            {
                UART_PRINT("[WLAN EVENT]Device disconnected from the AP: %s, "
                           "BSSID: %x:%x:%x:%x:%x:%x on application's "
                           "request \n\r",
                           g_ucConnectionSSID,g_ucConnectionBSSID[0],
                           g_ucConnectionBSSID[1],g_ucConnectionBSSID[2],
                           g_ucConnectionBSSID[3],g_ucConnectionBSSID[4],
                           g_ucConnectionBSSID[5]);
            }
            else
            {
                UART_PRINT("[WLAN ERROR]Device disconnected from the AP AP: %s, "
                           "BSSID: %x:%x:%x:%x:%x:%x on an ERROR..!! \n\r",
                           g_ucConnectionSSID,g_ucConnectionBSSID[0],
                           g_ucConnectionBSSID[1],g_ucConnectionBSSID[2],
                           g_ucConnectionBSSID[3],g_ucConnectionBSSID[4],
                           g_ucConnectionBSSID[5]);
            }
            memset(g_ucConnectionSSID,0,sizeof(g_ucConnectionSSID));
            memset(g_ucConnectionBSSID,0,sizeof(g_ucConnectionBSSID));
        }
        break;

        default:
        {
            UART_PRINT("[WLAN EVENT] Unexpected event [0x%x]\n\r",
                       pWlanEvent->Event);
        }
        break;
    }
}

//*****************************************************************************
//
//! \brief This function handles network events such as IP acquisition, IP
//!           leased, IP released etc.
//!
//! \param[in]  pNetAppEvent - Pointer to NetApp Event Info
//!
//! \return None
//!
//*****************************************************************************
void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
{
    if(pNetAppEvent == NULL)
    {
        UART_PRINT("Null pointer\n\r");
        LOOP_FOREVER();
    }

    switch(pNetAppEvent->Event)
    {
        case SL_NETAPP_IPV4_IPACQUIRED_EVENT:
        {
            SlIpV4AcquiredAsync_t *pEventData = NULL;

            SET_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED);

            //Ip Acquired Event Data
            pEventData = &pNetAppEvent->EventData.ipAcquiredV4;

            //Gateway IP address
            g_uiIpAddress = pEventData->ip;

            UART_PRINT("[NETAPP EVENT] IP Acquired: IP=%d.%d.%d.%d , "
                       "Gateway=%d.%d.%d.%d\n\r",
            SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,3),
            SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,2),
            SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,1),
            SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,0),
            SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,3),
            SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,2),
            SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,1),
            SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,0));
        }
        break;

        default:
        {
            UART_PRINT("[NETAPP EVENT] Unexpected event [0x%x] \n\r",
                       pNetAppEvent->Event);
        }
        break;
    }
}

//*****************************************************************************
//
//! \brief This function handles HTTP server events
//!
//! \param[in]  pServerEvent - Contains the relevant event information
//! \param[in]    pServerResponse - Should be filled by the user with the
//!                                      relevant response information
//!
//! \return None
//!
//****************************************************************************
void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pHttpEvent,
                                  SlHttpServerResponse_t *pHttpResponse)
{
    // Unused in this application
}

//*****************************************************************************
//
//! \brief This function handles General Events
//!
//! \param[in]     pDevEvent - Pointer to General Event Info
//!
//! \return None
//!
//*****************************************************************************
void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent)
{
    if(pDevEvent == NULL)
    {
        UART_PRINT("Null pointer\n\r");
        LOOP_FOREVER();
    }

    //
    // Most of the general errors are not FATAL are are to be handled
    // appropriately by the application
    //
    UART_PRINT("[GENERAL EVENT] - ID=[%d] Sender=[%d]\n\n",
               pDevEvent->EventData.deviceEvent.status,
               pDevEvent->EventData.deviceEvent.sender);
}

//*****************************************************************************
//
//! This function handles socket events indication
//!
//! \param[in]      pSock - Pointer to Socket Event Info
//!
//! \return None
//!
//*****************************************************************************
void SimpleLinkSockEventHandler(SlSockEvent_t *pSock)
{
    if(pSock == NULL)
    {
        return;
    }

    //
    // This application doesn't work w/ socket - Events are not expected
    //
    switch( pSock->Event )
    {
        case SL_SOCKET_TX_FAILED_EVENT:
        	switch( pSock->socketAsyncEvent.SockTxFailData.status )
            {
                case SL_ECLOSE:
                    /*UART_PRINT("[SOCK ERROR] - close socket (%d) operation "
                                "failed to transmit all queued packets\n\n",
                                    pSock->EventData.sd);*/
                    break;
                default:
                    /*UART_PRINT("[SOCK ERROR] - TX FAILED  :  socket %d , reason "
                                "(%d) \n\n",
                                pSock->EventData.sd, pSock->EventData.status); */
                  break;
            }
            break;

        default:
           /*UART_PRINT("[SOCK EVENT] - Unexpected Event [%x0x]\n\n",pSock->Event);*/
          break;
    }
}

//*****************************************************************************
// SimpleLink Asynchronous Event Handlers -- End
//*****************************************************************************

//*****************************************************************************
//
//! \brief This function initializes the application variables
//!
//! \param    None
//!
//! \return None
//!
//*****************************************************************************
static void InitializeAppVariables()
{
    g_ulStatus = 0;
    g_uiIpAddress = 0;
    memset(g_ucConnectionSSID,0,sizeof(g_ucConnectionSSID));
    memset(g_ucConnectionBSSID,0,sizeof(g_ucConnectionBSSID));
}

#ifdef MULTICAST
//*****************************************************************************
//
//! Add to Multicast Group to receive Audio Stream
//!
//! \param none
//!
//! \return  0 - Success
//!            -1 - Failure

//
//*****************************************************************************
long ReceiveMulticastPacket()
{
    long lRetVal = -1;
    SlSockIpMreq mreq;
    memset(&mreq,0,sizeof(SlSockIpMreq));

    // set interface
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    mreq.imr_multiaddr.s_addr = ADDR_MULTICAST_GROUP;

    // do membership call
    lRetVal = setsockopt(g_UdpSock.iSockDesc, IPPROTO_IP, IP_ADD_MEMBERSHIP,
                             &mreq, sizeof(SlSockIpMreq));
    ASSERT_ON_ERROR(lRetVal);

    return SUCCESS;
}
#endif

//****************************************************************************
//
//! Confgiures the mode in which the device will work
//!
//! \param iMode is the current mode of the device
//!
//!
//! \return   SlWlanMode_t
//!
//
//****************************************************************************
static int ConfigureMode(int iMode)
{
    long   lRetVal = -1;

    lRetVal = sl_WlanSetMode(iMode);
    ASSERT_ON_ERROR(lRetVal);

    /* Restart Network processor */
    lRetVal = sl_Stop(SL_STOP_TIMEOUT);

    // reset status bits
    CLR_STATUS_BIT_ALL(g_ulStatus);

    return sl_Start(NULL,NULL,NULL);
}

//*****************************************************************************
//
//! Connect the Device to Network
//!
//! \param  None
//!
//! \return  0 - Success
//!            -1 - Failure
//!
//*****************************************************************************

long ConnectToNetwork()
{
    long lRetVal = -1;
    unsigned int uiConnectTimeoutCnt =0;

    //Start Simplelink Device
    lRetVal =  sl_Start(NULL,NULL,NULL);
    ASSERT_ON_ERROR(lRetVal);

    if(lRetVal != ROLE_STA)
    {
        if (ROLE_AP == lRetVal)
        {
            // If the device is in AP mode, we need to wait for this event
            // before doing anything
            while(!IS_IP_ACQUIRED(g_ulStatus))
            {
#ifndef SL_PLATFORM_MULTI_THREADED
              _SlNonOsMainLoopTask();
#endif
            }
        }
        //
        // Configure to STA Mode
        //
        lRetVal = ConfigureMode(ROLE_STA);
        if(lRetVal !=ROLE_STA)
        {
            UART_PRINT("Unable to set STA mode...\n\r");
            lRetVal = sl_Stop(SL_STOP_TIMEOUT);
            CLR_STATUS_BIT_ALL(g_ulStatus);
            return DEVICE_NOT_IN_STATION_MODE;
        }
    }

    //waiting for the device to Auto Connect
    while(uiConnectTimeoutCnt<AUTO_CONNECTION_TIMEOUT_COUNT &&
        ((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus))))
    {
        //Turn Green LED On
        GPIO_IF_LedOn(MCU_GREEN_LED_GPIO);
        osi_Sleep(50);
        //Turn Green LED Off
        GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);
        osi_Sleep(50);

        uiConnectTimeoutCnt++;
    }
    //Couldn't connect Using Auto Profile
    if(uiConnectTimeoutCnt==AUTO_CONNECTION_TIMEOUT_COUNT)
    {
        CLR_STATUS_BIT_ALL(g_ulStatus);

        //Turn Green LED On
        GPIO_IF_LedOn(MCU_GREEN_LED_GPIO);

        //Connect Using Smart Config
        lRetVal = SmartConfigConnect();
        ASSERT_ON_ERROR(lRetVal);

        //Waiting for the device to Auto Connect
        while((!IS_CONNECTED(g_ulStatus)) || (!IS_IP_ACQUIRED(g_ulStatus)))
        {
            MAP_UtilsDelay(500);
        }

        //Turn Green LED Off
        GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);
    }

    return SUCCESS;

}
//*****************************************************************************
//
//! Create Socket and Bind to Local IP
//!
//! \param  None
//!
//! \return  0 - Success
//!            -1 - Failure
//
//*****************************************************************************

long CreateUdpServer(tUDPSocket *pSock)
{
    int uiPort = AUDIO_PORT;
    long lRetVal = -1;

    pSock->iSockDesc = socket(AF_INET, SOCK_DGRAM, 0);
    pSock->Server.sin_family = AF_INET;
    pSock->Server.sin_addr.s_addr = htonl(INADDR_ANY);
    pSock->Server.sin_port = htons(uiPort);
    pSock->iServerLength = sizeof(pSock->Server);

    pSock->Client.sin_family = AF_INET;
    pSock->Client.sin_addr.s_addr = htonl(INVALID_CLIENT_ADDRESS);
    pSock->Client.sin_port = htons(uiPort);
    pSock->iClientLength = sizeof(pSock->Client);
    lRetVal = bind(pSock->iSockDesc,(struct sockaddr*)&(pSock->Server),
                 pSock->iServerLength);
    ASSERT_ON_ERROR(lRetVal);

    return SUCCESS;

}

//*****************************************************************************
//
//! Network Task
//!
//! \param  pvParameters - Parameters to the task's entry function
//!
//! \return None
//!
//*****************************************************************************
void Network( void *pvParameters )
{
    long lRetVal = -1;

    //Initialize Global Variable
    InitializeAppVariables();

    //Connect to Network
    lRetVal = ConnectToNetwork();
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to establish connection w/ an AP \n\r");
        LOOP_FOREVER();
    }

    //Cread UDP Socket and Bind to Local IP Address
    lRetVal = CreateUdpServer(&g_UdpSock);
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to Create UDP Server \n\r");
        LOOP_FOREVER();
    }

#ifdef MULTICAST
    //Add to Multicast Group
    lRetVal = ReceiveMulticastPacket();
    if(lRetVal < 0)
    {
        UART_PRINT("Failed to Create UDP Server \n\r");
        LOOP_FOREVER();
    }

    //Delete the Networking Task as Service Discovery is not needed
    osi_TaskDelete(&g_NetworkTask);
#else
    //Discover CC3200 Audio Devices
    mDNS_Task();
#endif

}


text:
The dupReport.rc file (hereafter, the ".rc file") contains configuration information for dupReport to run properly. Many options in the dupReport.rc file have equivalent command line options. **If an option is specified on both the command line and the .rc file, the command line option takes precedence.**

The .rc file contains several "sections", and each section has the form:

```
[section]
option1 = value1
option2 = value2
option3 = value3
```

"[section]" is the name of the section and  the "option" lines below the section name sets various options for that section. For a complete description of how .rc files are formatted, please see this [Wikipedia Article](https://en.wikipedia.org/wiki/INI_file). The important sections in the dupReport.rc file are:

| Section                                                      | Purpose                                                      |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| [[main]](RcFileConfig-Main.md)                               | Sets the main program configuration                          |
| \[\<Email Server>]                                           | Sets the configuration for the POP3, IMAP, and SMTP servers. See the section on [Email Management](RcFileConfig-EmailManagement.md) for more information on the configuration of these sections. |
| [[\<source-destination>]](RcFileConfig-SourceDestination.md) | Sets specific operating configuration options for the backup job named "\<source-destination>" |
| [[apprise]](RcFileConfig-Apprise.md)                         | Set configuration options for the Apprise notification service |
| [[report]](Reporting-ReportSection.md)                       | Sets the default configuration for the reporting system      |
| [[\<report_name>]](Reporting-CustomReportSpec.md)            | Sets specific configuration options for user-defined custom reports |

Click the section name in the table above to see more information on how to configure that section.

(Return to [Main Page](readme.md))


text:
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using PathfinderCharacter;

namespace PathfinderCharacter.Migrations
{
    [DbContext(typeof(PathfinderContext))]
    [Migration("20170504204349_nullables")]
    partial class nullables
    {
        protected override void BuildTargetModel(ModelBuilder modelBuilder)
        {
            modelBuilder
                .HasAnnotation("ProductVersion", "1.1.1")
                .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);

            modelBuilder.Entity("PathfinderCharacter.Core.Models.RawSpell", b =>
                {
                    b.Property<int>("id")
                        .ValueGeneratedOnAdd();

                    b.Property<int?>("SLA_Level");

                    b.Property<bool?>("acid");

                    b.Property<int?>("adept");

                    b.Property<bool?>("air");

                    b.Property<int?>("alchemist");

                    b.Property<int?>("antipaladin");

                    b.Property<string>("area");

                    b.Property<string>("augmented");

                    b.Property<int?>("bard");

                    b.Property<string>("bloodline");

                    b.Property<int?>("bloodrager");

                    b.Property<string>("casting_time");

                    b.Property<bool?>("chaotic");

                    b.Property<int?>("cleric");

                    b.Property<bool?>("cold");

                    b.Property<string>("components");

                    b.Property<bool?>("costly_components");

                    b.Property<bool?>("curse");

                    b.Property<bool?>("darkness");

                    b.Property<bool?>("death");

                    b.Property<string>("deity");

                    b.Property<string>("description");

                    b.Property<string>("description_formated");

                    b.Property<string>("descriptor");

                    b.Property<bool?>("disease");

                    b.Property<bool?>("dismissible");

                    b.Property<bool?>("divine_focus");

                    b.Property<string>("domain");

                    b.Property<bool?>("draconic");

                    b.Property<int?>("druid");

                    b.Property<string>("duration");

                    b.Property<bool?>("earth");

                    b.Property<string>("effect");

                    b.Property<bool?>("electricity");

                    b.Property<bool?>("emotion");

                    b.Property<bool?>("evil");

                    b.Property<bool?>("fear");

                    b.Property<bool?>("fire");

                    b.Property<bool?>("focus");

                    b.Property<bool?>("force");

                    b.Property<string>("full_text");

                    b.Property<bool?>("good");

                    b.Property<string>("haunt_statistics");

                    b.Property<int?>("hunter");

                    b.Property<int?>("inquisitor");

                    b.Property<int?>("investigator");

                    b.Property<bool?>("language_dependent");

                    b.Property<bool?>("lawful");

                    b.Property<bool?>("light");

                    b.Property<string>("linktext");

                    b.Property<int?>("magus");

                    b.Property<bool?>("material");

                    b.Property<int?>("material_costs");

                    b.Property<bool?>("meditative");

                    b.Property<int?>("medium");

                    b.Property<int?>("mesmerist");

                    b.Property<bool?>("mind_affecting");

                    b.Property<bool?>("mythic");

                    b.Property<string>("mythic_text");

                    b.Property<string>("name");

                    b.Property<int?>("occultist");

                    b.Property<int?>("oracle");

                    b.Property<bool?>("pain");

                    b.Property<int?>("paladin");

                    b.Property<string>("patron");

                    b.Property<bool?>("poison");

                    b.Property<int?>("psychic");

                    b.Property<string>("range");

                    b.Property<int?>("ranger");

                    b.Property<bool?>("ruse");

                    b.Property<string>("saving_throw");

                    b.Property<string>("school");

                    b.Property<bool?>("shadow");

                    b.Property<int?>("shaman");

                    b.Property<bool?>("shapeable");

                    b.Property<string>("short_description");

                    b.Property<int?>("skald");

                    b.Property<bool?>("somatic");

                    b.Property<bool?>("sonic");

                    b.Property<int?>("sor");

                    b.Property<string>("source");

                    b.Property<string>("spell_level");

                    b.Property<string>("spell_resistence");

                    b.Property<int?>("spiritualist");

                    b.Property<string>("subschool");

                    b.Property<int?>("summoner");

                    b.Property<string>("targets");

                    b.Property<bool?>("verbal");

                    b.Property<bool?>("water");

                    b.Property<int?>("witch");

                    b.Property<int?>("wiz");

                    b.HasKey("id");

                    b.ToTable("RawSpells");
                });
        }
    }
}


text:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <soap:Body>
    <RemoveCNAMResponse xmlns="http://tempuri.org/">
      <RemoveCNAMResult>
        <responseCode>100</responseCode>
        <responseMessage>Success</responseMessage>
      </RemoveCNAMResult>
    </RemoveCNAMResponse>
  </soap:Body>
</soap:Envelope>


text:
/*

toggle visibility

*/
/*

toggle visibility

*/

function toggle_visibility(expander,collapsible) {
	expandertag = $("[id="+expander+"]");
	tagplus = $(expandertag).children("svg.fa-plus-square");
	console.log(tagplus);
	tagminus = $(expandertag).children("svg.fa-minus-square");
	console.log(tagminus);
	collapsibletag = $("[id="+collapsible+"]");
	ishidden = collapsibletag.hasClass( "hidden" );
	if( ishidden ) {
		collapsibletag.removeClass( "hidden" );
		expandertag.removeClass( "collapsed" );
		expandertag.addClass( "expanded" );
		tagplus.addClass( "hidden" );
		tagminus.removeClass( "hidden" );
	} else {
		collapsibletag.addClass( "hidden" );
		expandertag.removeClass( "expanded" );
		expandertag.addClass( "collapsed" );
		tagplus.removeClass( "hidden" );
		tagminus.addClass( "hidden" );
	}
}

/* http://stackoverflow.com/questions/8579643/simple-jquery-scroll-to-anchor-up-or-down-the-page */
function anchorDoScroll(dest) {
	$('html,body').animate({scrollTop:$('a[name='+dest+']').offset().top},1000);/*,'easeInOutCirc'*/
	console.log("scroll to:"+dest+"->"+$('a[name='+dest+']').offset().top);
}
// FIXME
/*
function anchorFactory() { // put this in document ready
	$("a[href^=#]").click(function(e) {
		e.preventDefault();
		anchorDoScroll($(this).attr('href').substring(1));
	});
}
*/

function compress(data) {
	data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
	return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}

$.fn.serializeObject = function() {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (this.value == 'on')
			this.value = true;
		if (this.value == 'off')
			this.value = false;
		if (o[this.name] !== undefined) {
			if (!o[this.name].push) {
				o[this.name] = [ o[this.name] ];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

function jsonForm(id) {
	// .serializeArray()
	// .serialize()
	return JSON.stringify($(id).serializeObject());
}

function replaceAll(str, find, replace) {
	return str.replace(new RegExp(find, 'g'), replace);
}

function escapeRegExp(string) {
	return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}

function selectedOption(selector) {
	return $(selector+' option:selected').text();
}

function selectedRadioOption(name) {
	return $('input[name='+name+'][type=radio]:checked').val();
}

// http://jsfiddle.net/Marcel/jvJzX/
jQuery.fn.extend({
	inputFocus : function() {
		return this.each(function() {
			if(this.nodeName == 'INPUT') {
				if($(this).attr('type') == 'text') {
					$(this).focus(function() {
						$(this).select().mouseup(function(event) {
							event.preventDefault();
							$(this).unbind("mouseup");
						});
					});
				}
			}
		});
	}
});

// https://asimilia.wordpress.com/2008/12/17/jquery-extend-confusion/
jQuery.fn.extend({
	resetform : function() {
		var form = $(this);
		form.find('input[type][value]').val('');
		form.find('input[type=checkbox]:checked').removeAttr('checked');
		form.find('select option:selected').removeAttr('selected');
	}
});

jQuery.fn.extend({
	// http://stackoverflow.com/questions/556767/limiting-number-of-lines-in-textarea
	// http://stackoverflow.com/questions/5271782/how-to-disable-the-resize-grabber-of-an-html-textarea
	fixTextArea : function() {
		var fixedTextArea = $(this);
		fixedTextArea.css('resize','none');
		fixedTextArea.scroll(function(){
			$(this).css('overflow','hidden');/* for the mozilla browser problem */
			$(this).animate({scrollTop:$(this).outerHeight()});
			while($(this).scrollTop()>0){/* for the copy and paste case */
				var lines=$(this).val().slice(0,-1);
				$(this).val(lines);
			}
			$(this).css('overflow','auto');/* For the mozilla browser problem */
		});
	}
});

/* http://codepen.io/anon/pen/NPZNPq */
function toggleByRadio(group) {
	console.log(group);
	$("[data-group='" + group + "']").addClass("optiontoggle").addClass("hidden");
	$("input[type='radio'][name='" + group + "']").click(function() { adjustByRadio(group); });
	adjustByRadio(group);
}
function toggleByRadioJqueryUIFix(group) {
	$("input[type='radio'][name='" + group + "']").parent().on('change', function(event){ adjustByRadio(group); });
}
function adjustByRadio(group) {
	var V = $("input[type='radio'][name='" + group + "']:checked").val();
	console.log(group+'='+V);
	$("[data-group='" + group + "'][data-value!='" + V + "']").addClass("hidden");
	$("[data-group='" + group + "'][data-value='" + V + "']").removeClass("hidden");
}

/*
<input type="radio" name="radiogroup" value="radiovalue1">value1
<input type="radio" name="radiogroup" value="radiovalue2" selected>value2

value1

value2

*/
function factoryHideByRadio(dataGroup) {
	$("input:radio[name='"+dataGroup+"']").change(function() {
		var dataValue = $(this).val();
		console.log(dataGroup+'='+dataValue);
		$("[data-group='"+dataGroup+"']").hide(); // hide adds "style=display:none"
		$("[data-group='"+dataGroup+"'][data-value='"+dataValue+"']").show(); // show removes "style=display:none"
	})
	// FIXME is called for each radio button in group (last should be initial selected */
	.change() // set initial blocks hidden and selected shown // https://stackoverflow.com/questions/23723005/uncaught-typeerror-cannot-read-property-tolowercase-of-undefined
	;
}


text:
import React from 'react';
import TestUtils from 'react-dom/test-utils';
import Icon from '..';

class Wrapper extends React.Component {
  render() {
    return this.props.children;
  }
}

describe('Icon', () => {
  let icon;
  let iconNode;

  beforeEach(() => {
    icon = TestUtils.renderIntoDocument(
      <Wrapper><Icon type="appstore" className="my-icon-classname" /></Wrapper>
    );
    iconNode = TestUtils.findRenderedDOMComponentWithTag(icon, 'I');
  });

  it('should render to a <i class="xxx"></i>', () => {
    expect(iconNode.tagName).toBe('I');
    expect(iconNode.className).toContain('my-icon-classname');
    expect(iconNode.className).toContain('anticon');
    expect(iconNode.className).toContain('anticon-appstore');
  });
});


text:
<?php
namespace Tzander\PageFactory\Handler;

class LocatingElementHandler
{

    /**
     * @param \Tzander\PageFactory\ElementLocator $locator
     */
    public function __construct(\Tzander\PageFactory\ElementLocator $locator)
    {
        $this->locator = $locator;
    }

    /**
     * @return \PHPUnit_Extensions_Selenium2TestCase_Element
     */
    public function invoke()
    {
        $element = $this->locator->findElement();
        return $element;
    }
}


text:
<?php

/**
 * Class for time management
 */
namespace Codersquad\Pennephp\Time;

/**
 * Class Time
 *
 * @package Codersquad\Pennephp\Time
 * @author Oliver Monneke <oliver@codersquad.de>
 * @version 1.0
 */
class Time extends DateTime
{
    /**
     * @var string
     */
    protected $formatDate = 'h:i:s';
}


text:
using System.Linq;
using HtmlConsole.Css;
using HtmlConsole.Tests.Css.Testing;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace HtmlConsole.Tests.Css
{
    [TestClass]
    public class LengthStyleValueTests
    {
        // The parser is immutable
        private readonly TestingStyleParser _parser = new TestingStyleParser();

        public enum TestEnum
        {
            ValueA,
            ValueB,
            ValueC
        }

        [TestMethod]
        public void TryCreate_PxValue_CreatesCorrectStyleValue()
        {
            var styleValue = LengthStyleValue.TryCreate(
                _parser.TestingGetSyntaxTree("1px", StyleParserMode.StyleValue).Matches.First()
            );

            Assert.AreEqual(1, styleValue.Length);
            Assert.AreEqual(LengthUnit.Px, styleValue.Unit);
        }

        [TestMethod]
        public void TryCreate_EmValue_CreatesCorrectStyleValue()
        {
            var styleValue = LengthStyleValue.TryCreate(
                _parser.TestingGetSyntaxTree("999em", StyleParserMode.StyleValue).Matches.First()
            );

            Assert.AreEqual(999, styleValue.Length);
            Assert.AreEqual(LengthUnit.Em, styleValue.Unit);
        }

        [TestMethod]
        public void TryCreate_DecimalEmValue_CreatesCorrectStyleValue()
        {
            var styleValue = LengthStyleValue.TryCreate(
                _parser.TestingGetSyntaxTree("999.99em", StyleParserMode.StyleValue).Matches.First()
            );

            Assert.AreEqual(999.99m, styleValue.Length);
            Assert.AreEqual(LengthUnit.Em, styleValue.Unit);
        }

        [TestMethod]
        public void TryCreate_Zero_CreatesCorrectStyleValue()
        {
            var styleValue = LengthStyleValue.TryCreate(
                _parser.TestingGetSyntaxTree("0", StyleParserMode.StyleValue).Matches.First()
            );

            Assert.AreEqual(0, styleValue.Length);
            Assert.AreEqual(LengthUnit.None, styleValue.Unit);
        }

        [TestMethod]
        public void TryCreate_NoneZeroWithoutDimension_ReturnsNull()
        {
            var styleValue = LengthStyleValue.TryCreate(
                _parser.TestingGetSyntaxTree("5", StyleParserMode.StyleValue).Matches.First()
            );

            Assert.IsNull(styleValue);
        }

        [TestMethod]
        public void TryCreate_InvalidString_ReturnsNull()
        {
            var styleValue = LengthStyleValue.TryCreate(
                _parser.TestingGetSyntaxTree("sdfadf", StyleParserMode.StyleValue).Matches.First()
            );

            Assert.IsNull(styleValue);
        }
    }
}