text:
package org.apache.camel.component.jetty;

import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.ssl.SslSelectChannelConnector;

public class ExplicitHttpsRouteTest extends HttpsRouteTest {

    // START SNIPPET: e2
    private Connector createSslSocketConnector(int port) throws URISyntaxException {
        // From Camel 2.5.0 Camel-Jetty is using SslSelectChannelConnector instead of SslSocketConnector
        SslSelectChannelConnector sslSocketConnector = new SslSelectChannelConnector();
        sslSocketConnector.getSslContextFactory().setKeyManagerPassword(pwd);
        sslSocketConnector.getSslContextFactory().setKeyStorePassword(pwd);
        URL keyStoreUrl = this.getClass().getClassLoader().getResource("jsse/localhost.ks");
        sslSocketConnector.getSslContextFactory().setKeyStorePath(keyStoreUrl.toURI().getPath());
        sslSocketConnector.getSslContextFactory().setTrustStoreType("JKS");
        sslSocketConnector.setPort(port);
        return sslSocketConnector;
    }
    // END SNIPPET: e2

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            public void configure() throws URISyntaxException {
                // START SNIPPET: e1
                // create SSL select channel connectors for port 9080 and 9090
                Map<Integer, Connector> connectors = new HashMap<Integer, Connector>();
                connectors.put(port1, createSslSocketConnector(port1));
                connectors.put(port2, createSslSocketConnector(port2));

                JettyHttpComponent jetty = getContext().getComponent("jetty", JettyHttpComponent.class);
                jetty.setSslSocketConnectors(connectors);
                // END SNIPPET: e1

                from("jetty:https://localhost:" + port1 + "/test").to("mock:a");

                Processor proc = new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        exchange.getOut().setBody("<b>Hello World</b>");
                    }
                };
                from("jetty:https://localhost:" + port1 + "/hello").process(proc);

                from("jetty:https://localhost:" + port2 + "/test").to("mock:b");
            }
        };
    }
}


text:
package mavenlink

import (
	"fmt"
	"net/url"
	"sort"
	"strconv"
	"time"

	"github.com/gistia/slackbot/db"
	"github.com/gistia/slackbot/utils"
)

type Mavenlink struct {
	Token   string
	Verbose bool
}

func NewMavenlink(token string, verbose bool) *Mavenlink {
	return &Mavenlink{Token: token, Verbose: verbose}
}

func NewFor(user string) (*Mavenlink, error) {
	token, err := db.GetSetting(user, "MAVENLINK_TOKEN")
	if err != nil {
		return nil, err
	}
	return NewMavenlink(token.Value, false), nil
}

//---------- Projects

func (mvn *Mavenlink) CreateProject(p Project) (*Project, error) {
	params := map[string]string{
		"workspace[title]":        p.Title,
		"workspace[description]":  p.Description,
		"workspace[creator_role]": p.CreatorRole,
	}
	resp, err := mvn.post("workspaces", params)
	if err != nil {
		return nil, err
	}
	projects := resp.ProjectList()
	if len(projects) > 0 {
		return &projects[0], nil
	}
	return nil, nil
}

func (mvn *Mavenlink) Projects() ([]Project, error) {
	var projects []Project
	resp, err := mvn.get("workspaces", nil)

	if err != nil {
		return nil, err
	}

	for k, _ := range resp.Projects {
		p := resp.Projects[k]
		projects = append(projects, p)
	}

	return projects, nil
}

func (mvn *Mavenlink) GetProject(id string) (*Project, error) {
	req := fmt.Sprintf("workspaces/%s", id)
	r, err := mvn.get(req, nil)

	if err != nil {
		return nil, err
	}

	return &r.ProjectList()[0], err
}

func (mvn *Mavenlink) SearchProject(term string) ([]Project, error) {
	search := fmt.Sprintf("matching=%s", term)
	r, err := mvn.get("workspaces", []string{search})

	if err != nil {
		return nil, err
	}

	return r.ProjectList(), err
}

//---------- Stories

func (mvn *Mavenlink) GetStory(id string) (*Story, error) {
	req := fmt.Sprintf("stories/%s", id)
	r, err := mvn.get(req, nil)

	if err != nil {
		return nil, err
	}

	return &r.StoryList()[0], err
}

func (mvn *Mavenlink) Stories(projectId string) ([]Story, error) {
	filters := []string{
		fmt.Sprintf("workspace_id=%s", projectId),
		"parents_only=true",
	}
	resp, err := mvn.get("stories", filters)

	if err != nil {
		return nil, err
	}

	return resp.StoryList(), nil
}

func (mvn *Mavenlink) getStoriesAssignees(stories []Story) ([]Story, error) {
	resStories := []Story{}
	for _, s := range stories {
		resStory, err := mvn.GetAssignees(s)
		if err != nil {
			return nil, err
		}

		resStories = append(resStories, *resStory)
	}

	return resStories, nil
}

func (mvn *Mavenlink) GetChildStories(parentId string) ([]Story, error) {
	filters := []string{
		fmt.Sprintf("with_parent_id=%s", parentId),
		"include=assignees",
	}
	resp, err := mvn.get("stories", filters)
	if err != nil {
		return nil, err
	}

	stories, err := mvn.getStoriesAssignees(resp.StoryList())
	if err != nil {
		return nil, err
	}

	return stories, nil
}

func (mvn *Mavenlink) CreateStory(s Story) (*Story, error) {
	params, err := s.ToParams()
	if err != nil {
		return nil, err
	}

	resp, err := mvn.post("stories", params)
	if err != nil {
		return nil, err
	}

	stories := resp.StoryList()
	if len(stories) > 0 {
		return &stories[0], nil
	}

	return nil, nil
}

func (mvn *Mavenlink) UpdateStory(story Story) (*Story, error) {
	params, err := story.ToParams()
	if err != nil {
		return nil, err
	}

	resp, err := mvn.put("stories/"+story.Id, params)
	if err != nil {
		return nil, err
	}

	stories := resp.StoryList()
	if len(stories) > 0 {
		return &stories[0], nil
	}

	return nil, nil
}

func (mvn *Mavenlink) SetStoryState(id, state string) (*Story, error) {
	params := map[string]string{"story[state]": state}
	resp, err := mvn.put("stories/"+id, params)
	if err != nil {
		return nil, err
	}

	stories := resp.StoryList()
	if len(stories) > 0 {
		return &stories[0], nil
	}

	return nil, nil
}

func (mvn *Mavenlink) AddTimeEntry(s *Story, minutes int) (*TimeEntry, error) {
	date := time.Now().Format("2006-01-02")
	minStr := strconv.Itoa(minutes)
	params := map[string]string{
		"time_entry[date_performed]":  date,
		"time_entry[time_in_minutes]": minStr,
		"time_entry[story_id]":        s.Id,
		"time_entry[workspace_id]":    s.WorkspaceId,
	}
	resp, err := mvn.post("time_entries", params)
	if err != nil {
		return nil, err
	}

	entries := resp.TimeEntryList()
	if len(entries) > 0 {
		return &entries[0], nil
	}

	return nil, nil
}

//---------- Users

type UsersByName []User

func (u UsersByName) Len() int {
	return len(u)
}
func (u UsersByName) Swap(i, j int) {
	u[i], u[j] = u[j], u[i]
}
func (u UsersByName) Less(i, j int) bool {
	return u[i].Name < u[j].Name
}

func (mvn *Mavenlink) GetUsersMap() (map[string]User, error) {
	users, err := mvn.GetUsers()
	if err != nil {
		return nil, err
	}

	usersMap := map[string]User{}
	for _, u := range users {
		usersMap[u.Id] = u
	}

	return usersMap, nil
}

func (mvn *Mavenlink) GetUsers() ([]User, error) {
	var users []User
	resp, err := mvn.get("users", nil)

	if err != nil {
		return nil, err
	}

	for k, _ := range resp.Users {
		p := resp.Users[k]
		users = append(users, p)
	}
	sort.Sort(UsersByName(users))

	return users, nil
}

//---------- Internals

func (mvn *Mavenlink) makeUrl(uri string) string {
	return fmt.Sprintf("https://api.mavenlink.com/api/v1/%s.json", uri)
}

func (mvn *Mavenlink) request(method string, url string, data url.Values) ([]byte, error) {
	auth := fmt.Sprintf("Bearer %s", mvn.Token)
	headers := map[string]string{
		"Content-Type":  "application/x-www-form-urlencoded",
		"Authorization": auth,
	}

	return utils.Request(method, url, data, headers)
}

func (mvn *Mavenlink) getBody(uri string, filters []string) ([]byte, error) {
	url := mvn.makeUrl(uri)

	if filters != nil {
		url = url + "?"
		for i, f := range filters {
			if i > 0 {
				url = url + "&"
			}
			url = url + f
		}
	}

	fmt.Printf("Requesting: %s...\n", url)

	return mvn.request("GET", url, nil)
}

func (mvn *Mavenlink) get(uri string, filters []string) (*Response, error) {
	if filters == nil {
		filters = []string{}
	}

	filters = append(filters, "per_page=200")

	json, err := mvn.getBody(uri, filters)
	if err != nil {
		return nil, err
	}

	fmt.Println("Got:", string(json))

	resp, err := NewFromJson(json)
	return resp, err
}

func (mvn *Mavenlink) performRequest(method string, uri string, params map[string]string) (*Response, error) {
	postParams := url.Values{}
	for k, v := range params {
		postParams.Add(k, v)
	}

	mvnUrl := mvn.makeUrl(uri)
	fmt.Printf("[mvn] Performing request %s to %s with %+v\n", method, mvnUrl, postParams)
	json, err := mvn.request(method, mvnUrl, postParams)
	if err != nil {
		return nil, err
	}

	resp, err := NewFromJson(json)
	return resp, err
}

func (mvn *Mavenlink) post(uri string, params map[string]string) (*Response, error) {
	return mvn.performRequest("POST", uri, params)
}

func (mvn *Mavenlink) put(uri string, params map[string]string) (*Response, error) {
	return mvn.performRequest("PUT", uri, params)
}

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#ifndef SAX_PARSER_H
#define SAX_PARSER_H

#include "store/api/item.h"
#include "store/api/item_factory.h"
#include "diagnostics/xquery_diagnostics.h"

#include <libxml/parser.h>
#include <libxml/xmlstring.h>

#include <istream>
#include <vector>

namespace zorba {

class ZORBA_DLL_PUBLIC SAXParser
{
 public:
  SAXParser(store::ItemFactory &factory,
            const zstring& baseUri,
            const zstring& docUri,
            XQueryDiagnostics* xqueryDiagnostics);

  virtual ~SAXParser();

 public:
  bool parseDocument(store::Item_t& result, std::istream& stream);
 public:
  static void	startDocument(void * ctx);

  static void endDocument(void * ctx);

  static void startElement(
			void * ctx,
			const xmlChar * localname,
			const xmlChar * prefix,
			const xmlChar * URI,
			int nb_namespaces,
			const xmlChar ** namespaces,
			int nb_attributes,
			int nb_defaulted,
			const xmlChar ** attributes);

  static void endElement(
			void * ctx,
			const xmlChar * localname,
			const xmlChar * prefix,
			const xmlChar * URI);

  static void characters(
			void * ctx,
			const xmlChar * ch,
			int len);

  static void	cdataBlock(
			void * ctx,
			const xmlChar * ch,
			int len);

  static void comment(
			void * ctx,
			const xmlChar * ch);

  static void	processingInstruction(
			void * ctx,
			const xmlChar * target,
			const xmlChar * data);

  static void error(void * ctx, const char * msg, ... );

  static void warning(void * ctx, const char * msg, ... );

 protected:
  void createTextNodeFromBuffer();

  xmlSAXHandler theHandler;
  store::Item_t theResult;
  store::ItemFactory& theFactory;
  const zstring& theBaseUri;
  const zstring& theDocUri;
  bool theSucceeded;
  std::vector<store::Item_t> theStack;
  XQueryDiagnostics* theXQueryDiagnostics;
  std::ostringstream* m_stream;
};

}

#endif
/* vim:set et sw=2 ts=2: */


text:
using System;
using NUnit.Framework;
using Moq;
using SJP.Schematic.Core;
using SJP.Schematic.Tests.Utilities;

namespace SJP.Schematic.Sqlite.Tests
{
    [TestFixture]
    internal static class SqliteDatabaseKeyTests
    {
        [Test]
        public static void Ctor_GivenNullName_DoesNotThrowArgumentNullException()
        {
            const DatabaseKeyType keyType = DatabaseKeyType.Primary;
            var column = Mock.Of<IDatabaseColumn>();
            var columns = new[] { column };

            Assert.That(() => new SqliteDatabaseKey(null, keyType, columns), Throws.Nothing);
        }

        [Test]
        public static void Ctor_GivenInvalidDatabaseKeyType_ThrowsArgumentException()
        {
            Identifier keyName = "test_key";
            const DatabaseKeyType keyType = (DatabaseKeyType)55;
            var column = Mock.Of<IDatabaseColumn>();
            var columns = new[] { column };

            Assert.That(() => new SqliteDatabaseKey(keyName, keyType, columns), Throws.ArgumentException);
        }

        [Test]
        public static void Ctor_GivenNullColumnSet_ThrowsArgumentNullException()
        {
            Identifier keyName = "test_key";
            const DatabaseKeyType keyType = DatabaseKeyType.Primary;

            Assert.That(() => new SqliteDatabaseKey(keyName, keyType, null), Throws.ArgumentNullException);
        }

        [Test]
        public static void Ctor_GivenEmptyColumnSet_ThrowsArgumentNullException()
        {
            Identifier keyName = "test_key";
            const DatabaseKeyType keyType = DatabaseKeyType.Primary;
            var columns = Array.Empty<IDatabaseColumn>();

            Assert.That(() => new SqliteDatabaseKey(keyName, keyType, columns), Throws.ArgumentNullException);
        }

        [Test]
        public static void Ctor_GivenColumnSetContainingNullColumn_ThrowsArgumentNullException()
        {
            Identifier keyName = "test_key";
            const DatabaseKeyType keyType = DatabaseKeyType.Primary;
            var columns = new IDatabaseColumn[] { null };

            Assert.That(() => new SqliteDatabaseKey(keyName, keyType, columns), Throws.ArgumentNullException);
        }

        [Test]
        public static void Name_PropertyGet_EqualsCtorArg()
        {
            Identifier keyName = "test_key";
            const DatabaseKeyType keyType = DatabaseKeyType.Primary;
            var column = Mock.Of<IDatabaseColumn>();
            var columns = new[] { column };

            var key = new SqliteDatabaseKey(keyName, keyType, columns);

            Assert.That(key.Name.UnwrapSome(), Is.EqualTo(keyName));
        }

        [Test]
        public static void KeyType_PropertyGet_EqualsCtorArg()
        {
            Identifier keyName = "test_key";
            const DatabaseKeyType keyType = DatabaseKeyType.Foreign;
            var column = Mock.Of<IDatabaseColumn>();
            var columns = new[] { column };

            var key = new SqliteDatabaseKey(keyName, keyType, columns);

            Assert.That(key.KeyType, Is.EqualTo(keyType));
        }

        [Test]
        public static void Columns_PropertyGet_EqualsCtorArg()
        {
            Identifier keyName = "test_key";
            const DatabaseKeyType keyType = DatabaseKeyType.Foreign;
            var column = Mock.Of<IDatabaseColumn>();
            var columns = new[] { column };

            var key = new SqliteDatabaseKey(keyName, keyType, columns);

            Assert.That(key.Columns, Is.EqualTo(columns));
        }

        [Test]
        public static void IsEnabled_PropertyGet_ReturnsTrue()
        {
            Identifier keyName = "test_key";
            const DatabaseKeyType keyType = DatabaseKeyType.Foreign;
            var column = Mock.Of<IDatabaseColumn>();
            var columns = new[] { column };
            const bool enabled = true;

            var key = new SqliteDatabaseKey(keyName, keyType, columns);

            Assert.That(key.IsEnabled, Is.EqualTo(enabled));
        }
    }
}


text:
package com.google.cloud.compute.deprecated;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class DiskImageConfigurationTest {

  private static final DiskId SOURCE_DISK =  DiskId.of("project", "zone", "disk");
  private static final String SOURCE_DISK_ID = "diskId";
  private static final Long ARCHIVE_SIZE_BYTES = 42L;
  private static final ImageConfiguration.SourceType SOURCE_TYPE =
      ImageConfiguration.SourceType.RAW;
  private static final DiskImageConfiguration CONFIGURATION =
      DiskImageConfiguration.newBuilder(SOURCE_DISK)
          .setSourceDiskId(SOURCE_DISK_ID)
          .setSourceType(SOURCE_TYPE)
          .setArchiveSizeBytes(ARCHIVE_SIZE_BYTES)
          .build();

  @Test
  public void testToBuilder() {
    compareDiskImageConfiguration(CONFIGURATION, CONFIGURATION.toBuilder().build());
    DiskId newDisk = DiskId.of("newProject", "newZone", "newDisk");
    String newDiskId = "newDiskId";
    DiskImageConfiguration configuration = CONFIGURATION.toBuilder()
        .setSourceDisk(newDisk)
        .setSourceDiskId(newDiskId)
        .build();
    assertEquals(newDisk, configuration.getSourceDisk());
    assertEquals(newDiskId, configuration.getSourceDiskId());
    configuration = configuration.toBuilder()
        .setSourceDiskId(SOURCE_DISK_ID)
        .setSourceDisk(SOURCE_DISK)
        .build();
    compareDiskImageConfiguration(CONFIGURATION, configuration);
  }

  @Test
  public void testToBuilderIncomplete() {
    DiskImageConfiguration configuration = DiskImageConfiguration.of(SOURCE_DISK);
    compareDiskImageConfiguration(configuration, configuration.toBuilder().build());
  }

  @Test
  public void testBuilder() {
    assertEquals(SOURCE_TYPE, CONFIGURATION.getSourceType());
    assertEquals(SOURCE_DISK, CONFIGURATION.getSourceDisk());
    assertEquals(SOURCE_DISK_ID, CONFIGURATION.getSourceDiskId());
    assertEquals(ARCHIVE_SIZE_BYTES, CONFIGURATION.getArchiveSizeBytes());
    assertEquals(ImageConfiguration.Type.DISK, CONFIGURATION.getType());
  }

  @Test
  public void testToAndFromPb() {
    assertTrue(ImageConfiguration.fromPb(CONFIGURATION.toPb()) instanceof DiskImageConfiguration);
    compareDiskImageConfiguration(CONFIGURATION,
        ImageConfiguration.<DiskImageConfiguration>fromPb(CONFIGURATION.toPb()));
    DiskImageConfiguration configuration = DiskImageConfiguration.of(SOURCE_DISK);
    compareDiskImageConfiguration(configuration,
        DiskImageConfiguration.fromPb(configuration.toPb()));
  }

  @Test
  public void testOf() {
    DiskImageConfiguration configuration = DiskImageConfiguration.of(SOURCE_DISK);
    assertEquals(ImageConfiguration.Type.DISK, configuration.getType());
    assertNull(configuration.getSourceDiskId());
    assertNull(configuration.getSourceType());
    assertNull(configuration.getArchiveSizeBytes());
    assertEquals(SOURCE_DISK, configuration.getSourceDisk());
  }

  @Test
  public void testSetProjectId() {
    DiskImageConfiguration configuration = CONFIGURATION.toBuilder()
        .setSourceDisk(DiskId.of("zone", "disk"))
        .build();
    compareDiskImageConfiguration(CONFIGURATION, configuration.setProjectId("project"));
  }

  private void compareDiskImageConfiguration(DiskImageConfiguration expected,
      DiskImageConfiguration value) {
    assertEquals(expected, value);
    assertEquals(expected.getType(), value.getType());
    assertEquals(expected.getArchiveSizeBytes(), value.getArchiveSizeBytes());
    assertEquals(expected.getSourceDisk(), value.getSourceDisk());
    assertEquals(expected.getSourceDiskId(), value.getSourceDiskId());
    assertEquals(expected.getSourceType(), value.getSourceType());
    assertEquals(expected.hashCode(), value.hashCode());
  }
}


text:
$modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules'

# Import the Networking Common Modules
Import-Module -Name (Join-Path -Path $modulePath `
                               -ChildPath (Join-Path -Path 'NetworkingDsc.Common' `
                                                     -ChildPath 'NetworkingDsc.Common.psm1'))

# Import the Networking Resource Helper Module
Import-Module -Name (Join-Path -Path $modulePath `
                               -ChildPath (Join-Path -Path 'NetworkingDsc.ResourceHelper' `
                                                     -ChildPath 'NetworkingDsc.ResourceHelper.psm1'))

# Import Localization Strings
$localizedData = Get-LocalizedData `
    -ResourceName 'MSFT_xNetAdapterBinding' `
    -ResourcePath (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)

<#
    .SYNOPSIS
    Returns the current state of an Adapter Binding on an interface.

    .PARAMETER InterfaceAlias
    Specifies the alias of a network interface. Supports the use of '*'.

    .PARAMETER ComponentId
    Specifies the underlying name of the transport or filter in the following
    form - ms_xxxx, such as ms_tcpip.

    .PARAMETER Ensure
    Specifies if the component ID for the Interface should be Enabled or Disabled.
#>
function Get-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Collections.Hashtable])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $InterfaceAlias,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ComponentId,

        [ValidateSet('Enabled', 'Disabled')]
        [String]
        $State = 'Enabled'
    )

    Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): "
        $($LocalizedData.GettingNetAdapterBindingMessage -f `
            $InterfaceAlias,$ComponentId)
        ) -join '')

    $currentNetAdapterBinding = Get-Binding @PSBoundParameters

    $adapterState = $currentNetAdapterBinding.Enabled |
        Sort-Object -Unique

    if ( $adapterState.Count -eq 2)
    {
        $currentEnabled = 'Mixed'
    }
    elseif ( $adapterState -eq $true )
    {
        $currentEnabled = 'Enabled'
    }
    else
    {
        $currentEnabled = 'Disabled'
    }

    $returnValue = @{
        InterfaceAlias = $InterfaceAlias
        ComponentId    = $ComponentId
        State          = $State
        CurrentState   = $currentEnabled
    }

    return $returnValue
} # Get-TargetResource

<#
    .SYNOPSIS
    Sets the Adapter Binding on a specific interface.

    .PARAMETER InterfaceAlias
    Specifies the alias of a network interface. Supports the use of '*'.

    .PARAMETER ComponentId
    Specifies the underlying name of the transport or filter in the following
    form - ms_xxxx, such as ms_tcpip.

    .PARAMETER Ensure
    Specifies if the component ID for the Interface should be Enabled or Disabled.
#>
function Set-TargetResource
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $InterfaceAlias,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ComponentId,

        [ValidateSet('Enabled', 'Disabled')]
        [String]
        $State = 'Enabled'
    )

    Write-Verbose -Message ( @( "$($MyInvocation.MyCommand): "
        $($LocalizedData.ApplyingNetAdapterBindingMessage -f `
            $InterfaceAlias,$ComponentId)
        ) -join '')

    $currentNetAdapterBinding = Get-Binding @PSBoundParameters

    # Remove the State so we can splat
    $null = $PSBoundParameters.Remove('State')

    if ($State -eq 'Enabled')
    {
        Enable-NetAdapterBinding @PSBoundParameters
        Write-Verbose -Message ( @("$($MyInvocation.MyCommand): "
            $($LocalizedData.NetAdapterBindingEnabledMessage -f `
                $InterfaceAlias,$ComponentId)
            ) -join '' )
    }
    else
    {
        Disable-NetAdapterBinding @PSBoundParameters
        Write-Verbose -Message ( @("$($MyInvocation.MyCommand): "
            $($LocalizedData.NetAdapterBindingDisabledMessage -f `
                $InterfaceAlias,$ComponentId)
            ) -join '' )
    } # if
} # Set-TargetResource

<#
    .SYNOPSIS
    Tests the current state of an Adapter Binding on an interface.

    .PARAMETER InterfaceAlias
    Specifies the alias of a network interface. Supports the use of '*'.

    .PARAMETER ComponentId
    Specifies the underlying name of the transport or filter in the following
    form - ms_xxxx, such as ms_tcpip.

    .PARAMETER Ensure
    Specifies if the component ID for the Interface should be Enabled or Disabled.
#>
function Test-TargetResource
{
    [CmdletBinding()]
    [OutputType([System.Boolean])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $InterfaceAlias,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ComponentId,

        [ValidateSet('Enabled', 'Disabled')]
        [String]
        $State = 'Enabled'
    )

    Write-Verbose -Message ( @("$($MyInvocation.MyCommand): "
        $($LocalizedData.CheckingNetAdapterBindingMessage -f `
            $InterfaceAlias,$ComponentId)
        ) -join '')

    $currentNetAdapterBinding = Get-Binding @PSBoundParameters

    $adapterState = $currentNetAdapterBinding.Enabled |
        Sort-Object -Unique

    if ( $adapterState.Count -eq 2)
    {
        $currentEnabled = 'Mixed'
    }
    elseif ( $adapterState -eq $true )
    {
        $currentEnabled = 'Enabled'
    }
    else
    {
        $currentEnabled = 'Disabled'
    }

    # Test if the binding is in the correct state
    if ($currentEnabled -ne $State)
    {
        Write-Verbose -Message ( @("$($MyInvocation.MyCommand): "
            $($LocalizedData.NetAdapterBindingDoesNotMatchMessage -f `
                $InterfaceAlias,$ComponentId,$State,$currentEnabled)
            ) -join '' )
        return $false
    }
    else
    {
        Write-Verbose -Message ( @("$($MyInvocation.MyCommand): "
            $($LocalizedData.NetAdapterBindingMatchMessage -f `
                $InterfaceAlias,$ComponentId)
            ) -join '' )
        return $true
    } # if
} # Test-TargetResource

<#
    .SYNOPSIS
    Ensures the interface and component Id exists and returns the Net Adapter binding object.

    .PARAMETER InterfaceAlias
    Specifies the alias of a network interface. Supports the use of '*'.

    .PARAMETER ComponentId
    Specifies the underlying name of the transport or filter in the following
    form - ms_xxxx, such as ms_tcpip.

    .PARAMETER Ensure
    Specifies if the component ID for the Interface should be Enabled or Disabled.
#>
function Get-Binding
{
    [CmdletBinding()]
    [OutputType([Microsoft.Management.Infrastructure.CimInstance])]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $InterfaceAlias,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ComponentId,

        [ValidateSet('Enabled', 'Disabled')]
        [String]
        $State = 'Enabled'
    )

    if (-not (Get-NetAdapter -Name $InterfaceAlias -ErrorAction SilentlyContinue))
    {
        $errorId = 'InterfaceNotAvailable'
        $errorCategory = [System.Management.Automation.ErrorCategory]::DeviceError
        $errorMessage = $($LocalizedData.InterfaceNotAvailableError) -f $InterfaceAlias
        $exception = New-Object -TypeName System.InvalidOperationException `
            -ArgumentList $errorMessage
        $errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord `
            -ArgumentList $exception, $errorId, $errorCategory, $null

        $PSCmdlet.ThrowTerminatingError($errorRecord)
    } # if

    $binding = Get-NetAdapterBinding `
        -InterfaceAlias $InterfaceAlias `
        -ComponentId $ComponentId `
        -ErrorAction Stop

    return $binding
} # Get-Binding

Export-ModuleMember -function *-TargetResource


text:
import ast
import unittest

from ..collector import Collector
from .. import node

from . import get_asset_path

class TestCollector(unittest.TestCase):
    def setUp(self):
        self.example = '''
class OuterClass(object):
    def method0(self):
        return 0

    def method1(self):
        if a:
            return 1

        return 2

def outer():
    if a:
        return 1

    else:
        return 2

    return 0'''

        self.node = Collector.collect_from_ast(ast.parse(self.example), filename='package/base/module.py')

    def __assert_node(self, node, name, ast_type, node_type=node.Node):
        self.assertIsInstance(node, node_type)
        self.assertEqual(name, node.name)
        self.assertIsInstance(node.ast, ast_type)

    def test_global_node(self):
        self.__assert_node(self.node, 'module', ast.Module, node.ModuleNode)
        self.assertEqual('package/base/module.py', self.node.filename)

    def test_outer_function(self):
        self.__assert_node(self.node.resolve('outer'), 'outer', ast.FunctionDef)

    def test_outer_class(self):
        self.__assert_node(self.node.resolve('OuterClass'), 'OuterClass', ast.ClassDef, node_type=node.ContainerNode)

    def test_method(self):
        self.__assert_node(self.node.resolve('OuterClass.method1'), 'method1', ast.FunctionDef)

    def test_init_file(self):
        pkg = Collector.collect_from_ast(ast.parse(self.example), filename='package/__init__.py')

        self.__assert_node(pkg, 'package', ast.Module, node_type=node.ModuleNode)

    def test_collect_from_file(self):
        pkg = Collector.collect_from_file(get_asset_path('testfile.py'))

        self.__assert_node(pkg, 'testfile', ast.Module, node_type=node.ModuleNode)
        self.assertEqual(get_asset_path('testfile.py'), pkg.filename)

    def test_collect_from_directory(self):
        pkg = Collector.collect_from_file(get_asset_path('testpackage'))

        self.__assert_node(pkg, 'testpackage', ast.Module, node_type=node.ModuleNode)
        self.assertEqual(get_asset_path('testpackage/__init__.py'), pkg.filename)


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>DestinyActivityGraphDefinition | The Traveler</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					The Traveler

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					DestinyActivityGraphDefinition

Interface DestinyActivityGraphDefinition

Represents a Map View in the director: be them overview views, destination views,
						or other.

They have nodes which map to activities, and other various visual elements that
					we (or others) may or may not be able to use.

Activity graphs, most importantly, have nodes which can have activities in
					various states of playability.

Unfortunately, activity graphs are combined at runtime with Game UI-only assets
						such as fragments of map images, various in-game special effects, decals etc...
					that we don't get in these definitions.

If we end up having time, we may end up trying to manually populate those here:
						but the last time we tried that, before the lead-up to D1, it proved to be
						unmaintainable as the game's content changed. So don't bet the farm on us
					providing that content in this definition.

Hierarchy

						DestinyActivityGraphDefinition

Index

Properties

art<wbr>Elements

connections

display<wbr>Objectives

display<wbr>Progressions

hash

index

linked<wbr>Graphs

nodes

redacted

Properties

art<wbr>Elements

art<wbr>Elements: DestinyActivityGraphArtElementDefinition[]

Defined in type-definitions/destiny2/interfaces.ts:2270

Represents one-off/special UI elements that appear on the map.

connections

connections: DestinyActivityGraphConnectionDefinition[]

Defined in type-definitions/destiny2/interfaces.ts:2275

Represents connections between graph nodes. However, it lacks context that we'd
							need to make good use of it.

display<wbr>Objectives

display<wbr>Objectives: DestinyActivityGraphDisplayObjectiveDefinition[]

Defined in type-definitions/destiny2/interfaces.ts:2282

Objectives can display on maps, and this is supposedly metadata for that. I have
								not had the time to analyze the details of what is useful within however: we
								could be missing important data to make this work. Expect this property to be
							expanded on later if possible.

display<wbr>Progressions

display<wbr>Progressions: DestinyActivityGraphDisplayProgressionDefinition[]

Defined in type-definitions/destiny2/interfaces.ts:2288

Progressions can also display on maps, but similarly to displayObjectives we
								appear to lack some required information and context right now. We will have to
							look into it later and add more data if possible.

hash

hash: number

Defined in type-definitions/destiny2/interfaces.ts:2298

The unique identifier for this entity. Guaranteed to be unique for the type of
							entity, but not globally.

When entities refer to each other in Destiny content, it is this hash that they
						are referring to.

index

index: number

Defined in type-definitions/destiny2/interfaces.ts:2300

The index of the entity as it was found in the investment tables.

linked<wbr>Graphs

linked<wbr>Graphs: DestinyLinkedGraphDefinition[]

Defined in type-definitions/destiny2/interfaces.ts:2290

Represents links between this Activity Graph and other ones.

nodes

nodes: DestinyActivityGraphNodeDefinition[]

Defined in type-definitions/destiny2/interfaces.ts:2268

These represent the visual "nodes" on the map's view. These are the activities
							you can click on in the map.

redacted

redacted: boolean

Defined in type-definitions/destiny2/interfaces.ts:2305

If this is true, then there is an entity with this identifier/type combination,
							but BNet is not yet allowed to show it. Sorry!

						Globals

						Destiny<wbr>Activity<wbr>Graph<wbr>Definition

								art<wbr>Elements

								connections

								display<wbr>Objectives

								display<wbr>Progressions

								hash

								index

								linked<wbr>Graphs

								nodes

								redacted

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method


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

namespace Autocore.Samples.Console
{
	#region Output services
	public interface IOutput : ISingletonDependency
	{
		void WriteLine(string text);
	}
	public class ConsoleOutput : IOutput
	{
		public virtual void WriteLine(string text)
		{
			System.Console.WriteLine(string.Format("ConsoleOutput: {0}", text));
		}
	}
	public class ColorConsoleOutput : IOutput
	{
		public virtual void WriteLine(string text)
		{
			System.Console.ForegroundColor = ConsoleColor.Yellow;
			System.Console.Write("ColorConsoleOutput: ");
			System.Console.ForegroundColor = ConsoleColor.Gray;
			System.Console.WriteLine(text);
		}
	}
	#endregion

	#region Greeter service
	public interface IGreeter : ISingletonDependency
	{
		void Greet(string name);
	}
	public class Greeter : IGreeter
	{
		IEnumerable<IOutput> _outputs;
		public Greeter(IEnumerable<IOutput> outputs)
		{
			_outputs = outputs;
		}
		public void Greet(string name)
		{
			var msg = string.Format("Hello {0}!", name);
			foreach (var o in _outputs)
			{
				o.WriteLine(msg);
			}
		}
	}
	#endregion

	public static class Program
	{
		public static void Main(string[] args)
		{
			using (var container = Autocore.Factory.Create())
			{
				var greeter = container.Resolve<IGreeter>();
				greeter.Greet("John");
			}
		}
	}
}


text:
<?php
$table = new HtmlNode('table', ['class' => 'table table-striped table-bordered table-hover']);
$table->addNode($thead = new HtmlNode('thead'));
$thead->addNode($tr = new HtmlNode('tr'));
foreach (Clientes::getFieldsNames() as $field_name) {
    $th = new HtmlNode('th', null, [$field_name]);
    $tr->addNode($th = new HtmlNode('th', null, [$field_name]));
}
$tr->addNode(new HtmlNode('th', null, 'Acciones'));
$table->addNode($tboby = new HtmlNode('tbody', null, App::$response['data']['rows'], function($row) {
	$tr = new HtmlNode('tr', null);
	foreach (Clientes::getFieldsNames() as $field_name) {
		$tr->addNode(new HtmlNode('td', null, $row[$field_name]));
	}
	$tr->addNode(new HtmlNode('td', null, array(
		new HtmlLink('clientes/'.$row->pk, 'Editar'), ' ',
		new HtmlLink('clientes/'.$row->pk.'/borrar', 'Borrar')
	)));
	return $tr;
}));
return $table;


text:
goGetEm
========

`goGetEm` is a small collection of shell scripts for managing your *Go* packages.

Disclaimer
---------

I have tested this on bash and zsh and it works as it should *for me*. I don't see any reason why it should do anything wrong, but YMMV and you use at your own risk.

Uses
----

There are a couple of things it is useful for:

1. "Backing up" your src files in a way that doesn't take up much space, so that you can quickly get your Go files up and running on new workstations.
2. Easily sharing the go packages you use with others.
3. Keeping your go packages up to date without hassle. `goGetUp.sh`could be set as a cron job to make this even less effort.

The Scripts
-----------

`goGetMe.sh` creates a newline delimited list of packages from the files in your $GOPATH/src folder and saves this in a file called `$GOPATH/src/.goGot` by default (I will continue to refer to this here as `.goGot`, but it could be called anything). You can set the filename with a variable as shown here:
```sh
sh goGetMe.sh [filename]
```
Each time this script is run, the packages it finds that aren't currently in `.goGot` will be arranged alphabetically and appended to it. This will result in alphabetically arranged chunks in chronological order. If you would like to have the whole file in alphabetical order, removing `.goGot` and running this script again, so it will pick up all your packages and arrange them alphabetically. (I would recommend making a backup of the file, just in case). You could also use the CLI tool `sort`.

-------------------------------------------------------------

`goGetEm.sh` runs `go get $package` on all the packages listed in `.goGot`. If the package list has another name, use the same syntax as above to show the script which file to use:
```sh
sh goGetEm.sh [filename]
```
-------------------------------------------------------------

`goGetUp.sh` is a small wrapper around the two previous scripts that runs `go get -u` any packages in `.goGot` that are not in the `$GOPATH/src` folder and updates the rest that are. This uses the same syntax once again:
```sh
sh goGetUp.sh [filename]
```
**NB: `go get -u` is a lot slower than `go get`, so this is correspondingly slower than `goGetEm`**

Setup
-----

1. Make sure that your `$GOPATH` environment variable is set. See the [golang code reference page][1] for more details and instructions on how to do this.
2. `git clone https://github.com/azmr/goGetEm` in whichever directory you would like it to live. Mine stays in `$GOPATH/src`.
Alternatively, fork this repo, so that you always have your `.goGot` under a VCS.
3. Run whichever scripts need running, as shown above.
4. Keep the `.goGot` file in a safe place for when you next need it.
[1]: http://golang.org/doc/code.html#GOPATH

Go get 'em tiger.


text:
#pragma once
#include <aws/pinpoint/Pinpoint_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Pinpoint
{
namespace Model
{
  enum class SegmentType
  {
    NOT_SET,
    DIMENSIONAL,
    IMPORT
  };

namespace SegmentTypeMapper
{
AWS_PINPOINT_API SegmentType GetSegmentTypeForName(const Aws::String& name);

AWS_PINPOINT_API Aws::String GetNameForSegmentType(SegmentType value);
} // namespace SegmentTypeMapper
} // namespace Model
} // namespace Pinpoint
} // namespace Aws


text:
/* $Id$ */

#include "module.h"
#include<assert.h>

/*  */

/************************************************************/
/*                Identity Selector Control                 */
/************************************************************/

struct idsel_dlg_data {
    khm_int32 magic;            /* Always IDSEL_DLG_DATA_MAGIC */
    khm_handle ident;           /* Current selection */
};

#define IDSEL_DLG_DATA_MAGIC 0x5967d973

/* Dialog procedure for IDD_IDSEL

   runs in UI thread */
static INT_PTR CALLBACK
idspec_dlg_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch(uMsg) {
    case WM_INITDIALOG:
        {
            struct idsel_dlg_data * d;

            d = PMALLOC(sizeof(*d));
            ZeroMemory(d, sizeof(*d));
            d->magic = IDSEL_DLG_DATA_MAGIC;
            d->ident = NULL;

#pragma warning(push)
#pragma warning(disable: 4244)
            SetWindowLongPtr(hwnd, DWLP_USER, (LONG_PTR) d);
#pragma warning(pop)

            /* TODO: Initialize controls etc. */

        }
        /* We return FALSE here because this is an embedded modeless
           dialog and we don't want to steal focus from the
           container. */
        return FALSE;

    case WM_DESTROY:
        {
            struct idsel_dlg_data * d;

            d = (struct idsel_dlg_data *)(LONG_PTR)
                GetWindowLongPtr(hwnd, DWLP_USER);

#ifdef DEBUG
            assert(d != NULL);
            assert(d->magic == IDSEL_DLG_DATA_MAGIC);
#endif
            if (d && d->magic == IDSEL_DLG_DATA_MAGIC) {
                if (d->ident) {
                    kcdb_identity_release(d->ident);
                    d->ident = NULL;
                }

                d->magic = 0;
                PFREE(d);
            }
#pragma warning(push)
#pragma warning(disable: 4244)
            SetWindowLongPtr(hwnd, DWLP_USER, 0);
#pragma warning(pop)
        }
        return TRUE;

    case WM_COMMAND:
        break;

    case KHUI_WM_NC_NOTIFY:
        {
            struct idsel_dlg_data * d;
            khm_handle * ph;

            d = (struct idsel_dlg_data *)(LONG_PTR)
                GetWindowLongPtr(hwnd, DWLP_USER);

            switch (HIWORD(wParam)) {
            case WMNC_IDSEL_GET_IDENT:
                ph = (khm_handle *) lParam;

                /* TODO: Make sure that d->ident is up-to-date */
                if (ph) {
                    *ph = d->ident;
                    if (d->ident)
                        kcdb_identity_hold(d->ident);
                }
                break;
            }
        }
        return TRUE;
    }
    return FALSE;
}

/* Identity Selector control factory

   Runs in UI thread */
khm_int32 KHMAPI
idsel_factory(HWND hwnd_parent, khui_identity_selector * u_data) {
    wchar_t dn[KHUI_MAXCCH_NAME];

    if (hwnd_parent) {

        u_data->hwnd_selector = CreateDialog(hResModule, MAKEINTRESOURCE(IDD_IDSPEC),
                                             hwnd_parent, idspec_dlg_proc);

        assert(u_data->hwnd_selector);

        LoadString(hResModule, IDS_ID_INSTANCE, dn, ARRAYLENGTH(dn));
        u_data->display_name = PWCSDUP(dn);

        u_data->icon = LoadIcon(hResModule, MAKEINTRESOURCE(IDI_IDENTITY));

        return (u_data->hwnd_selector ? KHM_ERROR_SUCCESS : KHM_ERROR_UNKNOWN);

    } else {
        if (u_data->display_name) {
            PFREE(u_data->display_name);
            u_data->display_name = NULL;
        }

        if (u_data->icon) {
            DestroyIcon(u_data->icon);
            u_data->icon = NULL;
        }

        return KHM_ERROR_SUCCESS;
    }
}


text:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="bc.css">

Idling, DMU, DocumentChanged and Need for Regen

Today we have two ever-recurring topics to revisit: a discussion on how to react to a document modification and yet another example of the need for regeneration:

Idling and external events, DMU and DocumentChanged

Need for regen in an updater

Idling and external events, DMU and DocumentChanged

We have repeatedly compared the various ways of reacting to Revit model changes, e.g. in the discussion on DocumentChanged versus Dynamic Model Updater.

Let's take a fresh look at this, with some important input once again from Arnošt Löbel:

Question: Is there any way to quickly retrieve an ApplicationServices.Application object when I don't have a Document to work with? I don't see a way to it in the OnStartUp event such that I could just cache it somewhere. I also assume using the following is bad:

  var app = new Application();

Often this is the case when I'm in an Idling event handler but not always. I need the application in order to get at the DocumentSet via Application.Documents.

Answer: If you are in an Idling event handler, are you sure that is the right place to be?

I recommend avoiding the Idling event in preference of external events, if you are using it to interact with the outside world.

The only time I think an Idling event is more useful than an external event is when you want it to be called immediately and once only, e.g., because you are in a situation in which you would like to start a transaction to modify the document and cannot do so right away.

Anyway, apart from that: if you indeed are inside an Idling event handler, you do in fact have extremely easy and direct access to the Application object.

The sender argument of various events, such as ApplicationInitialized and Idling, provide the UIApplication object to you straight away:

  private void OnIdling(
    object sender,
    IdlingEventArgs e )
  {
    var uiApp = sender as UIApplication;

    // . . .
  }

Response: Thanks for the info. My code is from previous versions of Revit where external events did not exist (I think) and that's why I was using the Idling event. I'll give these IExternalEventHandler classes a go and test it out.

Meanwhile can you confirm this is an acceptable workflow:

Create an IUpdater and set it trigger when a parameter value has changed.

When IUpdater.Execute is called and I need to make changes a Document I then invoke ExternalEvent.Create(IExternalEventHandler).

Inside of the IExternalEventHandler.Execute method, I create transactions and make more changes to the Document. This will not trigger the IUpdater to fire again.

Last time I remember transactions were not permitted inside of IUpdater.Execute. Please correct me if I'm wrong.

Answer: Yes, your workflow looks pretty OK to me.

Yes, you cannot start a new transaction inside the updater Execute method, because that is executed inside the already running transaction that triggered the updater in the first place.

For that usage, I would assume that a one-off Idling event handler is almost exactly equivalent to an external event, so you can use either.

Answer from Arnošt: Sorry, Jeremy, I have to chime in.

This workflow actually does not look good to me. Although it is possible to do it that way, it is neither an efficient way nor the safest way. You already hinted the solution in your second statement, though; that one is correct: If you need to make changes (as a reaction to model changes that triggered the updater), you should make them right there in the IUpdater.Execute method. It is possible because the model is already in a transaction and thus is open for changes made by external applications.

In the suggested workflow, the biggest problem I see (beside that it is rather inefficient) is that the new transaction will be separated from the transaction that triggered the updater. That is wrong and dangerous. The danger is in the possibility that the end user undoes one transaction but leaves the other one in which the updater run. That would leave the document in a state where changes were made to which you wanted to react, but the reaction (in the second transaction) is removed. From the point of view of the application the model would thus be invalid and corrupt.

Response: I agree there's danger although very limited. Let me explain what I'm trying to do and maybe you can direct me to the most efficient process.

I have 4 generic annotation families. I need to track all instances of these families, by their corresponding View, in our external database. Our database is not tracking individual instances of the generic annotations, just overall counts, by part number, per view and cannot be changed. So the events I need to capture from Revit are:

When these annotation instances are created

When these annotation instances are modified

When these annotation instances are deleted

Transaction is undone/redone

When any of these events occur I need launch a synchronization event which does the following:

Delete the existing bill of materials (model group) in the corresponding View

Validate the parameters of generic annotation instance in that View (if they are invalid I need to delete those instances)

Upload the new data to the external database

Recreate the bill of materials table (model group)

I'm using a model group with detail lines and text for the table. To be efficient, I only want to execute a synchronization event once per View.

The IUpdaters are good, however I haven't found a way for them to tell me what View the deleted element ids came from. I'm starting to question whether I should just do everything in the DocumentSaved events rather than bothering with the IUpdaters. I'm open to suggestions if you feel otherwise.

Answer: I agree that you are up to a challenge. Tracking deleted elements is never easy because one cannot get any properties of the elements from Revit. It is not because Revit does not want to give them; we do not have them either in the internal model database. Or rather, we do have them still in some form (for eventual undoing), but it is dangerous accessing them, for they have been disconnected from the rest of the model. This is an internal implementation detail, of course; the point is that one cannot get any info for deleted elements other than the elements' Ids.

You have two choices, the way I see it. Either you have to store more info in your database, or you try a different approach altogether. You suggested performing a synchronization only once when saving a (modified) file. If that is a viable approach for your needs, I would recommend it over the Updater approach.

There is one other thing also suggesting against the use of an updater, and it is also quite important one. You mentioned that: "I need to track all instances of these families, by their corresponding View, in our external database". If that is what I think it is, you should not use updaters at all for the purpose of syncing with the database. It is because updaters are called for new changes only; they are never called for undone or redone transactions, which is a huge problem for external tracking. It means that - in your case - if any creation of the annotations are undone, your database will not have correct records. Therefore, when there is a need for a sync between elements in a Revit model and external databases, the programmer must use the DocumentChanged event. The rule is as follow:

If an app needs to react to model changes by making further changes to the same modes, then an Updater is the way to go.

If an app needs to react to model changes by making changes to external data, then the DocumentChanged must be used.

However, the DocumentChanged event suffers from the same problem: one cannot get any data about already deleted elements. Sorry about that.

Good luck!

Need for Regen in an Updater

We have already looked at a large number of examples of how important it is to be aware of the Revit model modifications your add-in causes.

If you change anything in the model, beware of querying the model afterwards without forcing a regeneration, or you will receive stale and possibly conflicting data.

The Building Coder dedicates a whole topic group to the need to regenerate.

Now we have another entry to add to it, prompted
by Amr's
Revit API discussion thread asking why on earth
the IUpdater is triggered and run with no errors but model changes are undone,
and answered by Amr himself:

Question: IUpdater is triggered and run with no errors but model changes are undone for no obvious reason.

Heeelp, I'm pulling my hair out since morning.

I'm creating an application that searches the document for rooms and then uses the room boundary to create a new floor.

I created an IUpdater so that if the user moves a wall it changes the rooms boundary and therefore uses the new room boundary to create a new floor and delete the old one.

What happens, however, is this: when I move a wall, the updater is triggered and the code runs with no errors, but then I find the wall back in its original location.

I really don't know why and I can't connect any dots!!!

Here's my code for the IUpdater Execute method:

  try
  {
    foreach (ElementId elemId in data.GetModifiedElementIds())
    {
      List<Floor> floorsByRoomsList = new List<Floor>();
      Room r = doc.GetElement(elemId) as Room;
      if (r != null)
      {
        SpatialElementBoundaryOptions sb = new SpatialElementBoundaryOptions();
        sb.SpatialElementBoundaryLocation = SpatialElementBoundaryLocation.CoreBoundary;
        IList<IList<BoundarySegment>> loops = r.GetBoundarySegments(sb);

        List<Floor> floorsInDoc = new List<Floor>();
        floorsInDoc = GetAllFloors(doc);

        foreach(Floor existFloor in floorsInDoc)
        {
          string floorMark = existFloor.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).AsString();
          if (floorMark == r.Id.ToString())
          {
            Floor newFloor = null;
            Opening newOpening = null;
            if (loops.Count == 1)
            {
              #region the new floor properties
              CurveArray floorprofile = Data.ObtainCurveArray(r);
              FloorType fl = existFloor.FloorType;
              Level level = r.Level;
              bool bl;
              if (existFloor.GetAnalyticalModel() == null)
                bl = false;
              else
                bl = true;
              #endregion
              newFloor = doc.Create.NewFloor(floorprofile, fl, level, bl);
              floorsByRoomsList.Add(newFloor);
            }
            else if (loops.Count > 1)
            {
              #region the new floor & opening properties
              CurveArray floorprofile = Data.ObtainCurveArray(r);
              FloorType fl = existFloor.FloorType;
              Level level = r.Level;
              bool bl;
              if (existFloor.GetAnalyticalModel() == null)
                bl = false;
              else
                bl = true;

              CurveArray openingProfile = Data.ObtainOpeningCurveArray(r);
              bool blO = true;
              #endregion
              newFloor = doc.Create.NewFloor(floorprofile, fl, level, bl);
              floorsByRoomsList.Add(newFloor);
              newOpening = doc.Create.NewOpening(newFloor, openingProfile, blO);
            }
          } // if the floor is not located inside room and its name is not equal to room id
          else
          {
            continue;
          }
        }
      } // if the modified element is not a room
      else
      {
        continue;
      }
      foreach (Floor fl in floorsByRoomsList)
        fl.get_Parameter(BuiltInParameter.ALL_MODEL_MARK).Set(r.Id.ToString());
    }
  }

Answer: After various trials and errors I found out that the problem is that Revit doesn't update and reflect the changes instantly, so adding the NewOpening method right after NewFloor didn't work because somehow the floor wasn't yet written to the model. You have to write it manually by adding a call to doc.Regenerate between the calls to NewFloor and NewOpening. This will reflect the latest changes to the model and therefore the NewOpening method will work nicely.

Thank you very much, Amr, for discovering this the hard way and sharing it with us.


text:
<?php
namespace hav\V1\Rest\OnlineUsers;

use ZF\ApiProblem\ApiProblem;
use ZF\Rest\AbstractResourceListener;

class OnlineUsersResource extends AbstractResourceListener
{
    private function getUsers()
    {
        return unserialize(file_get_contents('onlineUsers.bin'));
    }
    /**
     * Create a resource
     *
     * @param  mixed $data
     * @return ApiProblem|mixed
     */
    public function create($data)
    {
        return new ApiProblem(405, 'The POST method has not been defined');
    }

    /**
     * Delete a resource
     *
     * @param  mixed $id
     * @return ApiProblem|mixed
     */
    public function delete($id)
    {
        return new ApiProblem(405, 'The DELETE method has not been defined for individual resources');
    }

    /**
     * Delete a collection, or members of a collection
     *
     * @param  mixed $data
     * @return ApiProblem|mixed
     */
    public function deleteList($data)
    {
        return new ApiProblem(405, 'The DELETE method has not been defined for collections');
    }

    /**
     * Fetch a resource
     *
     * @param  mixed $id
     * @return ApiProblem|mixed
     */
    public function fetch($id)
    {
        $users = unserialize(file_get_contents('onlineUsers.bin'));
        foreach($users as $user){
            if($user['id']==$id){
                return $user;
            }
        }
        return new ApiProblem(400, 'User not found');
    }

    /**
     * Fetch all or a subset of resources
     *
     * @param  array $params
     * @return ApiProblem|mixed
     */
    public function fetchAll($params = array())
    {
        $online = $this->getUsers();
        file_put_contents('onlineUsers.bin', serialize($online));
        return($online);
    }

    /**
     * Patch (partial in-place update) a resource
     *
     * @param  mixed $id
     * @param  mixed $data
     * @return ApiProblem|mixed
     */
    public function patch($id, $data)
    {
        return new ApiProblem(405, 'The PATCH method has not been defined for individual resources');
    }

    /**
     * Replace a collection or members of a collection
     *
     * @param  mixed $data
     * @return ApiProblem|mixed
     */
    public function replaceList($data)
    {
        return new ApiProblem(405, 'The PUT method has not been defined for collections');
    }

    /**
     * Update a resource
     *
     * @param  mixed $id
     * @param  mixed $data
     * @return ApiProblem|mixed
     */
    public function update($id, $data)
    {
        return new ApiProblem(405, 'The PUT method has not been defined for individual resources');
    }
}


text:
DEFINE_TEST_SUITE(NewLabelTests);

class AtlasDemoNew : public TestCase
{
};

class LabelFNTColorAndOpacity : public AtlasDemoNew
{
    float        _time;
public:
    CREATE_FUNC(LabelFNTColorAndOpacity);

    LabelFNTColorAndOpacity();

    virtual void step(float dt);

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFNTSpriteActions : public AtlasDemoNew
{
    float        _time;
public:
    CREATE_FUNC(LabelFNTSpriteActions);

    LabelFNTSpriteActions();
    virtual void step(float dt);

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFNTPadding : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTPadding);

    LabelFNTPadding();
    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFNTOffset : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTOffset);

    LabelFNTOffset();
    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFNTColor : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTColor);

    LabelFNTColor();
    virtual std::string title() const override;

    virtual std::string subtitle() const override;
};

class LabelFNTOpacity : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTOpacity);

    LabelFNTOpacity();
    virtual std::string title() const override;

    virtual std::string subtitle() const override;
};

class LabelFNTHundredLabels : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTHundredLabels);

    LabelFNTHundredLabels();
    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFNTMultiLine : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTMultiLine);

    LabelFNTMultiLine();
    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFNTandTTFEmpty : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTandTTFEmpty);

    LabelFNTandTTFEmpty();
    void updateStrings(float dt);
    virtual std::string title() const override;
    virtual std::string subtitle() const override;

private:
    bool setEmpty;
};

class LabelFNTRetina : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTRetina);

    LabelFNTRetina();
    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFNTGlyphDesigner : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTGlyphDesigner);

    LabelFNTGlyphDesigner();
    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFNTMultiLineAlignment : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTMultiLineAlignment);

    LabelFNTMultiLineAlignment();
    ~LabelFNTMultiLineAlignment();
    void snapArrowsToEdge();
    virtual std::string title() const override;
    virtual std::string subtitle() const override;
    void stringChanged(cocos2d::Ref* sender);
    void alignmentChanged(cocos2d::Ref* sender);
    void onTouchesBegan(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* event);
    void onTouchesEnded(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* event);
    void onTouchesMoved(const std::vector<cocos2d::Touch*>& touches, cocos2d::Event* event);

public:
    cocos2d::Label* _labelShouldRetain;
    cocos2d::Sprite* _arrowsBarShouldRetain;
    cocos2d::Sprite* _arrowsShouldRetain;
    cocos2d::MenuItemFont *_lastSentenceItem, *_lastAlignmentItem;
    bool _drag;
};

class LabelFNTUNICODELanguages : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTUNICODELanguages);

    LabelFNTUNICODELanguages();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFNTBounds : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFNTBounds);

    LabelFNTBounds();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelTTFLongLineWrapping : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelTTFLongLineWrapping);

    LabelTTFLongLineWrapping();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelTTFColor : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelTTFColor);

    LabelTTFColor();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelTTFUnicodeNew : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelTTFUnicodeNew);

    LabelTTFUnicodeNew();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelTTFDynamicAlignment : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelTTFDynamicAlignment);

    LabelTTFDynamicAlignment();
    virtual std::string title() const override;
    virtual std::string subtitle() const override;

private:

    void setAlignmentLeft(cocos2d::Ref* sender);
    void setAlignmentCenter(cocos2d::Ref* sender);
    void setAlignmentRight(cocos2d::Ref* sender);
    void updateAlignment();

    cocos2d::Label* _label;
    cocos2d::TextHAlignment   _horizAlign;

};

class LabelTTFCJKWrappingTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelTTFCJKWrappingTest);

    LabelTTFCJKWrappingTest();
    virtual std::string title() const override;
    virtual std::string subtitle() const override;

private:
};

class LabelTTFFontsTestNew : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelTTFFontsTestNew);

    LabelTTFFontsTestNew();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFontDefTestNew : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFontDefTestNew);

    LabelFontDefTestNew();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;

private:
};

class LabelTTFDistanceField : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelTTFDistanceField);

    LabelTTFDistanceField();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelOutlineAndGlowTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelOutlineAndGlowTest);

    LabelOutlineAndGlowTest();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelShadowTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelShadowTest);

    LabelShadowTest();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;

    void sliderEvent(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type);
private:
    cocos2d::Label* shadowLabelOutline;
    cocos2d::Label* shadowLabelTTF;
    cocos2d::Label* shadowLabelBMFont;
};

class LabelCharMapTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelCharMapTest);

    LabelCharMapTest();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;

    void step(float dt);

private:
    float _time;
};

class LabelCharMapColorTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelCharMapColorTest);

    LabelCharMapColorTest();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;

    void step(float dt);
    void actionFinishCallback();

private:
    float _time;
};

class LabelCrashTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelCrashTest);

    LabelCrashTest();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelTTFOldNew : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelTTFOldNew);

    LabelTTFOldNew();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFontNameTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFontNameTest);

    LabelFontNameTest();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelAlignmentTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelAlignmentTest);

    LabelAlignmentTest();
    virtual std::string title() const override;
    virtual std::string subtitle() const override;
private:
    void  setAlignmentLeft(cocos2d::Ref* sender);
    void  setAlignmentCenter(cocos2d::Ref* sender);
    void  setAlignmentRight(cocos2d::Ref* sender);
    void  setAlignmentTop(cocos2d::Ref* sender);
    void  setAlignmentMiddle(cocos2d::Ref* sender);
    void  setAlignmentBottom(cocos2d::Ref* sender);

    cocos2d::Label* _label;
};

class LabelIssue4428Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue4428Test);

    LabelIssue4428Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelIssue4999Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue4999Test);

    LabelIssue4999Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelLineHeightTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelLineHeightTest);

    LabelLineHeightTest();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;

    void sliderEvent(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type);
private:
    cocos2d::Label* label;
};

class LabelAdditionalKerningTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelAdditionalKerningTest);

    LabelAdditionalKerningTest();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;

    void sliderEvent(cocos2d::Ref* sender, cocos2d::ui::Slider::EventType type);
private:
    cocos2d::Label* label;
};

class LabelIssue8492Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue8492Test);

    LabelIssue8492Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelMultilineWithOutline : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelMultilineWithOutline);

    LabelMultilineWithOutline();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

// we don't support linebreak mode

class LabelIssue9255Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue9255Test);

    LabelIssue9255Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelSmallDimensionsTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelSmallDimensionsTest);

    LabelSmallDimensionsTest();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelIssue10089Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue10089Test);

    LabelIssue10089Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelSystemFontColor : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelSystemFontColor);

    LabelSystemFontColor();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelIssue10773Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue10773Test);

    LabelIssue10773Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelIssue11576Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue11576Test);

    LabelIssue11576Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelIssue11699Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue11699Test);

    LabelIssue11699Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelIssue12409Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue12409Test);

    LabelIssue12409Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelAddChildTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelAddChildTest);

    LabelAddChildTest();

    virtual std::string title() const override;
};

class LabelIssue12775Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue12775Test);

    LabelIssue12775Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelIssue11585Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue11585Test);

    LabelIssue11585Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelFullTypeFontTest : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelFullTypeFontTest);

    LabelFullTypeFontTest();

    virtual std::string title() const override;
};

class LabelIssue10688Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue10688Test);

    LabelIssue10688Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelIssue13202Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue13202Test);

    LabelIssue13202Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

class LabelIssue9500Test : public AtlasDemoNew
{
public:
    CREATE_FUNC(LabelIssue9500Test);

    LabelIssue9500Test();

    virtual std::string title() const override;
    virtual std::string subtitle() const override;
};

#endif


text:
package linkedlist;

import com.google.common.base.Preconditions;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class LinkedList {
    private Node head;
    private Node tail;

    public LinkedList() {
        this.head = null;
        this.tail = null;
    }

    public LinkedList(Node head) {
        Preconditions.checkNotNull(head);
        this.head = head;
        Node tmp = head;
        while (tmp.next != null) {
            tmp = tmp.next;
        }
        this.tail = tmp;
    }

    public LinkedList(int data) {
        this.head = new Node(data);
        this.tail = this.head;
    }

    /*
     * Add this node in the beginning of the current list. Node must be single non null node and
     *  if the node points to multiple nodes then all the rest nodes are dropped.
     */
    public void addNodeBegin(Node node) {
        Preconditions.checkNotNull(node);
        if (node.next != null) node.next = null;
        if (head == null) {
            head = tail = node;
            return;
        }
        node.next = head;
        head = node;
    }

    public void addNodeBegin(int data) {
        Node a = new Node(data);
        addNodeBegin(a);
    }

    public void addNodeLast(int data) {
        Node a = new Node(data);
        addNodeLast(a);
    }

    public void addNodeLast(Node node) {
        Preconditions.checkNotNull(node);
        if (node.next != null) node.next = null;
        if (head == null) {
            head = tail = node;
        }

        tail.next = node;
        tail = node;
    }

    public void reverse() {
        if (head == null || head.next == null) return;
        Node prev = null;
        Node current = head.next;

        while (current != null) {
            head.next = prev;
            prev = head;
            head = current;
            current = current.next;
        }
        head.next = prev;
    }

    public void print() {
        Node pointer = head;
        while (pointer != null) {
            System.out.print(pointer.data + "->");
            pointer = pointer.next;
        }
        System.out.println();
    }

    public Node middle() {
        if (head == null) return null;
        Node slow = head;
        Node fast = head;
        while (fast != null && fast.next != null && fast.next.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        return slow;
    }

    public void append(LinkedList a) {
        tail.next = a.getHead();
        tail = a.getTail();
    }

    public int len() {
        int count = 0;
        Node h = head;
        while (h != null) {
            h = h.next;
            count++;
        }
        return count;
    }

    public static LinkedList merge(LinkedList a, LinkedList b) {

        Node aHead = a.head;
        Node bHead = b.head;
        Node p1 = aHead.next;
        Node p2 = bHead.next;
        aHead.next = bHead;
        while (p1 != null && p2 != null) {
            bHead.next = p1;
            bHead = bHead.next;
            p1 = p1.next;
            bHead.next = p2;
            bHead = bHead.next;
            p2 = p2.next;
        }
        if (p1 != null) {
            bHead.next = p1;
        } else {
            bHead.next = p2;
        }
        return new LinkedList(aHead);
    }

    public boolean hasCycle() {
        Node fast = head;
        Node slow = head;
        while (fast != null && fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        LinkedList a = new LinkedList(new Node(3));
        a.addNodeBegin(4);
        a.addNodeBegin(2);
        a.print();
        LinkedList b = new LinkedList(new Node(11));
        b.addNodeBegin(42);
        b.addNodeBegin(23);
        b.print();
        a.append(b);
        a.print();
        System.out.println(a.len());
        System.out.println(b.hasCycle());
    }

}


text:
#include <g_DriverUtilsService.h>

namespace DriverUtils
{

const DDRpcServerRegisterServiceInfo IDriverUtilsService::kServiceInfo = []() -> DDRpcServerRegisterServiceInfo {
    DDRpcServerRegisterServiceInfo info = {};
    info.id                             = 0x24815012;
    info.version.major                  = 1;
    info.version.minor                  = 1;
    info.version.patch                  = 0;
    info.pName                          = "DriverUtils";
    info.pDescription                   = "A utilities service for modifying the driver.";

    return info;
}();

static DD_RESULT RegisterFunctions(
    DDRpcServer hServer,
    IDriverUtilsService* pService)
{
    DD_RESULT result = DD_RESULT_SUCCESS;

    // Register "EnableTracing"
    if (result == DD_RESULT_SUCCESS)
    {
        DDRpcServerRegisterFunctionInfo info = {};
        info.serviceId                       = 0x24815012;
        info.id                              = 0x1;
        info.pName                           = "EnableTracing";
        info.pDescription                    = "Informs driver we are collecting trace data";
        info.pFuncUserdata                   = pService;
        info.pfnFuncCb                       = [](
            const DDRpcServerCallInfo* pCall) -> DD_RESULT
        {
            auto* pService = reinterpret_cast<IDriverUtilsService*>(pCall->pUserdata);

            // Execute the service implementation
            return pService->EnableTracing();
        };

        result = ddRpcServerRegisterFunction(hServer, &info);
    }

    // Register "EnableCrashAnalysisMode"
    if (result == DD_RESULT_SUCCESS)
    {
        DDRpcServerRegisterFunctionInfo info = {};
        info.serviceId                       = 0x24815012;
        info.id                              = 0x2;
        info.pName                           = "EnableCrashAnalysisMode";
        info.pDescription                    = "Informs driver to enable crash analysis mode";
        info.pFuncUserdata                   = pService;
        info.pfnFuncCb                       = [](
            const DDRpcServerCallInfo* pCall) -> DD_RESULT
        {
            auto* pService = reinterpret_cast<IDriverUtilsService*>(pCall->pUserdata);

            // Execute the service implementation
            return pService->EnableCrashAnalysisMode();
        };

        result = ddRpcServerRegisterFunction(hServer, &info);
    }

    // Register "QueryPalDriverInfo"
    if (result == DD_RESULT_SUCCESS)
    {
        DDRpcServerRegisterFunctionInfo info = {};
        info.serviceId                       = 0x24815012;
        info.id                              = 0x3;
        info.pName                           = "QueryPalDriverInfo";
        info.pDescription                    = "Queries for PAL driver info";
        info.pFuncUserdata                   = pService;
        info.pfnFuncCb                       = [](
            const DDRpcServerCallInfo* pCall) -> DD_RESULT
        {
            auto* pService = reinterpret_cast<IDriverUtilsService*>(pCall->pUserdata);

            // Execute the service implementation
            return pService->QueryPalDriverInfo(*pCall->pWriter);
        };

        result = ddRpcServerRegisterFunction(hServer, &info);
    }

    return result;
}

DD_RESULT RegisterService(
    DDRpcServer hServer,
    IDriverUtilsService* pService
)
{
    // Register the service
    DD_RESULT result = ddRpcServerRegisterService(hServer, &IDriverUtilsService::kServiceInfo);

    // Register individual functions
    if (result == DD_RESULT_SUCCESS)
    {
        result = RegisterFunctions(hServer, pService);

        if (result != DD_RESULT_SUCCESS)
        {
            // Unregister the service if registering functions fails
            ddRpcServerUnregisterService(hServer, IDriverUtilsService::kServiceInfo.id);
        }
    }

    return result;
}

} // namespace DriverUtils


text:
import * as tools from '../tools';

const childTools = [];
Object.keys(tools).forEach(key => childTools.push(tools[key]));

export const allTools = {
  id: 'allTools',
  name: 'Measurements',
  childTools: childTools,
  options: {
    caseProgress: {
      include: true,
      evaluate: true,
    },
  },
};


text:
module Eve
  class Etag < ApplicationRecord
    validates :url, presence: true

    validates :url, uniqueness: true

    validates :etag, presence: true
  end
end


text:
package com.nagopy.android.mypkgs;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ListFragment;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;

import com.nagopy.android.mypkgs.constants.FilterType;
import com.nagopy.android.mypkgs.model.AppData;
import com.nagopy.android.mypkgs.model.event.ListItemSelectedEvent;
import com.nagopy.android.mypkgs.model.event.MultiChoiceModeListenerEvent;
import com.nagopy.android.mypkgs.model.loader.ApplicationLoader;
import com.nagopy.android.mypkgs.util.EventBus;
import com.nagopy.android.mypkgs.view.adapter.ApplicationListAdapter;

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

public class ApplicationListFragment extends ListFragment implements AbsListView.MultiChoiceModeListener {

    private static final String ARG_FILTER_TYPE = "filter_type";
    private final Handler handler = new Handler();

    public static ApplicationListFragment newInstance(FilterType filterType) {
        ApplicationListFragment fragment = new ApplicationListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_FILTER_TYPE, filterType.name());
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return View.inflate(getActivity().getApplicationContext(), R.layout.fragment_application_list, null);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        ListView listView = getListView();
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        listView.setMultiChoiceModeListener(this);

        Context context = getActivity().getApplicationContext();
        FilterType filterType = FilterType.valueOf(getArguments().getString(ARG_FILTER_TYPE));
        final ApplicationListAdapter applicationListAdapter = new ApplicationListAdapter(context, filterType);
        setListAdapter(applicationListAdapter);

        loadApplications();
    }

    public void loadApplications() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (getActivity() == null) {
                    return;
                }
                Context context = getActivity().getApplicationContext();
                final ApplicationListAdapter applicationListAdapter = (ApplicationListAdapter) getListAdapter();

                final ApplicationLoader applicationLoader = ApplicationLoader.getInstance();
                applicationLoader.loadApplicationList(context, new ApplicationLoader.ApplicationLoadListener() {
                    @Override
                    public void onLoaded(final List<AppData> appList) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                applicationListAdapter.updateApplicationList(appList);
                                applicationListAdapter.doFilter();
                                hideProgressBar();
                            }
                        });
                    }
                });
            }
        }).start();
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        AppData appData = (AppData) getListAdapter().getItem(position);
        EventBus.getDefault().post(new ListItemSelectedEvent(appData));
    }

    public ApplicationListFragment showProgressBar() {
        View view = getView();
        if (view != null) {
            view.findViewById(R.id.progressBar).setVisibility(View.VISIBLE);
            getListView().setVisibility(View.INVISIBLE);
        }
        return this;
    }

    public void hideProgressBar() {
        View view = getView();
        if (view != null) {
            view.findViewById(R.id.progressBar).setVisibility(View.GONE);
            getListView().setVisibility(View.VISIBLE);
        } else {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    hideProgressBar();
                }
            }, 3000);
        }
    }

    @Override
    public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean b) {
        MultiChoiceModeListenerEvent.ItemCheckedStateChangedEvent event = new MultiChoiceModeListenerEvent.ItemCheckedStateChangedEvent.Builder()
                .setActionMode(actionMode)
                .setPosition(i)
                .setId(l)
                .setChecked(b)
                .setCheckedItemCount(getListView().getCheckedItemCount())
                .build();
        EventBus.getDefault().post(event);
    }

    @Override
    public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
        EventBus.getDefault().post(new MultiChoiceModeListenerEvent.CreateActionModeEvent(actionMode, menu));
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
        return true;
    }

    @Override
    public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
        List<AppData> checkedItemList = getCheckedItemList(getListView());
        EventBus.getDefault().post(new MultiChoiceModeListenerEvent.ActionItemClickedEvent(actionMode, menuItem, checkedItemList));
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode actionMode) {
        EventBus.getDefault().post(new MultiChoiceModeListenerEvent.DestroyActionModeEvent(actionMode));
    }

    @SuppressWarnings("unchecked")
    @NonNull
    <T> List<T> getCheckedItemList(@NonNull ListView listView) {
        List<T> checkedItemList = new ArrayList<>();
        SparseBooleanArray checkedItemPositions = listView.getCheckedItemPositions();
        for (int i = 0; i < checkedItemPositions.size(); i++) {
            if (checkedItemPositions.valueAt(i)) {
                checkedItemList.add((T) listView.getItemAtPosition(checkedItemPositions.keyAt(i)));
            }
        }
        return checkedItemList;
    }
}