text:
import logging

from ryu.base import app_manager
from ryu.controller import event
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ether
from ryu.ofproto import ofproto_v1_0
from ryu.ofproto import ofproto_v1_2
from ryu.ofproto import ofproto_v1_3
from ryu.lib import addrconv
from ryu.lib.dpid import dpid_to_str
from ryu.lib.packet import packet
from ryu.lib.packet import ethernet
from ryu.lib.packet import slow

class EventPacketIn(event.EventBase):
    """a PacketIn event class using except LACP."""
    def __init__(self, msg):
        """initialization."""
        super(EventPacketIn, self).__init__()
        self.msg = msg

class EventSlaveStateChanged(event.EventBase):
    """a event class that notifies the changes of the statuses of the
    slave i/fs."""
    def __init__(self, datapath, port, enabled):
        """initialization."""
        super(EventSlaveStateChanged, self).__init__()
        self.datapath = datapath
        self.port = port
        self.enabled = enabled

class LacpLib(app_manager.RyuApp):
    """LACP exchange library. this works only in a PASSIVE mode."""

    # -------------------------------------------------------------------
    # PUBLIC METHODS
    # -------------------------------------------------------------------
    def __init__(self):
        """initialization."""
        super(LacpLib, self).__init__()
        self.name = 'lacplib'
        self._bonds = []
        self._add_flow = {
            ofproto_v1_0.OFP_VERSION: self._add_flow_v1_0,
            ofproto_v1_2.OFP_VERSION: self._add_flow_v1_2,
            ofproto_v1_3.OFP_VERSION: self._add_flow_v1_2,
        }
        self._set_logger()

    def add(self, dpid, ports):
        """add a setting of a bonding i/f.
        'add' method takes the corresponding args in this order.

        ========= =====================================================
        Attribute Description
        ========= =====================================================
        dpid      datapath id.

        ports     a list of integer values that means the ports face
                  with the slave i/fs.
        ========= =====================================================

        if you want to use multi LAG, call 'add' method more than once.
        """
        assert isinstance(ports, list)
        assert len(ports) >= 2
        ifs = {}
        for port in ports:
            ifs[port] = {'enabled': False, 'timeout': 0}
        bond = {dpid: ifs}
        self._bonds.append(bond)

    # -------------------------------------------------------------------
    # PUBLIC METHODS ( EVENT HANDLERS )
    # -------------------------------------------------------------------
    @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
    def packet_in_handler(self, evt):
        """PacketIn event handler. when the received packet was LACP,
        proceed it. otherwise, send a event."""
        req_pkt = packet.Packet(evt.msg.data)
        if slow.lacp in req_pkt:
            (req_lacp, ) = req_pkt.get_protocols(slow.lacp)
            (req_eth, ) = req_pkt.get_protocols(ethernet.ethernet)
            self._do_lacp(req_lacp, req_eth.src, evt.msg)
        else:
            self.send_event_to_observers(EventPacketIn(evt.msg))

    @set_ev_cls(ofp_event.EventOFPFlowRemoved, MAIN_DISPATCHER)
    def flow_removed_handler(self, evt):
        """FlowRemoved event handler. when the removed flow entry was
        for LACP, set the status of the slave i/f to disabled, and
        send a event."""
        msg = evt.msg
        datapath = msg.datapath
        ofproto = datapath.ofproto
        dpid = datapath.id
        match = msg.match
        if ofproto.OFP_VERSION == ofproto_v1_0.OFP_VERSION:
            port = match.in_port
            dl_type = match.dl_type
        else:
            port = match['in_port']
            dl_type = match['eth_type']
        if ether.ETH_TYPE_SLOW != dl_type:
            return
        self.logger.info(
            "SW=%s PORT=%d LACP exchange timeout has occurred.",
            dpid_to_str(dpid), port)
        self._set_slave_enabled(dpid, port, False)
        self._set_slave_timeout(dpid, port, 0)
        self.send_event_to_observers(
            EventSlaveStateChanged(datapath, port, False))

    # -------------------------------------------------------------------
    # PRIVATE METHODS ( RELATED TO LACP )
    # -------------------------------------------------------------------
    def _do_lacp(self, req_lacp, src, msg):
        """packet-in process when the received packet is LACP."""
        datapath = msg.datapath
        dpid = datapath.id
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser
        if ofproto.OFP_VERSION == ofproto_v1_0.OFP_VERSION:
            port = msg.in_port
        else:
            port = msg.match['in_port']

        self.logger.info("SW=%s PORT=%d LACP received.",
                         dpid_to_str(dpid), port)
        self.logger.debug(str(req_lacp))

        # when LACP arrived at disabled port, update the status of
        # the slave i/f to enabled, and send a event.
        if not self._get_slave_enabled(dpid, port):
            self.logger.info(
                "SW=%s PORT=%d the slave i/f has just been up.",
                dpid_to_str(dpid), port)
            self._set_slave_enabled(dpid, port, True)
            self.send_event_to_observers(
                EventSlaveStateChanged(datapath, port, True))

        # set the idle_timeout time using the actor state of the
        # received packet.
        if req_lacp.LACP_STATE_SHORT_TIMEOUT == \
           req_lacp.actor_state_timeout:
            idle_timeout = req_lacp.SHORT_TIMEOUT_TIME
        else:
            idle_timeout = req_lacp.LONG_TIMEOUT_TIME

        # when the timeout time has changed, update the timeout time of
        # the slave i/f and re-enter a flow entry for the packet from
        # the slave i/f with idle_timeout.
        if idle_timeout != self._get_slave_timeout(dpid, port):
            self.logger.info(
                "SW=%s PORT=%d the timeout time has changed.",
                dpid_to_str(dpid), port)
            self._set_slave_timeout(dpid, port, idle_timeout)
            func = self._add_flow.get(ofproto.OFP_VERSION)
            assert func
            func(src, port, idle_timeout, datapath)

        # create a response packet.
        res_pkt = self._create_response(datapath, port, req_lacp)

        # packet-out the response packet.
        out_port = ofproto.OFPP_IN_PORT
        actions = [parser.OFPActionOutput(out_port)]
        out = datapath.ofproto_parser.OFPPacketOut(
            datapath=datapath, buffer_id=ofproto.OFP_NO_BUFFER,
            data=res_pkt.data, in_port=port, actions=actions)
        datapath.send_msg(out)

    def _create_response(self, datapath, port, req):
        """create a packet including LACP."""
        src = datapath.ports[port].hw_addr
        res_ether = ethernet.ethernet(
            slow.SLOW_PROTOCOL_MULTICAST, src, ether.ETH_TYPE_SLOW)
        res_lacp = self._create_lacp(datapath, port, req)
        res_pkt = packet.Packet()
        res_pkt.add_protocol(res_ether)
        res_pkt.add_protocol(res_lacp)
        res_pkt.serialize()
        return res_pkt

    def _create_lacp(self, datapath, port, req):
        """create a LACP packet."""
        actor_system = datapath.ports[datapath.ofproto.OFPP_LOCAL].hw_addr
        res = slow.lacp(
            actor_system_priority=0xffff,
            actor_system=actor_system,
            actor_key=req.actor_key,
            actor_port_priority=0xff,
            actor_port=port,
            actor_state_activity=req.LACP_STATE_PASSIVE,
            actor_state_timeout=req.actor_state_timeout,
            actor_state_aggregation=req.actor_state_aggregation,
            actor_state_synchronization=req.actor_state_synchronization,
            actor_state_collecting=req.actor_state_collecting,
            actor_state_distributing=req.actor_state_distributing,
            actor_state_defaulted=req.LACP_STATE_OPERATIONAL_PARTNER,
            actor_state_expired=req.LACP_STATE_NOT_EXPIRED,
            partner_system_priority=req.actor_system_priority,
            partner_system=req.actor_system,
            partner_key=req.actor_key,
            partner_port_priority=req.actor_port_priority,
            partner_port=req.actor_port,
            partner_state_activity=req.actor_state_activity,
            partner_state_timeout=req.actor_state_timeout,
            partner_state_aggregation=req.actor_state_aggregation,
            partner_state_synchronization=req.actor_state_synchronization,
            partner_state_collecting=req.actor_state_collecting,
            partner_state_distributing=req.actor_state_distributing,
            partner_state_defaulted=req.actor_state_defaulted,
            partner_state_expired=req.actor_state_expired,
            collector_max_delay=0)
        self.logger.info("SW=%s PORT=%d LACP sent.",
                         dpid_to_str(datapath.id), port)
        self.logger.debug(str(res))
        return res

    def _get_slave_enabled(self, dpid, port):
        """get whether a slave i/f at some port of some datapath is
        enable or not."""
        slave = self._get_slave(dpid, port)
        if slave:
            return slave['enabled']
        else:
            return False

    def _set_slave_enabled(self, dpid, port, enabled):
        """set whether a slave i/f at some port of some datapath is
        enable or not."""
        slave = self._get_slave(dpid, port)
        if slave:
            slave['enabled'] = enabled

    def _get_slave_timeout(self, dpid, port):
        """get the timeout time at some port of some datapath."""
        slave = self._get_slave(dpid, port)
        if slave:
            return slave['timeout']
        else:
            return 0

    def _set_slave_timeout(self, dpid, port, timeout):
        """set the timeout time at some port of some datapath."""
        slave = self._get_slave(dpid, port)
        if slave:
            slave['timeout'] = timeout

    def _get_slave(self, dpid, port):
        """get slave i/f at some port of some datapath."""
        result = None
        for bond in self._bonds:
            if dpid in bond:
                if port in bond[dpid]:
                    result = bond[dpid][port]
                    break
        return result

    # -------------------------------------------------------------------
    # PRIVATE METHODS ( RELATED TO OPEN FLOW PROTOCOL )
    # -------------------------------------------------------------------
    def _add_flow_v1_0(self, src, port, timeout, datapath):
        """enter a flow entry for the packet from the slave i/f
        with idle_timeout. for OpenFlow ver1.0."""
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        match = parser.OFPMatch(
            in_port=port, dl_src=addrconv.mac.text_to_bin(src),
            dl_type=ether.ETH_TYPE_SLOW)
        actions = [parser.OFPActionOutput(
            ofproto.OFPP_CONTROLLER, 65535)]
        mod = parser.OFPFlowMod(
            datapath=datapath, match=match, cookie=0,
            command=ofproto.OFPFC_ADD, idle_timeout=timeout,
            priority=65535, flags=ofproto.OFPFF_SEND_FLOW_REM,
            actions=actions)
        datapath.send_msg(mod)

    def _add_flow_v1_2(self, src, port, timeout, datapath):
        """enter a flow entry for the packet from the slave i/f
        with idle_timeout. for OpenFlow ver1.2 and ver1.3."""
        ofproto = datapath.ofproto
        parser = datapath.ofproto_parser

        match = parser.OFPMatch(
            in_port=port, eth_src=src, eth_type=ether.ETH_TYPE_SLOW)
        actions = [parser.OFPActionOutput(
            ofproto.OFPP_CONTROLLER, ofproto.OFPCML_MAX)]
        inst = [parser.OFPInstructionActions(
            ofproto.OFPIT_APPLY_ACTIONS, actions)]
        mod = parser.OFPFlowMod(
            datapath=datapath, command=ofproto.OFPFC_ADD,
            idle_timeout=timeout, priority=65535,
            flags=ofproto.OFPFF_SEND_FLOW_REM, match=match,
            instructions=inst)
        datapath.send_msg(mod)

    # -------------------------------------------------------------------
    # PRIVATE METHODS ( OTHERS )
    # -------------------------------------------------------------------
    def _set_logger(self):
        """change log format."""
        self.logger.propagate = False
        hdl = logging.StreamHandler()
        fmt_str = '[LACP][%(levelname)s] %(message)s'
        hdl.setFormatter(logging.Formatter(fmt_str))
        self.logger.addHandler(hdl)


text:
<?xml version="1.0" ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<link rel="stylesheet" type="text/css" href="../../../scineplex.css">
<title></title>
<link rel="stylesheet" href="../../../Active.css" type="text/css" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rev="made" href="mailto:" />

NAME

VERSION

DESCRIPTION

THE UTILITIES

curry_method

curry_chain

merge_col

mixin_installer

like

AUTHOR

COPYRIGHT AND LICENSE

NAME

Sub::Exporter::Util - utilities to make Sub::Exporter easier

VERSION

version 0.984

DESCRIPTION

This module provides a number of utility functions for performing common or useful operations when setting up a Sub::Exporter configuration. All of the utilites may be exported, but none are by default.

THE UTILITIES

curry_method

  exports => {
    some_method => curry_method,
  }

This utility returns a generator which will produce an invocant-curried version of a method. In other words, it will export a method call with the exporting class built in as the invocant.

A module importing the code some the above example might do this:

  use Some::Module qw(some_method);

  my $x = some_method;

This would be equivalent to:

  use Some::Module;

  my $x = Some::Module->some_method;

If Some::Module is subclassed and the subclass's import method is called to import some_method, the subclass will be curried in as the invocant.

If an argument is provided for curry_method it is used as the name of the curried method to export. This means you could export a Widget constructor like this:

  exports => { widget => curry_method('new') }

This utility may also be called as curry_class, for backwards compatibility.

curry_chain

curry_chain behaves like "curry_method", but is meant for generating exports that will call several methods in succession.

  exports => {
    reticulate => curry_chain([
      new => gather_data => analyze => [ detail => 100 ] => results
    ]),
  }

If imported from Spliner, calling the reticulate routine will be equivalent to:

  Splinter->new->gather_data->analyze(detail => 100)->results;

If any method returns something on which methods may not be called, the routine croaks.

The arguments to curry_chain form an optlist. The names are methods to be called and the arguments, if given, are arrayrefs to be dereferenced and passed as arguments to those methods. curry_chain returns a generator like those expected by Sub::Exporter.

Achtung! at present, there is no way to pass arguments from the generated routine to the method calls. This will probably be solved in future revisions by allowing the opt list's values to be subroutines that will be called with the generated routine's stack.

merge_col

  exports => {
    merge_col(defaults => {
      twiddle => \'_twiddle_gen',
      tweak   => \&_tweak_gen,
    }),
  }

This utility wraps the given generator in one that will merge the named collection into its args before calling it. This means that you can support a "default" collector in multipe exports without writing the code each time.

You can specify as many pairs of collection names and generators as you like.

mixin_installer

  use Sub::Exporter -setup => {
    installer => Sub::Exporter::Util::mixin_installer,
    exports   => [ qw(foo bar baz) ],
  };

This utility returns an installer that will install into a superclass and adjust the ISA importing class to include the newly generated superclass.

If the target of importing is an object, the hierarchy is reversed: the new class will be ISA the object's class, and the object will be reblessed.

Prerequisites: This utility requires that Package::Generator be installed.

like

It's a collector that adds imports for anything like given regex.

If you provide this configuration:

  exports    => [ qw(igrep imap islurp exhausted) ],
  collectors => { -like => Sub::Exporter::Util::like },

A user may import from your module like this:

  use Your::Iterator -like => qr/^i/; # imports igre, imap, islurp

or

  use Your::Iterator -like => [ qr/^i/ => { -prefix => 'your_' } ];

The group-like prefix and suffix arguments are respected; other arguments are passed on to the generators for matching exports.

AUTHOR

Ricardo Signes <rjbs@cpan.org>

COPYRIGHT AND LICENSE

This software is copyright (c) 2007 by Ricardo Signes.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.

redpajama_set_name: RedPajamaGithub


text:
const BackgroundPropertyFormatter = require('./BackgroundPropertyFormatter');
const BorderRadiusPropertyFormatter = require('./BorderRadiusPropertyFormatter');
const CommaSeparatedListPropertyFormatter = require('./CommaSeparatedListPropertyFormatter');
const FlexPropertyFormatter = require('./FlexPropertyFormatter');
const FontPropertyFormatter = require('./FontPropertyFormatter');
const TrblPropertyFormatter = require('./TrblPropertyFormatter');
const UnorderedOptionalListPropertyFormatter = require('./UnorderedOptionalListPropertyFormatter');

module.exports = {
  BackgroundPropertyFormatter,
  BorderRadiusPropertyFormatter,
  CommaSeparatedListPropertyFormatter,
  FlexPropertyFormatter,
  FontPropertyFormatter,
  TrblPropertyFormatter,
  UnorderedOptionalListPropertyFormatter,
};


text: © {{ site.time | date: '%Y' }} {{ site.owner.name }}. Powered by Jekyll, leonids theme made with


text:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Audio;
using System.Collections;
using System.Collections.Generic;
using Zeltex.Util;
using System.IO;

namespace Zeltex.Guis.Maker
{
    /// <summary>
    /// Handles making blocks
    /// Meta data saved in alphabetical order as blocks use their id to get meta from the VoxelTileGenerator
    /// </summary>
    public class MusicMaker : MakerGui
    {
        #region Variables
        //[Header("SoundMaker")]  // idk why i have 3 references.. lol
        public List<AudioClip> Data;
        //AudioClip
        #endregion

        #region Data
        public static SoundMaker Get()
        {
            return GameObject.Find("GameManager").GetComponent<MapMaker>().MySoundMaker;
        }
        /// <summary>
        /// Clear the  all the stored data
        /// </summary>
        public override void Clear()
        {
            //MyNames.Clear();
            Data.Clear();
        }

        /// <summary>
        /// Returns the selected script
        /// </summary>
        public AudioClip GetSelectedAudio()
        {
            return Data[MyIndexController.SelectedIndex];
        }

        public AudioClip GetAudio(string Name)
        {
            /*for (int i = 0; i < MyNames.Count; i++)
            {
                if (Name == MyNames[i])
                {
                    return Data[i];
                }
            }*/
            return null;
        }
        #endregion

        #region IndexController
        /// <summary>
        /// Load Gui with Input
        /// Only gets called if index is updated
        /// </summary>
        public override void OnUpdatedIndex(int NewIndex)
        {
            base.OnUpdatedIndex(NewIndex);
            Debug.Log("Updating Index in Polygon Maker: " + NewIndex);
            GetInput("NameInput").text = GetSelectedName();
            //RefreshViewer();
            //GenerateSolidity();
            //UpdateStatistics();
            //CancelInvokes();
        }

		/// <summary>
		/// Add a new model to our list
		/// </summary>
		protected override void AddData()
		{
            //AudioClip MyClip = new AudioClip();
			//DataManager.Get().AddSound(DataManagerFolder, MyClip);
            //Data.Add(MyClip);
            //MyNames.Add("Sound " + MyNames.Count);
            //base.OnAdd(NewIndex);
        }

		/// <summary>
		/// When an index is removed
		/// </summary>
		/// <param name="NewIndex"></param>
		protected override void RemovedData(int Index)
		{
			//DataManager.Get().RemoveSound(DataManagerFolder, Index);
        }

        #endregion

        #region Files
        /// <summary>
        /// Set file paths!
        /// </summary>
        protected override void SetFilePaths()
        {
            DataManagerFolder = "Music";
        }

            #endregion

        #region UI
            /// <summary>
            /// Used for generically updating input buttons
            /// </summary>
        public override void UseInput(InputField MyInputField)
        {
            if (MyInputField.name == "NameInput")
            {
                MyInputField.text = Rename(MyInputField.text);
            }
        }

        /// <summary>
        /// Used for generically updating buttons
        /// </summary>
        public override void UseInput(Button MyButton)
        {
            if (MyButton.name == "ImportButton")
            {
                StartCoroutine(ImportRoutine());
            }
            else if (MyButton.name == "PlayButton")
            {
                GetComponent<AudioSource>().clip = (GetSelectedAudio());
                GetComponent<AudioSource>().Play();
            }
            else if (MyButton.name == "StopButton")
            {
                GetComponent<AudioSource>().Stop();
            }
        }
        IEnumerator ImportRoutine()
        {
            /*Dropdown MyDropdown = GetDropdown("ImportDropdown");
            string FileName = FileUtil.GetFolderPath("MusicImports/") + MyDropdown.options[MyDropdown.value].text + "." + FileExtension;
            WWW MyLoader = new WWW("file://" + FileName);
            yield return MyLoader;
            if (string.IsNullOrEmpty(MyLoader.error) == false)
            {
                Debug.LogError(MyLoader.error);
            }
            else
            {
                Data[GetSelectedIndex()] = MyLoader.audioClip;
            }*/
            yield break;
        }
        /// <summary>
        /// Fill the drop downs with data
        /// </summary>
        public override void FillDropdown(Dropdown MyDropdown)
        {
            /*List<string> MyDropdownNames = new List<string>();
            if (MyDropdown.name == "ImportDropdown")
            {
                List<string> MyFiles = FileUtil.GetFilesOfType(FileUtil.GetFolderPath("MusicImports/"), FileExtension);
                for (int i = 0; i < MyFiles.Count; i++)
                {
                    MyDropdownNames.Add(Path.GetFileNameWithoutExtension(MyFiles[i]));
                }
                FillDropDownWithList(MyDropdown, MyDropdownNames);
            }*/
        }
        #endregion
    }
}
/// <summary>
/// Load all the polygonal models!
/// </summary>
/* public override void LoadAll()
 {
     base.LoadAll();
     Clear();
     //StartCoroutine(LoadRoutine());
 }
 public IEnumerator LoadRoutine()
 {
     yield break;
     base.LoadAll();
     Clear();
     string MyFolderPath = FileUtil.GetFolderPath(FolderName);
     List<string> MyFiles = FileUtil.GetFilesOfType(MyFolderPath, FileExtension);
     Debug.Log("Loading all Musics: " + MyFolderPath + ":" + MyFiles.Count);
     MyFiles = FileUtil.SortAlphabetically(MyFiles);
     for (int i = 0; i < MyFiles.Count; i++)
     {
         Debug.Log(i + " Loading Music: " + MyFiles[i]);
         MyNames.Add(Path.GetFileNameWithoutExtension(MyFiles[i]));
         WWW MyLoader = new WWW("file://" + MyFiles[i]);
         yield return MyLoader;
         Data.Add(MyLoader.audioClip);
     }
 }
 /// <summary>
 /// Save all the polygonal models!
 /// </summary>
 public override void SaveAll()
 {
     Debug.Log("Saving Sounds to: " + GetFilePath());
     for (int i = 0; i < Data.Count; i++)
     {
         string MyFilePath = GetFilePath() + MyNames[i] + "." + FileExtension;
         Debug.Log("Saving Music " + i + " to: " + MyFilePath);
         SavWav.Save(MyFilePath, Data[i]);
     }
 }*/


text:
package eu.qualimaster.common.shedding;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * A dummy shedder that does no shadding.
 *
 * @author Holger Eichelberger
 */
public class NoShedder extends LoadShedder<Object> {

    public static final NoShedder INSTANCE = new NoShedder();
    private static final long serialVersionUID = 9191712027878070454L;

    /**
     * Creates the shedder.
     */
    private NoShedder() {
        super(DefaultLoadShedders.NO_SHEDDING, Object.class);
    }

    @Override
    protected boolean isEnabledImpl(Object tuple) {
        return true;
    }

    @Override
    public void configure(ILoadShedderConfigurer configurer) {
    }

    @Override
    public Map<ILoadSheddingParameter, Serializable> getConfiguration() {
        return new HashMap<ILoadSheddingParameter, Serializable>();
    }

}


text:
package io.cloudslang.worker.management.services;

import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;

/**
 * User: wahnonm
 * Date: 12/08/13
 * Time: 10:10
 */
public class WorkerThreadFactoryTest {

    List<Long> endedThreads ;

    @Before
    public void setUp(){
        endedThreads = Collections.synchronizedList(new ArrayList<Long>());
    }

    public class simpleCmd implements Runnable{

        private Long id;

        public simpleCmd(Long id){
           this.id = id;
        }

        @Override
        public void run() {
            System.out.println("Just Msg");
            endedThreads.add(id);
        }
    }

    @Test
    public void testNewThread() throws Exception {
        Assert.assertTrue(endedThreads.isEmpty());

        WorkerThreadFactory factory = new WorkerThreadFactory("worker1");
        Thread thread1 = factory.newThread(new simpleCmd(1L));
        Thread thread2 = factory.newThread(new simpleCmd(2L));

        Assert.assertNotSame(thread1.getName(),thread2.getName());

        thread1.start();
        thread2.start();

        while(thread1.isAlive() || thread2.isAlive()){}

        Assert.assertEquals(2,endedThreads.size());
        Assert.assertEquals(3,endedThreads.get(0)+endedThreads.get(1));
    }
}


text:
#include "config.h"
#include "TextEncodingRegistry.h"

#include "TextCodecICU.h"
#include "TextCodecLatin1.h"
#include "TextCodecUserDefined.h"
#include "TextCodecUTF16.h"
#include "TextCodecUTF8.h"
#include "TextEncoding.h"
#include <mutex>
#include <wtf/ASCIICType.h>
#include <wtf/HashMap.h>
#include <wtf/HashSet.h>
#include <wtf/MainThread.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/StdLibExtras.h>
#include <wtf/StringExtras.h>

#if PLATFORM(COCOA)
#include "WebCoreSystemInterface.h"
#endif

#if PLATFORM(MAC)
#include "TextCodecMac.h"
#endif

#include <wtf/CurrentTime.h>
#include <wtf/text/CString.h>

using namespace WTF;

namespace WebCore {

const size_t maxEncodingNameLength = 63;

// Hash for all-ASCII strings that does case folding.
struct TextEncodingNameHash {
    static bool equal(const char* s1, const char* s2)
    {
        char c1;
        char c2;
        do {
            c1 = *s1++;
            c2 = *s2++;
            if (toASCIILower(c1) != toASCIILower(c2))
                return false;
        } while (c1 && c2);
        return !c1 && !c2;
    }

    // This algorithm is the one-at-a-time hash from:
    // http://burtleburtle.net/bob/hash/hashfaq.html
    // http://burtleburtle.net/bob/hash/doobs.html
    static unsigned hash(const char* s)
    {
        unsigned h = WTF::stringHashingStartValue;
        for (;;) {
            char c = *s++;
            if (!c) {
                h += (h << 3);
                h ^= (h >> 11);
                h += (h << 15);
                return h;
            }
            h += toASCIILower(c);
            h += (h << 10);
            h ^= (h >> 6);
        }
    }

    static const bool safeToCompareToEmptyOrDeleted = false;
};

struct TextCodecFactory {
    NewTextCodecFunction function;
    const void* additionalData;
    TextCodecFactory(NewTextCodecFunction f = 0, const void* d = 0) : function(f), additionalData(d) { }
};

typedef HashMap<const char*, const char*, TextEncodingNameHash> TextEncodingNameMap;
typedef HashMap<const char*, TextCodecFactory> TextCodecMap;

static std::mutex& encodingRegistryMutex()
{
    // We don't have to construct this mutex in a thread safe way because this function
    // is called on the main thread for any page before it is used in worker threads.
    static NeverDestroyed<std::mutex> mutex;

    return mutex;
}

static TextEncodingNameMap* textEncodingNameMap;
static TextCodecMap* textCodecMap;
static bool didExtendTextCodecMaps;
static HashSet<const char*>* japaneseEncodings;
static HashSet<const char*>* nonBackslashEncodings;

static const char* const textEncodingNameBlacklist[] = { "UTF-7" };

#if ERROR_DISABLED

static inline void checkExistingName(const char*, const char*) { }

#else

static void checkExistingName(const char* alias, const char* atomicName)
{
    const char* oldAtomicName = textEncodingNameMap->get(alias);
    if (!oldAtomicName)
        return;
    if (oldAtomicName == atomicName)
        return;
    // Keep the warning silent about one case where we know this will happen.
    if (strcmp(alias, "ISO-8859-8-I") == 0
            && strcmp(oldAtomicName, "ISO-8859-8-I") == 0
            && strcasecmp(atomicName, "iso-8859-8") == 0)
        return;
    LOG_ERROR("alias %s maps to %s already, but someone is trying to make it map to %s", alias, oldAtomicName, atomicName);
}

#endif

static bool isUndesiredAlias(const char* alias)
{
    // Reject aliases with version numbers that are supported by some back-ends (such as "ISO_2022,locale=ja,version=0" in ICU).
    for (const char* p = alias; *p; ++p) {
        if (*p == ',')
            return true;
    }
    // 8859_1 is known to (at least) ICU, but other browsers don't support this name - and having it caused a compatibility
    // problem, see bug 43554.
    if (0 == strcmp(alias, "8859_1"))
        return true;
    return false;
}

static void addToTextEncodingNameMap(const char* alias, const char* name)
{
    ASSERT(strlen(alias) <= maxEncodingNameLength);
    if (isUndesiredAlias(alias))
        return;
    const char* atomicName = textEncodingNameMap->get(name);
    ASSERT(strcmp(alias, name) == 0 || atomicName);
    if (!atomicName)
        atomicName = name;
    checkExistingName(alias, atomicName);
    textEncodingNameMap->add(alias, atomicName);
}

static void addToTextCodecMap(const char* name, NewTextCodecFunction function, const void* additionalData)
{
    const char* atomicName = textEncodingNameMap->get(name);
    ASSERT(atomicName);
    textCodecMap->add(atomicName, TextCodecFactory(function, additionalData));
}

static void pruneBlacklistedCodecs()
{
    for (size_t i = 0; i < WTF_ARRAY_LENGTH(textEncodingNameBlacklist); ++i) {
        const char* atomicName = textEncodingNameMap->get(textEncodingNameBlacklist[i]);
        if (!atomicName)
            continue;

        Vector<const char*> names;
        TextEncodingNameMap::const_iterator it = textEncodingNameMap->begin();
        TextEncodingNameMap::const_iterator end = textEncodingNameMap->end();
        for (; it != end; ++it) {
            if (it->value == atomicName)
                names.append(it->key);
        }

        size_t length = names.size();
        for (size_t j = 0; j < length; ++j)
            textEncodingNameMap->remove(names[j]);

        textCodecMap->remove(atomicName);
    }
}

static void buildBaseTextCodecMaps()
{
    ASSERT(isMainThread());
    ASSERT(!textCodecMap);
    ASSERT(!textEncodingNameMap);

    textCodecMap = new TextCodecMap;
    textEncodingNameMap = new TextEncodingNameMap;

    TextCodecLatin1::registerEncodingNames(addToTextEncodingNameMap);
    TextCodecLatin1::registerCodecs(addToTextCodecMap);

    TextCodecUTF8::registerEncodingNames(addToTextEncodingNameMap);
    TextCodecUTF8::registerCodecs(addToTextCodecMap);

    TextCodecUTF16::registerEncodingNames(addToTextEncodingNameMap);
    TextCodecUTF16::registerCodecs(addToTextCodecMap);

    TextCodecUserDefined::registerEncodingNames(addToTextEncodingNameMap);
    TextCodecUserDefined::registerCodecs(addToTextCodecMap);
}

static void addEncodingName(HashSet<const char*>* set, const char* name)
{
    // We must not use atomicCanonicalTextEncodingName() because this function is called in it.
    const char* atomicName = textEncodingNameMap->get(name);
    if (atomicName)
        set->add(atomicName);
}

static void buildQuirksSets()
{
    // FIXME: Having isJapaneseEncoding() and shouldShowBackslashAsCurrencySymbolIn()
    // and initializing the sets for them in TextEncodingRegistry.cpp look strange.

    ASSERT(!japaneseEncodings);
    ASSERT(!nonBackslashEncodings);

    japaneseEncodings = new HashSet<const char*>;
    addEncodingName(japaneseEncodings, "EUC-JP");
    addEncodingName(japaneseEncodings, "ISO-2022-JP");
    addEncodingName(japaneseEncodings, "ISO-2022-JP-1");
    addEncodingName(japaneseEncodings, "ISO-2022-JP-2");
    addEncodingName(japaneseEncodings, "ISO-2022-JP-3");
    addEncodingName(japaneseEncodings, "JIS_C6226-1978");
    addEncodingName(japaneseEncodings, "JIS_X0201");
    addEncodingName(japaneseEncodings, "JIS_X0208-1983");
    addEncodingName(japaneseEncodings, "JIS_X0208-1990");
    addEncodingName(japaneseEncodings, "JIS_X0212-1990");
    addEncodingName(japaneseEncodings, "Shift_JIS");
    addEncodingName(japaneseEncodings, "Shift_JIS_X0213-2000");
    addEncodingName(japaneseEncodings, "cp932");
    addEncodingName(japaneseEncodings, "x-mac-japanese");

    nonBackslashEncodings = new HashSet<const char*>;
    // The text encodings below treat backslash as a currency symbol for IE compatibility.
    // See http://blogs.msdn.com/michkap/archive/2005/09/17/469941.aspx for more information.
    addEncodingName(nonBackslashEncodings, "x-mac-japanese");
    addEncodingName(nonBackslashEncodings, "ISO-2022-JP");
    addEncodingName(nonBackslashEncodings, "EUC-JP");
    // Shift_JIS_X0213-2000 is not the same encoding as Shift_JIS on Mac. We need to register both of them.
    addEncodingName(nonBackslashEncodings, "Shift_JIS");
    addEncodingName(nonBackslashEncodings, "Shift_JIS_X0213-2000");
}

bool isJapaneseEncoding(const char* canonicalEncodingName)
{
    return canonicalEncodingName && japaneseEncodings && japaneseEncodings->contains(canonicalEncodingName);
}

bool shouldShowBackslashAsCurrencySymbolIn(const char* canonicalEncodingName)
{
    return canonicalEncodingName && nonBackslashEncodings && nonBackslashEncodings->contains(canonicalEncodingName);
}

static void extendTextCodecMaps()
{
    TextCodecICU::registerEncodingNames(addToTextEncodingNameMap);
    TextCodecICU::registerCodecs(addToTextCodecMap);

#if PLATFORM(MAC)
    TextCodecMac::registerEncodingNames(addToTextEncodingNameMap);
    TextCodecMac::registerCodecs(addToTextCodecMap);
#endif

    pruneBlacklistedCodecs();
    buildQuirksSets();
}

PassOwnPtr<TextCodec> newTextCodec(const TextEncoding& encoding)
{
    std::lock_guard<std::mutex> lock(encodingRegistryMutex());

    ASSERT(textCodecMap);
    TextCodecFactory factory = textCodecMap->get(encoding.name());
    ASSERT(factory.function);
    return factory.function(encoding, factory.additionalData);
}

const char* atomicCanonicalTextEncodingName(const char* name)
{
    if (!name || !name[0])
        return nullptr;

    if (!textEncodingNameMap)
        buildBaseTextCodecMaps();

    std::lock_guard<std::mutex> lock(encodingRegistryMutex());

    if (const char* atomicName = textEncodingNameMap->get(name))
        return atomicName;
    if (didExtendTextCodecMaps)
        return nullptr;

    extendTextCodecMaps();
    didExtendTextCodecMaps = true;
    return textEncodingNameMap->get(name);
}

template <typename CharacterType>
const char* atomicCanonicalTextEncodingName(const CharacterType* characters, size_t length)
{
    char buffer[maxEncodingNameLength + 1];
    size_t j = 0;
    for (size_t i = 0; i < length; ++i) {
        CharacterType c = characters[i];
        if (j == maxEncodingNameLength)
            return 0;
        buffer[j++] = c;
    }
    buffer[j] = 0;
    return atomicCanonicalTextEncodingName(buffer);
}

const char* atomicCanonicalTextEncodingName(const String& alias)
{
    if (!alias.length())
        return nullptr;

    if (alias.is8Bit())
        return atomicCanonicalTextEncodingName(alias.characters8(), alias.length());

    return atomicCanonicalTextEncodingName(alias.characters16(), alias.length());
}

bool noExtendedTextEncodingNameUsed()
{
    // If the calling thread did not use extended encoding names, it is fine for it to use a stale false value.
    return !didExtendTextCodecMaps;
}

#if PLATFORM(COCOA)
String defaultTextEncodingNameForSystemLanguage()
{
    String systemEncodingName = CFStringConvertEncodingToIANACharSetName(wkGetWebDefaultCFStringEncoding());

    // CFStringConvertEncodingToIANACharSetName() returns cp949 for kTextEncodingDOSKorean AKA "extended EUC-KR" AKA windows-949.
    // ICU uses this name for a different encoding, so we need to change the name to a value that actually gives us windows-949.
    // In addition, this value must match what is used in Safari, see <rdar://problem/5579292>.
    // On some OS versions, the result is CP949 (uppercase).
    if (equalIgnoringCase(systemEncodingName, "cp949"))
        systemEncodingName = "ks_c_5601-1987";
    return systemEncodingName;
}
#endif

#ifndef NDEBUG
void dumpTextEncodingNameMap()
{
    unsigned size = textEncodingNameMap->size();
    fprintf(stderr, "Dumping %u entries in WebCore::textEncodingNameMap...\n", size);

    std::lock_guard<std::mutex> lock(encodingRegistryMutex());

    TextEncodingNameMap::const_iterator it = textEncodingNameMap->begin();
    TextEncodingNameMap::const_iterator end = textEncodingNameMap->end();
    for (; it != end; ++it)
        fprintf(stderr, "'%s' => '%s'\n", it->key, it->value);
}
#endif

} // namespace WebCore


text:
package manager

import (
	"fmt"

	group_types "github.com/docker/infrakit/pkg/plugin/group/types"
	"github.com/docker/infrakit/pkg/spi/group"
	"github.com/docker/infrakit/pkg/spi/instance"
	"github.com/docker/infrakit/pkg/types"
)

// Groups returns a map of *scoped* group controllers by ID of the group.
func (m *manager) Groups() (map[group.ID]group.Plugin, error) {
	groups := map[group.ID]group.Plugin{
		group.ID("groups"): m,
	}
	all, err := m.Plugin.InspectGroups()
	if err != nil {
		return groups, nil
	}
	for _, spec := range all {
		gid := spec.ID
		groups[gid] = m
	}

	log.Debug("Groups", "map", groups, "V", debugV3)
	return groups, nil
}

func (m *manager) loadGroupSpec(id group.ID) (group.Spec, error) {
	// load the config
	config := globalSpec{}

	// load the latest version -- assumption here is that it's been persisted already.
	err := config.load(m.Options.SpecStore)
	if err != nil {
		log.Warn("Error loading config", "err", err)
		return group.Spec{}, err
	}
	return config.getGroupSpec(id)
}

func (m *manager) updateConfig(spec group.Spec) error {
	log.Debug("Updating config", "spec", spec)
	m.lock.Lock()
	defer m.lock.Unlock()

	// Always read and then update with the current value.  Assumes the user's input
	// is always authoritative.
	stored := globalSpec{}
	err := stored.load(m.Options.SpecStore)
	if err != nil {
		return err
	}

	log.Debug("Saving updated config", "global", stored, "spec", spec)
	defer log.Debug("Saved snapshot", "global", stored, "spec", spec)

	stored.updateGroupSpec(spec, m.Options.Group)
	return stored.store(m.Options.SpecStore)
}

func (m *manager) removeConfig(id group.ID) error {
	log.Debug("Removing config", "groupID", id)
	m.lock.Lock()
	defer m.lock.Unlock()

	// Always read and then update with the current value.  Assumes the user's input
	// is always authoritative.
	stored := globalSpec{}
	err := stored.load(m.Options.SpecStore)
	if err != nil {
		return err
	}
	log.Debug("Deleting config", "global", stored, "id", id)
	defer log.Debug("Saved snapshot", "global", stored, "id", id)

	stored.removeGroup(id)
	return stored.store(m.Options.SpecStore)
}

func (m *manager) queue(name string, work func() (retry bool, err error)) <-chan struct{} {
	wait := make(chan struct{})
	m.backendOps <- backendOp{
		name: name,
		operation: func() (bool, error) {
			retry, err := work()
			close(wait)
			return retry, err
		},
	}
	return wait
}

// This implements/ overrides the Group Plugin interface to support single group-only operations
func (m *manager) CommitGroup(grp group.Spec, pretend bool) (resp string, err error) {

	if is, errLeader := m.IsLeader(); errLeader != nil || !is {
		err = errNotLeader
		return
	}

	retry := true
	<-m.queue("commit",
		func() (bool, error) {
			log.Debug("Manager CommitGroup", "spec", grp, "V", debugV)

			// We first update the user's desired state first
			if !pretend {
				if updateErr := m.updateConfig(grp); updateErr != nil {
					log.Error("Error updating", "err", updateErr)
					resp = "Cannot update spec. Abort"
					err = updateErr
					return false, updateErr
				}
			}

			resp, err = m.Plugin.CommitGroup(grp, pretend)
			return retry, err
		})

	return
}

// Serialized describe group
func (m *manager) DescribeGroup(id group.ID) (desc group.Description, err error) {

	if is, errLeader := m.IsLeader(); errLeader != nil || !is {
		err = errNotLeader
		return
	}

	retry := false
	<-m.queue("describe",
		func() (bool, error) {
			log.Debug("Manager DescribeGroup", "id", id, "V", debugV)
			desc, err = m.Plugin.DescribeGroup(id)
			return retry, err
		})
	return
}

// This implements/ overrides the Group Plugin interface to support single group-only operations
func (m *manager) DestroyGroup(id group.ID) (err error) {

	if is, errLeader := m.IsLeader(); errLeader != nil || !is {
		err = errNotLeader
		return
	}

	retry := false
	<-m.queue("destroy",
		func() (bool, error) {
			log.Debug("Manager DestroyGroup", "groupID", id, "V", debugV)

			// We first update the user's desired state first
			if removeErr := m.removeConfig(id); removeErr != nil {
				log.Warn("Error updating/ remove", "err", removeErr)
				err = removeErr
				return retry, err
			}

			err = m.Plugin.DestroyGroup(id)
			return retry, err
		})
	return
}

// This implements/ overrides the Group Plugin interface to support single group-only operations
func (m *manager) FreeGroup(id group.ID) (err error) {

	if is, errLeader := m.IsLeader(); errLeader != nil || !is {
		err = errNotLeader
		return
	}

	retry := false
	<-m.queue("free",
		func() (bool, error) {
			log.Debug("Manager FreeGroup", "groupID", id, "V", debugV)

			// We first update the user's desired state first
			if removeErr := m.removeConfig(id); removeErr != nil {
				log.Warn("Error updating / remove", "err", removeErr)
				err = removeErr
				return retry, err
			}

			err = m.Plugin.FreeGroup(id)
			return retry, err
		})

	return
}

// This implements/ overrides the Group Plugin interface to support single group-only operations
func (m *manager) DestroyInstances(id group.ID, instances []instance.ID) (err error) {

	if is, errLeader := m.IsLeader(); errLeader != nil || !is {
		err = errNotLeader
		return
	}

	retry := false
	<-m.queue("destroyInstances",
		func() (bool, error) {
			log.Debug("Manager DestroyInstances", "groupID", id, "instances", instances, "V", debugV)

			err = m.Plugin.DestroyInstances(id, instances)
			return retry, err
		})

	return
}

// This implements/ overrides the Group Plugin interface to support single group-only operations
func (m *manager) SetSize(id group.ID, size int) error {

	if is, errLeader := m.IsLeader(); errLeader != nil || !is {
		return errNotLeader
	}

	spec, err := m.loadGroupSpec(id)
	if err != nil {
		return err
	}
	parsed, err := group_types.ParseProperties(spec)
	if err != nil {
		return err
	}
	if s := len(parsed.Allocation.LogicalIDs); s > 0 {
		return fmt.Errorf("cannot set size when logical ids are explicitly set")
	}
	parsed.Allocation.Size = uint(size)
	spec.Properties = types.AnyValueMust(parsed)
	_, err = m.CommitGroup(spec, false)
	return err
}

// This implements/ overrides the Group Plugin interface to support single group-only operations
func (m *manager) Size(id group.ID) (size int, err error) {

	if is, errLeader := m.IsLeader(); errLeader != nil || !is {
		err = errNotLeader
		return
	}

	spec, err := m.loadGroupSpec(id)
	if err != nil {
		return 0, err
	}
	parsed, err := group_types.ParseProperties(spec)
	if err != nil {
		return 0, err
	}
	if s := len(parsed.Allocation.LogicalIDs); s > 0 {
		size = s
		return size, nil
	}
	return int(parsed.Allocation.Size), nil
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<faceted-project>
	<runtime name="MyEclipse JEE 6.0 Runtime" />
	<fixed facet="wst.jsdt.web" />
	<installed facet="java" version="1.6" />
	<installed facet="jst.web" version="3.0" />
	<installed facet="wst.jsdt.web" version="1.0" />
</faceted-project>


text:
local isfallbackscoreType

function isFallbackScoreType()
	return isfallbackscoreType
end

-- Grabs the currently selected rate as a string in the form of "r.rx"
function getCurRateString()
	return string.format("%.1f",getCurRateValue()).."x"
end

function getCurRateDisplayString()
	return string.format("%.1f",getCurRateValue()).."xMusic"
end

-- Grab only the scores for the current rate
function getCurRateScores()
	return getCurChart().Scores[getCurRateString()]
end

-- Functions involving grabbing highscores under varying circumstances
function getAlternativeBestRateScores(scoreType)
	local all = getCurChart().Scores
	local rates = tableKeys(all)
	local o
	table.sort(rates)

	for i=#rates, 1, -1 do
		o = getRateScoresBestScore(all[rates[i]], scoreType, "Grade_Failed")
		if o then return o end
	end

	o = getRateScoresBestScore(getCurRateScores(), scoreType, nil)
	if o then return o end

	for i=#rates, 1, -1 do
		o = getRateScoresBestScore(all[rates[i]], scoreType, nil)
		if o then return o end
	end
	return nil
end

function getRateScoresBestScore(RateScores, scoreType, filter)	-- filter by grade
	isfallbackscoreType = false
	if not RateScores then return nil end
	local n, o = -math.huge
	for k,v in pairs(RateScores) do
		if v.Metadata.Grade ~= filter then
			v = v.ScoreTable[scoreType]
			if v and v.Percent > n then
				n, o = v.Percent, k
			end
		end
	end

	if not o then
		for k,v in pairs(RateScores) do
		if v.Metadata.Grade ~= filter then
			v = v.ScoreTable[getfallbackscoreType()]
			if v and v.Percent > n then
				n, o = v.Percent, k
			end
			if not o then
				return nil
			end
		end
	end
		isfallbackscoreType = true
	end
	return RateScores[o]
end

function getCurRateScoresBestScore(scoreType)	-- not used atm
	isfallbackscoreType = false
	local RateScores = getCurRateScores()

	if not RateScores then return nil end
	local n, o = -math.huge
	for k,v in pairs(RateScores) do
		v = v.ScoreTable[scoreType]
		if v and v.Percent > n then
			n, o = v.Percent, k
		end
	end

	if not o then
		for k,v in pairs(RateScores) do
			v = v.ScoreTable[getfallbackscoreType()]
			if v and v.Percent > n then
				n, o = v.Percent, k
			end
			if not o then
				isfallbackscoreType = nil
				return nil
			end
		end
		isfallbackscoreType = true
	end
	return RateScores[o]
end

-- for making the music wheel show all grades... one day... the dream...
local gradeTiers = {
	Grade_Tier01 = 0,
	Grade_Tier02 = 1,
	Grade_Tier03 = 2,
	Grade_Tier04 = 3,
	Grade_Tier05 = 4,
	Grade_Tier06 = 5,
	Grade_Tier07 = 6,
	Grade_Tier08 = 7,
	Grade_Tier09 = 8,
	Grade_Tier10 = 9,
	Grade_Tier11 = 10,
	Grade_Tier12 = 11,
	Grade_Tier13 = 12,
	Grade_Tier14 = 13,
	Grade_Tier15 = 14,
	Grade_Tier16 = 15,
	Grade_Tier17 = 16,
	Grade_Tier18 = 17,
	Grade_Tier19 = 18,
	Grade_Tier20 = 19,
	Grade_Failed = 20
}

function getBestGradeBySong(song)
	if not song then return nil end		-- shouldn't ever be the case

	local highest = 21
	local indexScore
	local grade = "Grade_None"
	local temp = 0
	local scoretable
	local profile = GetPlayerOrMachineProfile(PLAYER_1)
	local steps4k = song:GetStepsByStepsType('StepsType_Dance_Single')

	for ix=1,#steps4k do
		scoretable = profile:GetHighScoreList(song,steps4k[ix]):GetHighScores()
		for i=1, #scoretable do
			indexScore = scoretable[i]
			temp = gradeTiers[indexScore:GetGrade()] or 21
			if temp <= highest and isScoreValid(PLAYER_1,steps4k[ix],indexScore) then
				grade = getScoreGrade(indexScore)
				highest = temp
			end
		end
	end
	return grade
end


text:
"use strict";

var ReactDOMSelection = require("./ReactDOMSelection");

var containsNode = require("./containsNode");
var getActiveElement = require("./getActiveElement");

function isInDocument(node) {
  return containsNode(document.documentElement, node);
}

/**
 * @ReactInputSelection: React input selection module. Based on Selection.js,
 * but modified to be suitable for react and has a couple of bug fixes (doesn't
 * assume buttons have range selections allowed).
 * Input selection module for React.
 */
var ReactInputSelection = {

  hasSelectionCapabilities: function(elem) {
    return elem && (
      (elem.nodeName === 'INPUT' && elem.type === 'text') ||
      elem.nodeName === 'TEXTAREA' ||
      elem.contentEditable === 'true'
    );
  },

  getSelectionInformation: function() {
    var focusedElem = getActiveElement();
    return {
      focusedElem: focusedElem,
      selectionRange:
          ReactInputSelection.hasSelectionCapabilities(focusedElem) ?
          ReactInputSelection.getSelection(focusedElem) :
          null
    };
  },

  /**
   * @restoreSelection: If any selection information was potentially lost,
   * restore it. This is useful when performing operations that could remove dom
   * nodes and place them back in, resulting in focus being lost.
   */
  restoreSelection: function(priorSelectionInformation) {
    var curFocusedElem = getActiveElement();
    var priorFocusedElem = priorSelectionInformation.focusedElem;
    var priorSelectionRange = priorSelectionInformation.selectionRange;
    if (curFocusedElem !== priorFocusedElem &&
        isInDocument(priorFocusedElem)) {
      if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) {
        ReactInputSelection.setSelection(
          priorFocusedElem,
          priorSelectionRange
        );
      }
      priorFocusedElem.focus();
    }
  },

  /**
   * @getSelection: Gets the selection bounds of a focused textarea, input or
   * contentEditable node.
   * -@input: Look up selection bounds of this input
   * -@return {start: selectionStart, end: selectionEnd}
   */
  getSelection: function(input) {
    var selection;

    if ('selectionStart' in input) {
      // Modern browser with input or textarea.
      selection = {
        start: input.selectionStart,
        end: input.selectionEnd
      };
    } else if (document.selection && input.nodeName === 'INPUT') {
      // IE8 input.
      var range = document.selection.createRange();
      // There can only be one selection per document in IE, so it must
      // be in our element.
      if (range.parentElement() === input) {
        selection = {
          start: -range.moveStart('character', -input.value.length),
          end: -range.moveEnd('character', -input.value.length)
        };
      }
    } else {
      // Content editable or old IE textarea.
      selection = ReactDOMSelection.getOffsets(input);
    }

    return selection || {start: 0, end: 0};
  },

  /**
   * @setSelection: Sets the selection bounds of a textarea or input and focuses
   * the input.
   * -@input     Set selection bounds of this input or textarea
   * -@offsets   Object of same form that is returned from get*
   */
  setSelection: function(input, offsets) {
    var start = offsets.start;
    var end = offsets.end;
    if (typeof end === 'undefined') {
      end = start;
    }

    if ('selectionStart' in input) {
      input.selectionStart = start;
      input.selectionEnd = Math.min(end, input.value.length);
    } else if (document.selection && input.nodeName === 'INPUT') {
      var range = input.createTextRange();
      range.collapse(true);
      range.moveStart('character', start);
      range.moveEnd('character', end - start);
      range.select();
    } else {
      ReactDOMSelection.setOffsets(input, offsets);
    }
  }
};

module.exports = ReactInputSelection;


text:
package org.apache.storm.hdfs.blobstore;

import org.apache.storm.Config;
import org.apache.storm.blobstore.BlobStoreFile;
import org.apache.storm.utils.ObjectReader;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * HDFS blob store impl.
 */
public class HdfsBlobStoreImpl {
    private static final Logger LOG = LoggerFactory.getLogger(HdfsBlobStoreImpl.class);

    private static final long FULL_CLEANUP_FREQ = 60 * 60 * 1000l;
    private static final int BUCKETS = 1024;
    private static final String BLOBSTORE_DATA = "data";

    private Timer timer;

    public class KeyInHashDirIterator implements Iterator<String> {
        private int currentBucket = 0;
        private Iterator<String> it = null;
        private String next = null;

        public KeyInHashDirIterator() throws IOException {
            primeNext();
        }

        private void primeNext() throws IOException {
            while (it == null && currentBucket < BUCKETS) {
                String name = String.valueOf(currentBucket);
                Path dir = new Path(_fullPath, name);
                try {
                    it = listKeys(dir);
                } catch (FileNotFoundException e) {
                    it = null;
                }
                if (it == null || !it.hasNext()) {
                    it = null;
                    currentBucket++;
                } else {
                    next = it.next();
                }
            }
        }

        @Override
        public boolean hasNext() {
            return next != null;
        }

        @Override
        public String next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            String current = next;
            next = null;
            if (it != null) {
                if (!it.hasNext()) {
                    it = null;
                    currentBucket++;
                    try {
                        primeNext();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                } else {
                    next = it.next();
                }
            }
            return current;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Delete Not Supported");
        }
    }

    private Path _fullPath;
    private FileSystem _fs;
    private Configuration _hadoopConf;

    // blobstore directory is private!
    final public static FsPermission BLOBSTORE_DIR_PERMISSION =
            FsPermission.createImmutable((short) 0700); // rwx--------

    public HdfsBlobStoreImpl(Path path, Map<String, Object> conf) throws IOException {
        this(path, conf, new Configuration());
    }

    public HdfsBlobStoreImpl(Path path, Map<String, Object> conf,
                             Configuration hconf) throws IOException {
        LOG.info("Blob store based in {}", path);
        _fullPath = path;
        _hadoopConf = hconf;
        _fs = path.getFileSystem(_hadoopConf);

        if (!_fs.exists(_fullPath)) {
            FsPermission perms = new FsPermission(BLOBSTORE_DIR_PERMISSION);
            boolean success = _fs.mkdirs(_fullPath, perms);
            if (!success) {
                throw new IOException("Error creating blobstore directory: " + _fullPath);
            }
        }

        Object shouldCleanup = conf.get(Config.BLOBSTORE_CLEANUP_ENABLE);
        if (ObjectReader.getBoolean(shouldCleanup, false)) {
            LOG.debug("Starting hdfs blobstore cleaner");
            TimerTask cleanup = new TimerTask() {
                @Override
                public void run() {
                    try {
                        fullCleanup(FULL_CLEANUP_FREQ);
                    } catch (IOException e) {
                        LOG.error("Error trying to cleanup", e);
                    }
                }
            };
            timer = new Timer("HdfsBlobStore cleanup thread", true);
            timer.scheduleAtFixedRate(cleanup, 0, FULL_CLEANUP_FREQ);
        }
    }

    /**
     * @return all keys that are available for reading.
     * @throws IOException on any error.
     */
    public Iterator<String> listKeys() throws IOException {
        return new KeyInHashDirIterator();
    }

    /**
     * Get an input stream for reading a part.
     *
     * @param key the key of the part to read.
     * @return the where to read the data from.
     * @throws IOException on any error
     */
    public BlobStoreFile read(String key) throws IOException {
        return new HdfsBlobStoreFile(getKeyDir(key), BLOBSTORE_DATA, _hadoopConf);
    }

    /**
     * Get an object tied to writing the data.
     *
     * @param key the key of the part to write to.
     * @param create whether the file needs to be new or not.
     * @return an object that can be used to both write to, but also commit/cancel the operation.
     * @throws IOException on any error
     */
    public BlobStoreFile write(String key, boolean create) throws IOException {
        return new HdfsBlobStoreFile(getKeyDir(key), true, create, _hadoopConf);
    }

    /**
     * Check if the key exists in the blob store.
     *
     * @param key the key to check for
     * @return true if it exists else false.
     */
    public boolean exists(String key) {
        Path dir = getKeyDir(key);
        boolean res = false;
        try {
            _fs = dir.getFileSystem(_hadoopConf);
            res = _fs.exists(dir);
        } catch (IOException e) {
            LOG.warn("Exception checking for exists on: " + key);
        }
        return res;
    }

    /**
     * Delete a key from the blob store
     *
     * @param key the key to delete
     * @throws IOException on any error
     */
    public void deleteKey(String key) throws IOException {
        Path keyDir = getKeyDir(key);
        HdfsBlobStoreFile pf = new HdfsBlobStoreFile(keyDir, BLOBSTORE_DATA,
                _hadoopConf);
        pf.delete();
        delete(keyDir);
    }

    protected Path getKeyDir(String key) {
        String hash = String.valueOf(Math.abs((long) key.hashCode()) % BUCKETS);
        Path hashDir = new Path(_fullPath, hash);

        Path ret = new Path(hashDir, key);
        LOG.debug("{} Looking for {} in {}", new Object[]{_fullPath, key, hash});
        return ret;
    }

    public void fullCleanup(long age) throws IOException {
        long cleanUpIfBefore = System.currentTimeMillis() - age;
        Iterator<String> keys = new KeyInHashDirIterator();
        while (keys.hasNext()) {
            String key = keys.next();
            Path keyDir = getKeyDir(key);
            Iterator<BlobStoreFile> i = listBlobStoreFiles(keyDir);
            if (!i.hasNext()) {
                //The dir is empty, so try to delete it, may fail, but that is OK
                try {
                    _fs.delete(keyDir, true);
                } catch (Exception e) {
                    LOG.warn("Could not delete " + keyDir + " will try again later");
                }
            }
            while (i.hasNext()) {
                BlobStoreFile f = i.next();
                if (f.isTmp()) {
                    if (f.getModTime() <= cleanUpIfBefore) {
                        f.delete();
                    }
                }
            }
        }
    }

    protected Iterator<BlobStoreFile> listBlobStoreFiles(Path path) throws IOException {
        ArrayList<BlobStoreFile> ret = new ArrayList<BlobStoreFile>();
        FileStatus[] files = _fs.listStatus(new Path[]{path});
        if (files != null) {
            for (FileStatus sub : files) {
                try {
                    ret.add(new HdfsBlobStoreFile(sub.getPath().getParent(), sub.getPath().getName(),
                            _hadoopConf));
                } catch (IllegalArgumentException e) {
                    //Ignored the file did not match
                    LOG.warn("Found an unexpected file in {} {}", path, sub.getPath().getName());
                }
            }
        }
        return ret.iterator();
    }

    protected Iterator<String> listKeys(Path path) throws IOException {
        ArrayList<String> ret = new ArrayList<String>();
        FileStatus[] files = _fs.listStatus(new Path[]{path});
        if (files != null) {
            for (FileStatus sub : files) {
                try {
                    ret.add(sub.getPath().getName().toString());
                } catch (IllegalArgumentException e) {
                    //Ignored the file did not match
                    LOG.debug("Found an unexpected file in {} {}", path, sub.getPath().getName());
                }
            }
        }
        return ret.iterator();
    }

    protected int getBlobReplication(String key) throws IOException {
        Path path = getKeyDir(key);
        Path dest = new Path(path, BLOBSTORE_DATA);
        return _fs.getFileStatus(dest).getReplication();
    }

    protected int updateBlobReplication(String key, int replication) throws IOException {
        Path path = getKeyDir(key);
        Path dest = new Path(path, BLOBSTORE_DATA);
        _fs.setReplication(dest, (short) replication);
        return _fs.getFileStatus(dest).getReplication();
    }

    protected void delete(Path path) throws IOException {
        _fs.delete(path, true);
    }

    public void shutdown() {
        if (timer != null) {
            timer.cancel();
        }
    }
}


text:
<!DOCTYPE html>

    <link rel="stylesheet" href="css/bootstrap.min.css"/>

    <link rel="stylesheet" href="css/style.css"/>

3DWeb WebGL Workshop


text:
class A {
    public #foo = 3;         // Error
    private #bar = 3;        // Error
    protected #baz = 3;      // Error
    readonly #qux = 3;       // OK
    declare #what: number;   // Error

    public #fooMethod() { return  3; }         // Error
    private #barMethod() { return  3; }        // Error
    protected #bazMethod() { return  3; }      // Error
    readonly #quxMethod() { return  3; }       // Error
    declare #whatMethod()                      // Error
    async #asyncMethod() { return 1; }         //OK
    *#genMethod() { return 1; }                //OK
    async *#asyncGenMethod() { return 1; }     //OK

    public get #fooProp() { return  3; }         // Error
    public set #fooProp(value: number) {  }      // Error
    private get #barProp() { return  3; }        // Error
    private set #barProp(value: number) {  }     // Error
    protected get #bazProp() { return  3; }      // Error
    protected set #bazProp(value: number) {  }   // Error
    readonly get #quxProp() { return  3; }       // Error
    readonly set #quxProp(value: number) {  }    // Error
    declare get #whatProp()                      // Error
    declare set #whatProp(value: number)         // Error
    async get #asyncProp() { return 1; }         // Error
    async set #asyncProp(value: number) { }      // Error
}

abstract class B {
    abstract #quux = 3;      // Error
}


text:
#region CmdMessenger - MIT - (c) 2014 Thijs Elenbaas.

#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace CommandMessenger.Transport.Serial
{

    /// <summary>
    /// Class for storing last succesfull connection
    /// </summary>
    [Serializable]
    public class SerialConnectionManagerSettings
    {
        public String Port{ get; set; }
        public int BaudRate { get; set; }
    }

    /// <summary>
    /// Connection manager for serial port connection
    /// </summary>
    public class SerialConnectionManager : ConnectionManager
    {
        private enum ScanType { None, Quick, Thorough }

        private SerialConnectionManagerSettings _serialConnectionManagerSettings;
        private readonly ISerialConnectionStorer _serialConnectionStorer;
        private readonly SerialTransport _serialTransport;

        private ScanType _scanType = ScanType.None;

        // The control to invoke the callback on
        private readonly object _tryConnectionLock = new object();

        /// <summary>
        /// Available serial port names in system.
        /// </summary>
        public string[] AvailableSerialPorts
        {
            get;
            private set;
        }

        /// <summary>
        /// In scan mode allow to try different baud rates besides that is configured in SerialSettings.
        /// </summary>
        public bool DeviceScanBaudRateSelection { get; set; }

        /// <summary>
        /// Connection manager for serial port connection
        /// </summary>
        public SerialConnectionManager(SerialTransport serialTransport, CmdMessenger cmdMessenger, int watchdogCommandId = 0, string uniqueDeviceId = null, ISerialConnectionStorer serialConnectionStorer = null) :
            base(cmdMessenger, watchdogCommandId, uniqueDeviceId)
        {

            if (serialTransport == null)
                throw new ArgumentNullException("serialTransport", "Transport is null.");

            _serialTransport = serialTransport;
            _serialConnectionStorer = serialConnectionStorer;
            PersistentSettings = (_serialConnectionStorer != null);

            DeviceScanBaudRateSelection = true;

            UpdateAvailablePorts();

            _serialConnectionManagerSettings = new SerialConnectionManagerSettings();
            ReadSettings();
        }

        /// <summary>
        /// Try connection
        /// </summary>
        /// <returns>Result</returns>
        private DeviceStatus TryConnection(string portName = null, int baudRate = int.MinValue)
        {
            lock (_tryConnectionLock)
            {
                // Save current port and baud rate
                string oldPortName = _serialTransport.CurrentSerialSettings.PortName;
                int oldBaudRate = _serialTransport.CurrentSerialSettings.BaudRate;

                // Update serial settings with new port and baud rate.
                if (portName != null) _serialTransport.CurrentSerialSettings.PortName = portName;
                if (baudRate != int.MinValue) _serialTransport.CurrentSerialSettings.BaudRate = baudRate;

                if (!_serialTransport.CurrentSerialSettings.IsValid())
                {
                    // Restore back previous settings if newly provided was invalid.
                    _serialTransport.CurrentSerialSettings.PortName = oldPortName;
                    _serialTransport.CurrentSerialSettings.BaudRate = oldBaudRate;

                    return DeviceStatus.NotAvailable;
                }

                Connected = false;

                Log(1, @"Trying serial port " + _serialTransport.CurrentSerialSettings.PortName + " at " + _serialTransport.CurrentSerialSettings.BaudRate + " bauds.");
                if (_serialTransport.Connect())
                {
                    // Calculate optimal timeout for command. It should be not less than Serial Port timeout. Lets add additional 250ms.
                    int optimalTimeout = _serialTransport.CurrentSerialSettings.Timeout + 250;
                    DeviceStatus status = ArduinoAvailable(optimalTimeout);

                    Connected = (status == DeviceStatus.Available);

                    if (Connected)
                    {
                        Log(1, "Connected to serial port " + _serialTransport.CurrentSerialSettings.PortName + " at " + _serialTransport.CurrentSerialSettings.BaudRate + " bauds.");
                        StoreSettings();
                    }
                    else
                    {
                        _serialTransport.Disconnect();
                    }

                    return status;
                }

                return DeviceStatus.NotAvailable;
            }
        }

        protected override void StartScan()
        {
            base.StartScan();

            if (ConnectionManagerMode == Mode.Scan)
            {
                UpdateAvailablePorts();
                _scanType = ScanType.None;
            }
        }

        //Try to connect using current connections settings and trigger event if succesful
        protected override void DoWorkConnect()
        {
            var activeConnection = false;

            try
            {
                activeConnection = TryConnection() == DeviceStatus.Available;
            }
            catch
            {
                // Do nothing
            }

            if (activeConnection)
            {
                ConnectionFoundEvent();
            }
        }

        // Perform scan to find connected systems
        protected override void DoWorkScan()
        {
            // First try if currentConnection is open or can be opened
            var activeConnection = false;

            switch (_scanType)
            {
                case ScanType.None:
                    try
                    {
                        activeConnection = TryConnection() == DeviceStatus.Available;
                    }
                    catch
                    {
                        // Do nothing
                    }
                    _scanType = ScanType.Quick;
                    break;
                case ScanType.Quick:
                    try
                    {
                        activeConnection = QuickScan();
                    }
                    catch
                    {
                        // Do nothing
                    }
                    _scanType = ScanType.Thorough;
                    break;
                case ScanType.Thorough:
                    try
                    {
                        activeConnection = ThoroughScan();
                    }
                    catch
                    {
                        // Do nothing
                    }
                    _scanType = ScanType.Quick;
                    break;
            }

            // Trigger event when a connection was made
            if (activeConnection)
            {
                ConnectionFoundEvent();
            }
        }

        private bool QuickScan()
        {
            Log(3, "Performing quick scan.");

            if (PersistentSettings)
            {
                // Then try if last stored connection can be opened
                Log(3, "Trying last stored connection.");
                if (TryConnection(_serialConnectionManagerSettings.Port, _serialConnectionManagerSettings.BaudRate) == DeviceStatus.Available)
                    return true;
            }

            // Quickly run through most used baud rates
            var commonBaudRates = DeviceScanBaudRateSelection
                ? SerialUtils.CommonBaudRates
                : new [] { _serialTransport.CurrentSerialSettings.BaudRate };
            foreach (var portName in AvailableSerialPorts)
            {
                // Get baud rates collection
                var baudRateCollection = DeviceScanBaudRateSelection
                    ? SerialUtils.GetSupportedBaudRates(portName)
                    : new[] { _serialTransport.CurrentSerialSettings.BaudRate };

                var baudRates = commonBaudRates.Where(baudRateCollection.Contains).ToList();
                if (baudRates.Any())
                {
                    Log(1, "Trying serial port " + portName + " using " + baudRateCollection.Length + " baud rate(s).");

                    //  Now loop through baud rate collection
                    foreach (var commonBaudRate in baudRates)
                    {
                        // Stop scanning if state was changed
                        if (ConnectionManagerMode != Mode.Scan) return false;

                        DeviceStatus status = TryConnection(portName, commonBaudRate);
                        if (status == DeviceStatus.Available) return true;
                        if (status == DeviceStatus.IdentityMismatch) break; // break the loop and continue to next port.
                    }
                }

                // If port list has changed, interrupt scan and test new ports first
                if (NewPortScan()) return true;
            }

            if (!AvailableSerialPorts.Any())
            {
                // Need to check for new ports if current ports list is empty
                if (NewPortScan()) return true;

                // Add small delay to reduce of Quick->Thorough->Quick->Thorough scan attempts - 400ms here + 100ms in main loop = ~500ms
                Thread.Sleep(400);
            }

            return false;
        }

        private bool ThoroughScan()
        {
            Log(1, "Performing thorough scan.");

            // Then try if last stored connection can be opened
            if (PersistentSettings && TryConnection(_serialConnectionManagerSettings.Port, _serialConnectionManagerSettings.BaudRate) == DeviceStatus.Available)
                return true;

            // Slowly walk through
            foreach (var portName in AvailableSerialPorts)
            {
                // Get baud rates collection
                var baudRateCollection = DeviceScanBaudRateSelection
                    ? SerialUtils.GetSupportedBaudRates(portName)
                    : new[] { _serialTransport.CurrentSerialSettings.BaudRate };

                //  Now loop through baud rate collection
				if (baudRateCollection.Any())
				{
                	Log(1, "Trying serial port " + portName + " using " + baudRateCollection.Length + " baud rate(s).");

	                foreach (var baudRate in baudRateCollection)
	                {
                        // Stop scanning if state was changed
                        if (ConnectionManagerMode != Mode.Scan) return false;

                        DeviceStatus status = TryConnection(portName, baudRate);
                        if (status == DeviceStatus.Available) return true;
                        if (status == DeviceStatus.IdentityMismatch) break; // break the loop and continue to next port.
	                }
				}

                // If port list has changed, interrupt scan and test new ports first
                if (NewPortScan()) return true;
            }

            if (!AvailableSerialPorts.Any())
            {
                // Need to check for new ports if current ports list is empty
                if (NewPortScan()) return true;

                // Add small delay to reduce of Quick->Thorough->Quick->Thorough scan attempts - 400ms here + 100ms in main loop = ~500ms
                Thread.Sleep(400);
            }

            return false;
        }

        private bool NewPortScan()
        {
            // Then see if port list has changed
            var newPorts = NewPortInList();
            if (!newPorts.Any()) { return false; }

            //TODO: 4s - practical delay for Leonardo board, probably for other boards will be different. Need to investigate more on this.
            const int waitTime = 4000;
            Log(1, "New port(s) " + string.Join(",", newPorts) + " detected, wait for " + (waitTime / 1000.0) + "s before attempt to connect.");

            // Wait a bit before new port will be available then try to connect
            Thread.Sleep(waitTime);

            // Quickly run through most used ports
            var commonBaudRates = DeviceScanBaudRateSelection
                ? SerialUtils.CommonBaudRates
                : new[] { _serialTransport.CurrentSerialSettings.BaudRate };

            foreach (var portName in newPorts)
            {
                // Get baud rates collection
                var baudRateCollection = DeviceScanBaudRateSelection
                    ? SerialUtils.GetSupportedBaudRates(portName)
                    : new[] { _serialTransport.CurrentSerialSettings.BaudRate };

                // First add commonBaudRates available
                var sortedBaudRates = commonBaudRates.Where(baudRateCollection.Contains).ToList();
                // Then add other BaudRates
                sortedBaudRates.AddRange(baudRateCollection.Where(baudRate => !commonBaudRates.Contains(baudRate)));

                foreach (var currentBaudRate in sortedBaudRates)
                {
                    // Stop scanning if state was changed
                    if (ConnectionManagerMode != Mode.Scan) return false;

                    DeviceStatus status = TryConnection(portName, currentBaudRate);
                    if (status == DeviceStatus.Available) return true;
                    if (status == DeviceStatus.IdentityMismatch) break; // break the loop and continue to next port.
                }
            }

            return false;
        }

        private void UpdateAvailablePorts()
        {
            AvailableSerialPorts = SerialUtils.GetPortNames();
        }

        private List<string> NewPortInList()
        {
            var currentPorts = SerialUtils.GetPortNames();
            var newPorts = currentPorts.Except(AvailableSerialPorts).ToList();

            // Actualize ports collection
            AvailableSerialPorts = currentPorts;

            return newPorts;
        }

        protected override void StoreSettings()
        {
            if (!PersistentSettings) return;

            _serialConnectionManagerSettings.Port = _serialTransport.CurrentSerialSettings.PortName;
            _serialConnectionManagerSettings.BaudRate = _serialTransport.CurrentSerialSettings.BaudRate;

            _serialConnectionStorer.StoreSettings(_serialConnectionManagerSettings);
        }

        protected override sealed void ReadSettings()
        {
            if (!PersistentSettings) return;
            _serialConnectionManagerSettings = _serialConnectionStorer.RetrieveSettings();
        }
    }
}


text:
/*
 * This is a helper class for the generated Sqlite 'data' package.
 * This class is not generated, and must be manually updated when
 * database tables are added or removed.  See 'generate_data_contentprovider'
 */
package com.harlie.radiotheater.radiomysterytheater.data_helper;

import android.content.ContentUris;
import android.net.Uri;

import com.harlie.radiotheater.radiomysterytheater.data.RadioTheaterProvider;
import com.harlie.radiotheater.radiomysterytheater.data.actors.ActorsColumns;
import com.harlie.radiotheater.radiomysterytheater.data.actorsepisodes.ActorsEpisodesColumns;
import com.harlie.radiotheater.radiomysterytheater.data.configepisodes.ConfigEpisodesColumns;
import com.harlie.radiotheater.radiomysterytheater.data.configuration.ConfigurationColumns;
import com.harlie.radiotheater.radiomysterytheater.data.episodes.EpisodesColumns;
import com.harlie.radiotheater.radiomysterytheater.data.episodesactors.EpisodesActorsColumns;
import com.harlie.radiotheater.radiomysterytheater.data.episodeswriters.EpisodesWritersColumns;
import com.harlie.radiotheater.radiomysterytheater.data.writers.WritersColumns;
import com.harlie.radiotheater.radiomysterytheater.data.writersepisodes.WritersEpisodesColumns;
import com.harlie.radiotheater.radiomysterytheater.utils.LogHelper;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class RadioTheaterContract {
    private final static String TAG = "LEE: <" + RadioTheaterContract.class.getSimpleName() + ">";

    // Reference the AUTHORITY generated from 'generate-data-provider.sh'
    public static final String CONTENT_AUTHORITY = RadioTheaterProvider.AUTHORITY;

    public static String airDate(String episodeAirDate) {
        DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
        DateFormat outputFormat = new SimpleDateFormat("EEEE', 'MMMM d', ' yyyy", Locale.getDefault());
        Date date = null;
        try {
            date = inputFormat.parse(episodeAirDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String outputDateStr = outputFormat.format(date);
        LogHelper.v(TAG, "airdate="+episodeAirDate+", formatted="+outputDateStr);
        return outputDateStr;
    }

    public static String airDateShort(String episodeAirDate) {
        String airdateTmp = airDate(episodeAirDate);
        airdateTmp = airdateTmp.substring(airdateTmp.indexOf(',') + 1);
        return airdateTmp;
    }

    /* Inner class that defines the table contents of the configuration table */
    public static final class ConfigurationEntry extends ConfigurationColumns {

        public static Uri buildConfigurationUri(long id) {
            LogHelper.v(TAG, "buildConfigurationUri");
            return ContentUris.withAppendedId(CONTENT_URI, id);
        }

        @SuppressWarnings("SameReturnValue")
        public static Uri buildConfigurationUri() {
            LogHelper.v(TAG, "buildConfigurationUri");
            return CONTENT_URI;
        }

    }

    /* Inner class that defines the table contents of the configuration table */
    public static final class ConfigEpisodesEntry extends ConfigEpisodesColumns {

        public static Uri buildConfigEpisodeUri(long id) {
            LogHelper.v(TAG, "buildConfigEpisodeUri");
            return ContentUris.withAppendedId(CONTENT_URI, id);
        }

        @SuppressWarnings("SameReturnValue")
        public static Uri buildConfigEpisodesUri() {
            LogHelper.v(TAG, "buildConfigEpisodesUri");
            return CONTENT_URI;
        }

    }

    /* Inner class that defines the table contents of the episodes table */
    public static final class EpisodesEntry extends EpisodesColumns {

        public static Uri buildEpisodeUri(long id) {
            LogHelper.v(TAG, "buildEpisodeUri");
            return ContentUris.withAppendedId(CONTENT_URI, id);
        }

        @SuppressWarnings("SameReturnValue")
        public static Uri buildEpisodesUri() {
            LogHelper.v(TAG, "buildEpisodesUri");
            return CONTENT_URI;
        }

    }

    /* Inner class that defines the table contents of the episodesactors table */
    public static final class EpisodesActorsEntry extends EpisodesActorsColumns {

        public static Uri buildEpisodeActorUri(long id) {
            LogHelper.v(TAG, "buildEpisodeActorUri");
            return ContentUris.withAppendedId(CONTENT_URI, id);
        }

        @SuppressWarnings("SameReturnValue")
        public static Uri buildEpisodesActorsUri() {
            LogHelper.v(TAG, "buildEpisodesActorsUri");
            return CONTENT_URI;
        }

    }

    /* Inner class that defines the table contents of the episodeswriters table */
    public static final class EpisodesWritersEntry extends EpisodesWritersColumns {

        public static Uri buildEpisodeWriterUri(long id) {
            LogHelper.v(TAG, "buildEpisodeWriterUri");
            return ContentUris.withAppendedId(CONTENT_URI, id);
        }

        @SuppressWarnings("SameReturnValue")
        public static Uri buildEpisodesWritersUri() {
            LogHelper.v(TAG, "buildEpisodesWritersUri");
            return CONTENT_URI;
        }

    }

    /* Inner class that defines the table contents of the actors table */
    public static final class ActorsEntry extends ActorsColumns {

        public static Uri buildActorUri(long id) {
            LogHelper.v(TAG, "buildActorUri");
            return ContentUris.withAppendedId(CONTENT_URI, id);
        }

        @SuppressWarnings("SameReturnValue")
        public static Uri buildActorsUri() {
            LogHelper.v(TAG, "buildActorsUri");
            return CONTENT_URI;
        }

    }

    /* Inner class that defines the table contents of the actorsepisodes table */
    public static final class ActorsEpisodesEntry extends ActorsEpisodesColumns {

        public static Uri buildActorEpisodesUri(long id) {
            LogHelper.v(TAG, "buildActorEpisodesUri");
            return ContentUris.withAppendedId(CONTENT_URI, id);
        }

        @SuppressWarnings("SameReturnValue")
        public static Uri buildActorsEpisodesUri() {
            LogHelper.v(TAG, "buildActorsEpisodesUri");
            return CONTENT_URI;
        }

    }

    /* Inner class that defines the table contents of the writers table */
    public static final class WritersEntry extends WritersColumns {

        public static Uri buildWriterUri(long id) {
            LogHelper.v(TAG, "buildWriterUri");
            return ContentUris.withAppendedId(CONTENT_URI, id);
        }

        @SuppressWarnings("SameReturnValue")
        public static Uri buildWritersUri() {
            LogHelper.v(TAG, "buildWritersUri");
            return CONTENT_URI;
        }

    }

    /* Inner class that defines the table contents of the writersepisodes table */
    public static final class WritersEpisodesEntry extends WritersEpisodesColumns {

        public static Uri buildWriterEpisodesUri(long id) {
            LogHelper.v(TAG, "buildWriterEpisodesUri");
            return ContentUris.withAppendedId(CONTENT_URI, id);
        }

        @SuppressWarnings("SameReturnValue")
        public static Uri buildWritersEpisodesUri() {
            LogHelper.v(TAG, "buildWritersEpisodesUri");
            return CONTENT_URI;
        }

    }

}


text:
@interface SentryCrashLogger_Tests : XCTestCase

@property (nonatomic, readwrite, retain) NSString *tempDir;

@end

@implementation SentryCrashLogger_Tests

@synthesize tempDir = _tempDir;

- (void)setUp
{
    [super setUp];
    self.tempDir = [self createTempPath];
}

- (void)tearDown
{
    [self removePath:self.tempDir];
}

- (void)testLogError
{
    SentryCrashLOG_ERROR(@"TEST");
}

- (void)testLogErrorNull
{
    NSString *str = nil;
    SentryCrashLOG_ERROR(str);
}

- (void)testLogAlways
{
    SentryCrashLOG_ALWAYS(@"TEST");
}

- (void)testLogAlwaysNull
{
    NSString *str = nil;
    SentryCrashLOG_ALWAYS(str);
}

- (void)testLogBasicError
{
    SentryCrashLOGBASIC_ERROR(@"TEST");
}

- (void)testLogBasicErrorNull
{
    NSString *str = nil;
    SentryCrashLOGBASIC_ERROR(str);
}

- (void)testLogBasicAlways
{
    SentryCrashLOGBASIC_ALWAYS(@"TEST");
}

- (void)testLogBasicAlwaysNull
{
    NSString *str = nil;
    SentryCrashLOGBASIC_ALWAYS(str);
}

- (void)testSetLogFilename
{
    NSString *expected = @"TEST";
    NSString *logFileName = [self.tempDir stringByAppendingPathComponent:@"log.txt"];
    sentrycrashlog_setLogFilename([logFileName UTF8String], true);
    SentryCrashLOGBASIC_ALWAYS(expected);
    sentrycrashlog_setLogFilename(nil, true);

    NSError *error = nil;
    NSString *result = [NSString stringWithContentsOfFile:logFileName
                                                 encoding:NSUTF8StringEncoding
                                                    error:&error];
    XCTAssertNil(error, @"");
    result = [[result componentsSeparatedByString:@"\x0a"] objectAtIndex:0];
    XCTAssertEqualObjects(result, expected, @"");

    SentryCrashLOGBASIC_ALWAYS(@"blah blah");
    result = [NSString stringWithContentsOfFile:logFileName
                                       encoding:NSUTF8StringEncoding
                                          error:&error];
    result = [[result componentsSeparatedByString:@"\x0a"] objectAtIndex:0];
    XCTAssertNil(error, @"");
    XCTAssertEqualObjects(result, expected, @"");
}

@end


text:
#include <aws/greengrassv2/model/CreateDeploymentRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::GreengrassV2::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

CreateDeploymentRequest::CreateDeploymentRequest() :
    m_targetArnHasBeenSet(false),
    m_deploymentNameHasBeenSet(false),
    m_componentsHasBeenSet(false),
    m_iotJobConfigurationHasBeenSet(false),
    m_deploymentPoliciesHasBeenSet(false),
    m_tagsHasBeenSet(false),
    m_clientToken(Aws::Utils::UUID::RandomUUID()),
    m_clientTokenHasBeenSet(true)
{
}

Aws::String CreateDeploymentRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_targetArnHasBeenSet)
  {
   payload.WithString("targetArn", m_targetArn);

  }

  if(m_deploymentNameHasBeenSet)
  {
   payload.WithString("deploymentName", m_deploymentName);

  }

  if(m_componentsHasBeenSet)
  {
   JsonValue componentsJsonMap;
   for(auto& componentsItem : m_components)
   {
     componentsJsonMap.WithObject(componentsItem.first, componentsItem.second.Jsonize());
   }
   payload.WithObject("components", std::move(componentsJsonMap));

  }

  if(m_iotJobConfigurationHasBeenSet)
  {
   payload.WithObject("iotJobConfiguration", m_iotJobConfiguration.Jsonize());

  }

  if(m_deploymentPoliciesHasBeenSet)
  {
   payload.WithObject("deploymentPolicies", m_deploymentPolicies.Jsonize());

  }

  if(m_tagsHasBeenSet)
  {
   JsonValue tagsJsonMap;
   for(auto& tagsItem : m_tags)
   {
     tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
   }
   payload.WithObject("tags", std::move(tagsJsonMap));

  }

  if(m_clientTokenHasBeenSet)
  {
   payload.WithString("clientToken", m_clientToken);

  }

  return payload.View().WriteReadable();
}