text:
namespace tao::pq
{
   class table_writer;

   namespace internal
   {
      class connection;

      class transaction
         : public std::enable_shared_from_this< transaction >
      {
      public:
         friend class pq::table_writer;

      protected:
         std::shared_ptr< connection > m_connection;

         explicit transaction( const std::shared_ptr< connection >& connection );
         virtual ~transaction() = 0;

      public:
         transaction( const transaction& ) = delete;
         transaction( transaction&& ) = delete;
         void operator=( const transaction& ) = delete;
         void operator=( transaction&& ) = delete;

      protected:
         [[nodiscard]] virtual auto v_is_direct() const noexcept -> bool = 0;

         virtual void v_commit() = 0;
         virtual void v_rollback() = 0;

         virtual void v_reset() noexcept = 0;

         [[nodiscard]] auto current_transaction() const noexcept -> transaction*&;
         void check_current_transaction() const;

         [[nodiscard]] auto execute_params( const char* statement,
                                            const int n_params,
                                            const Oid types[],
                                            const char* const values[],
                                            const int lengths[],
                                            const int formats[] ) -> result;

         auto underlying_raw_ptr() const noexcept -> PGconn*;

      public:
         void commit();
         void rollback();
      };

   }  // namespace internal

}  // namespace tao::pq

#endif

redpajama_set_name: RedPajamaGithub


text:
package br.com.elotech.tributacao.oxm.nfse;

import java.math.BigDecimal;

public class DadosDeducao {

	private String tipoDeducao;

	private String cpf;

	private String cnpj;

	private Integer numeroNotaFiscalReferencia;

	private BigDecimal valorTotalNotaFiscal;

	private BigDecimal percentualADeduzir;

	private BigDecimal valorADeduzir;

	public String getTipoDeducao() {
		return tipoDeducao;
	}

	public void setTipoDeducao(String tipoDeducao) {
		this.tipoDeducao = tipoDeducao;
	}

	public String getCpf() {
		return cpf;
	}

	public void setCpf(String cpf) {
		this.cpf = cpf;
	}

	public String getCnpj() {
		return cnpj;
	}

	public void setCnpj(String cnpj) {
		this.cnpj = cnpj;
	}

	public Integer getNumeroNotaFiscalReferencia() {
		return numeroNotaFiscalReferencia;
	}

	public void setNumeroNotaFiscalReferencia(Integer numeroNotaFiscalReferencia) {
		this.numeroNotaFiscalReferencia = numeroNotaFiscalReferencia;
	}

	public BigDecimal getValorTotalNotaFiscal() {
		return valorTotalNotaFiscal;
	}

	public void setValorTotalNotaFiscal(BigDecimal valorTotalNotaFiscal) {
		this.valorTotalNotaFiscal = valorTotalNotaFiscal;
	}

	public BigDecimal getPercentualADeduzir() {
		return percentualADeduzir;
	}

	public void setPercentualADeduzir(BigDecimal percentualADeduzir) {
		this.percentualADeduzir = percentualADeduzir;
	}

	public BigDecimal getValorADeduzir() {
		return valorADeduzir;
	}

	public void setValorADeduzir(BigDecimal valorADeduzir) {
		this.valorADeduzir = valorADeduzir;
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("DadosDeducao [tipoDeducao=");
		builder.append(tipoDeducao);
		builder.append(", cpf=");
		builder.append(cpf);
		builder.append(", cnpj=");
		builder.append(cnpj);
		builder.append(", numeroNotaFiscalReferencia=");
		builder.append(numeroNotaFiscalReferencia);
		builder.append(", valorTotalNotaFiscal=");
		builder.append(valorTotalNotaFiscal);
		builder.append(", percentualADeduzir=");
		builder.append(percentualADeduzir);
		builder.append(", valorADeduzir=");
		builder.append(valorADeduzir);
		builder.append("]");
		return builder.toString();
	}

}


text:
using System;
using HappyMapper.Benchmarks.Types;
using NUnit.Framework;

namespace HappyMapper.Tests.Tools
{
    public class ObjectComparer_Tests
    {
        [Test]
        public void AreEqual_EqualSimpleObjects_ReturnsTrue()
        {
            Src src = new Src();
            Dest dest = new Dest();

            dest.Name = src.Name;
            dest.Number = src.Number;
            dest.Float = src.Float;
            dest.DateTime = src.DateTime;

            var result = ObjectComparer.AreEqual(src, dest);

            result.Errors.ForEach(Console.WriteLine);

            Assert.IsTrue(result.Success);
            Assert.IsEmpty(result.Errors);
        }

        [Test]
        public void AreEqual_NotEqualSimpleObjects_ReturnsFalse()
        {
            Src src = new Src();
            Dest dest = new Dest();

            dest.Name = src.Name;
            dest.Number = src.Number;
            dest.Float = src.Float;
            dest.Float = src.Float + 0.1f;
            dest.DateTime = src.DateTime;

            var result = ObjectComparer.AreEqual(src, dest);

            result.Errors.ForEach(Console.WriteLine);

            Assert.IsFalse(result.Success);
            Assert.IsNotEmpty(result.Errors);
        }

        [Test]
        public void AreEqual_EqualNestedObjects_ReturnsTrue()
        {
            var src = new NestedSrc();
            var dest = new NestedDest();

            dest.Name = src.Name;
            dest.Number = src.Number;
            dest.Float = src.Float;
            dest.DateTime = src.DateTime;
            dest.Child.MyProperty = src.Child.MyProperty;
            dest.Child.GrandChild.Foo = src.Child.GrandChild.Foo;

            var result = ObjectComparer.AreEqual(src, dest);

            result.Errors.ForEach(Console.WriteLine);

            Assert.IsTrue(result.Success);
            Assert.IsEmpty(result.Errors);
        }

        [Test]
        public void AreEqual_NotEqualNestedObjects_ReturnsFalse()
        {
            var src = new NestedSrc();
            var dest = new NestedDest();

            dest.Name = src.Name;
            dest.Number = src.Number;
            dest.Float = src.Float;
            dest.DateTime = src.DateTime;
            dest.Child.MyProperty = src.Child.MyProperty - 42;

            var result = ObjectComparer.AreEqual(src, dest);

            result.Errors.ForEach(Console.WriteLine);

            Assert.IsFalse(result.Success);
            Assert.IsNotEmpty(result.Errors);
        }

    }
}


text:
package org.smof.parsers.metadata;

import java.util.List;

import org.bson.Document;
import org.smof.field.ParameterField;

@SuppressWarnings("javadoc")
public interface TypeBuilder<T> {

	void setTypes(TypeParser<?> parser);

	T build(Document document);

	List<ParameterField> getParams();

}


text:
require_relative '../../../puppet_x/puppetlabs/aws.rb'
require 'securerandom'

Puppet::Type.type(:route53_zone).provide(:v2, :parent => PuppetX::Puppetlabs::Aws) do
  confine feature: :aws

  mk_resource_methods

  def self.instances
    response = route53_client.list_hosted_zones()
    response.data.hosted_zones.collect do |zone|
      new({
        name: zone.name,
        ensure: :present,
      })
    end
  end

  def self.prefetch(resources)
    instances.each do |prov|
      if resource = resources[prov.name]
        resource.provider = prov
      end
    end
  end

  def exists?
    Puppet.info("Checking if zone #{name} exists")
    @property_hash[:ensure] == :present
  end

  def create
    reference = SecureRandom.hex
    Puppet.info("Creating zone #{name} with #{reference}")
    route53_client.create_hosted_zone(
      name: name,
      caller_reference: reference,
    )
    @property_hash[:ensure] = :present
  end

  def destroy
    Puppet.info("Deleting zone #{name}")
    zones = route53_client.list_hosted_zones.data.hosted_zones.select { |zone| zone.name == name }
    if zones
      zones.each do |zone|
        route53_client.delete_hosted_zone(id: zone.id)
      end
    end
    @property_hash[:ensure] = :absent
  end
end


text:
<link href="../build-output/css/sdk.css" type="text/css" rel="stylesheet"/>

OPEN CONSOLE TO SEE LOG MESSAGES


text:
<?php

namespace skeeks\cms\backend\actions;

use skeeks\cms\backend\BackendAction;
use skeeks\cms\helpers\RequestResponse;
use skeeks\sx\helpers\ResponseHelper;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

/**
 * @author Semenov Alexander <semenov@skeeks.com>
 */
class BackendModelMultiDeleteAction extends BackendModelMultiAction
{
    public function init()
    {
        ini_set('memory_limit', '2048M');

        if (!$this->icon)
        {
            $this->icon = "fa fa-trash";
        }

        if (!$this->confirm)
        {
            $this->confirm = \Yii::t('skeeks/backend', 'Are you sure you want to permanently delete the selected items?');
        }

        if (!$this->name)
        {
            $this->name = \Yii::t('skeeks/backend', "Delete");
        }

        if (!$this->priority)
        {
            $this->priority = 99999;
        }

        parent::init();
    }

    /**
     * @param $model
     * @return bool
     */
    public function eachExecute($model)
    {
        try
        {
            return $model->delete();
        } catch (\Exception $e)
        {
            return false;
        }
    }

}


text:
'use strict'

var functionNode = require('@node-red/nodes/core/function/10-function.js')
var injectNode = require('@node-red/nodes/core/common/20-inject.js')
var nodeUnderTest = require('../../src/modbus-response-filter.js')
var nodeIOConfig = require('../../src/modbus-io-config.js')
var clientNode = require('../../src/modbus-client.js')
var serverNode = require('../../src/modbus-server.js')
var flexGetterNode = require('../../src/modbus-flex-getter.js')

var helper = require('node-red-node-test-helper')
helper.init(require.resolve('node-red'))

describe('Response Filter node Testing', function () {
  before(function (done) {
    helper.startServer(function () {
      done()
    })
  })

  afterEach(function (done) {
    helper.unload().then(function () {
      done()
    }).catch(function () {
      done()
    })
  })

  after(function (done) {
    helper.stopServer(function () {
      done()
    })
  })

  describe('Node', function () {
    it('should be loaded', function (done) {
      helper.load([nodeUnderTest, nodeIOConfig], [
        {
          id: '50f41d03.d1eff4',
          type: 'modbus-response-filter',
          name: 'ModbusResponseFilter',
          filter: 'FilterTest',
          registers: 0,
          ioFile: '2f5a90d.bcaa1f',
          filterResponseBuffer: true,
          filterValues: true,
          filterInput: true,
          showStatusActivities: false,
          showErrors: false,
          wires: [[], []]
        },
        {
          id: '2f5a90d.bcaa1f',
          type: 'modbus-io-config',
          name: 'ModbusIOConfig',
          path: 'test',
          format: 'utf8',
          addressOffset: ''
        }
      ], function () {
        var modbusNode = helper.getNode('50f41d03.d1eff4')
        modbusNode.should.have.property('name', 'ModbusResponseFilter')
        modbusNode.should.have.property('filter', 'FilterTest')
        done()
      })
    })

    it('should be loaded and handle wrong input without crash', function (done) {
      helper.load([nodeUnderTest, nodeIOConfig], [
        {
          id: '50f41d03.d1eff4',
          type: 'modbus-response-filter',
          name: 'ModbusResponseFilter',
          filter: 'FilterTest',
          registers: 0,
          ioFile: '2f5a90d.bcaa1f',
          filterResponseBuffer: true,
          filterValues: true,
          filterInput: true,
          showStatusActivities: false,
          showErrors: false,
          wires: [[], []]
        },
        {
          id: '2f5a90d.bcaa1f',
          type: 'modbus-io-config',
          name: 'ModbusIOConfig',
          path: 'test',
          format: 'utf8',
          addressOffset: ''
        }
      ], function () {
        const modbusResponseFilter = helper.getNode('50f41d03.d1eff4')
        setTimeout(function () {
          modbusResponseFilter.receive({})
          done()
        }, 800)
      })
    })

    it('should stop on input with wrong count of registers', function (done) {
      helper.load([nodeUnderTest, nodeIOConfig], [
        {
          id: '50f41d03.d1eff4',
          type: 'modbus-response-filter',
          name: 'ModbusResponseFilter',
          filter: 'FilterTest',
          registers: 2,
          ioFile: '2f5a90d.bcaa1f',
          filterResponseBuffer: true,
          filterValues: true,
          filterInput: true,
          showStatusActivities: false,
          showErrors: false,
          wires: [[], []]
        },
        {
          id: '2f5a90d.bcaa1f',
          type: 'modbus-io-config',
          name: 'ModbusIOConfig',
          path: 'test',
          format: 'utf8',
          addressOffset: ''
        }
      ], function () {
        const modbusResponseFilter = helper.getNode('50f41d03.d1eff4')
        setTimeout(function () {
          modbusResponseFilter.receive({ payload: {}, registers: [0, 1, 0, 1] })
          done()
        }, 800)
      })
    })

    it('should work on input with exact count registers', function (done) {
      helper.load([nodeUnderTest, nodeIOConfig], [
        {
          id: '50f41d03.d1eff4',
          type: 'modbus-response-filter',
          name: 'ModbusResponseFilter',
          filter: 'FilterTest',
          registers: 4,
          ioFile: '2f5a90d.bcaa1f',
          filterResponseBuffer: true,
          filterValues: true,
          filterInput: true,
          showStatusActivities: false,
          showErrors: false,
          wires: [[], []]
        },
        {
          id: '2f5a90d.bcaa1f',
          type: 'modbus-io-config',
          name: 'ModbusIOConfig',
          path: 'test',
          format: 'utf8',
          addressOffset: ''
        }
      ], function () {
        const modbusResponseFilter = helper.getNode('50f41d03.d1eff4')
        setTimeout(function () {
          modbusResponseFilter.receive({ payload: {}, registers: [0, 1, 0, 1] })
          done()
        }, 800)
      })
    })

    it('should work with Flex Getter', function (done) {
      helper.load([injectNode, functionNode, clientNode, serverNode, flexGetterNode, nodeUnderTest, nodeIOConfig], [
        {
          id: '178284ea.5055ab',
          type: 'modbus-server',
          name: '',
          logEnabled: false,
          hostname: '',
          serverPort: '6502',
          responseDelay: '50',
          delayUnit: 'ms',
          coilsBufferSize: 1024,
          holdingBufferSize: 1024,
          inputBufferSize: 1024,
          discreteBufferSize: 1024,
          showErrors: false,
          wires: [
            [],
            [],
            [],
            []
          ]
        },
        {
          id: '29991a24.b64dfe',
          type: 'inject',
          name: 'Get flexible!',
          topic: '',
          payload: '',
          payloadType: 'date',
          repeat: '0.2',
          crontab: '',
          once: true,
          wires: [
            [
              '5cf6efb4.f62018'
            ]
          ]
        },
        {
          id: '5cf6efb4.f62018',
          type: 'function',
          name: '',
          func: "msg.payload = { input: msg.payload, 'fc': 4, 'unitid': 1, 'address': 0 , 'quantity': 30 }\nreturn msg;",
          outputs: 1,
          noerr: 0,
          wires: [
            [
              'c730e78b.3b8b5'
            ]
          ]
        },
        {
          id: 'c730e78b.3b8b5',
          type: 'modbus-flex-getter',
          name: '',
          showStatusActivities: false,
          showErrors: false,
          logIOActivities: false,
          server: '80aeec4c.0cb9e8',
          useIOFile: true,
          ioFile: '7417947e.da6c3c',
          useIOForPayload: true,
          wires: [
            [
              '5a7d9b84.a543a4'
            ],
            []
          ]
        },
        {
          id: '5a7d9b84.a543a4',
          type: 'modbus-response-filter',
          name: 'ModbusResponseFilter',
          filter: 'bOperationActive',
          registers: 0,
          ioFile: '7417947e.da6c3c',
          filterResponseBuffer: true,
          filterValues: true,
          filterInput: true,
          showStatusActivities: false,
          showErrors: false,
          wires: [
            [
              'h1'
            ]
          ]
        },
        { id: 'h1', type: 'helper' },
        {
          id: '80aeec4c.0cb9e8',
          type: 'modbus-client',
          name: 'Modbus Server',
          clienttype: 'tcp',
          bufferCommands: true,
          stateLogEnabled: false,
          tcpHost: '127.0.0.1',
          tcpPort: '6502',
          tcpType: 'DEFAULT',
          serialPort: '/dev/ttyUSB',
          serialType: 'RTU-BUFFERD',
          serialBaudrate: '9600',
          serialDatabits: '8',
          serialStopbits: '1',
          serialParity: 'none',
          serialConnectionDelay: '100',
          unit_id: '1',
          commandDelay: '1',
          clientTimeout: '100',
          reconnectTimeout: 200
        },
        {
          id: '7417947e.da6c3c',
          type: 'modbus-io-config',
          name: 'C3FactorySet',
          path: './test/nodes/resources/device.json',
          format: 'utf8',
          addressOffset: ''
        }
      ], function () {
        var modbusNode = helper.getNode('5a7d9b84.a543a4')
        modbusNode.should.have.property('name', 'ModbusResponseFilter')
        modbusNode.should.have.property('filter', 'bOperationActive')

        var h1 = helper.getNode('h1')
        h1.on('input', function () {
          done()
        })
      })
    })
  })

  describe('post', function () {
    it('should fail for invalid node', function (done) {
      helper.request().post('/modbus-reponse-filter/invalid').expect(404).end(done)
    })
  })
})


text:
/**
 * @file
 */
#include "src/expression/Member.hpp"

#include "src/visitor/all.hpp"

birch::Member::Member(Expression* left, Expression* right,
    Location* loc) :
    Expression(loc),
    Couple<Expression>(left, right) {
  //
}

bool birch::Member::isMembership() const {
  return true;
}

void birch::Member::accept(Visitor* visitor) const {
  return visitor->visit(this);
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using insticore;
using System.IO;
using System.Diagnostics;
using com.tikumo.regis3;
using Microsoft.Win32;

namespace instic
{
    class Program : IReportProgress
    {
        /*
         * - recognize if current installation has been modified
         * - revert to backup version
         * - create snapshot version
         * - switch to other version by first uninstalling, then installing new version
         */

        private string BaseDirectory;
        private string InstallationFile;
        private int MaxSnapshots;

        public Program()
        {
            var s = new instic.Properties.Settings();

            BaseDirectory = Environment.ExpandEnvironmentVariables(s.BaseDirectory);
            InstallationFile = Environment.ExpandEnvironmentVariables(s.InstallationFile);
            MaxSnapshots = s.MaxSnapshots;
        }

        private delegate bool HandlerMethod(ProjectDescription description, List<string> nextMethodArgs);

        public bool Run(string[] args)
        {
            Console.WriteLine("*** instic 1.0 - manage multiple ProAKT installations ***");
            Console.WriteLine();

            ProjectDescription description = ProjectDescription.FromFile(InstallationFile);
            if (description != null)
            {
                Console.WriteLine("Existing installation: {0}", description);
            }
            else
            {
                Console.WriteLine("Existing installation: - None -");
            }
            Console.WriteLine();

            HandlerMethod nextMethod = null;
            List<string> nextMethodArgs = new List<string>();

            foreach (string arg in args)
            {
                if (arg.Equals("/UNINSTALL", StringComparison.CurrentCultureIgnoreCase))
                {
                    nextMethod = Uninstall;
                }
                else if (arg.Equals("/BACKUP", StringComparison.CurrentCultureIgnoreCase))
                {
                    nextMethod = Backup;
                }
                else if (arg.Equals("/RESTORE", StringComparison.CurrentCultureIgnoreCase))
                {
                    nextMethod = Restore;
                }
                else if (arg.Equals("/SNAPSHOT", StringComparison.CurrentCultureIgnoreCase))
                {
                    nextMethod = Snapshot;
                }
                else if (arg.Equals("/REVERT", StringComparison.CurrentCultureIgnoreCase))
                {
                    nextMethod = Revert;
                }
                else if (arg.Equals("/?") || arg.Equals("/HELP", StringComparison.CurrentCultureIgnoreCase))
                {
                    return Help();
                }
                else if (nextMethod != null)
                {
                    nextMethodArgs.Add(arg);
                }
            }
            if( nextMethod != null )
            {
                return nextMethod(description, nextMethodArgs);
            }
            return ListInstallations(description);
        }

        private bool Backup(ProjectDescription description, List<string> args)
        {
            if( description == null )
            {
                // check to see if we can create a new backup from scratch
                if( args.Count == 1 )
                {
                    description = ProjectDescription.FromDefault(BaseDirectory, "", args[0]);
                }
                else if( args.Count == 2 )
                {
                    description = ProjectDescription.FromDefault(BaseDirectory, args[0], args[1]);
                }
                else
                {
                    Console.WriteLine("ERROR, cannot perform backup: installation.xml does not exist, and no archive name given.");
                    return false;
                }
                if( description == null )
                {
                    Console.WriteLine("ERROR, no default installation.xml exists in '{0}'", BaseDirectory);
                    return false;
                }
            }
            else
            {
                // maybe rename existing installation
                if (args.Count == 1)
                {
                    description.Archive = args[0];
                }
                else if (args.Count == 2)
                {
                    description.Description = args[0];
                    description.Archive = args[1];
                }
                else if( args.Count > 0)
                {
                    Console.WriteLine("ERROR, bad parameters for /BACKUP. Please consult your non-existing manual.");
                    return false;
                }
            }

            Trace.Assert(description != null);

            Console.WriteLine("Creating backup {0}", description);
            if( description.Backup(BaseDirectory, false, 0, this) )
            {
                Console.WriteLine("Done.");
                return true;
            }
            Console.WriteLine("Warning: unable to backup installation");
            return false;
        }

        private bool Snapshot(ProjectDescription description, List<string> args)
        {
            if (description == null)
            {
                Console.WriteLine("ERROR, no installation.xml exists: /SNAPSHOT is only possible for instic-installations");
                return false;
            }
            else if (args.Count != 0)
            {
                Console.WriteLine("ERROR, /SNAPSHOT has no arguments");
                return false;
            }

            Console.WriteLine("Creating snapshot {0}", description);
            if (description.Backup(BaseDirectory, true, MaxSnapshots, this))
            {
                Console.WriteLine("Done.");
                return true;
            }
            Console.WriteLine("Warning: unable to backup installation");
            return false;
        }

        private bool Uninstall(ProjectDescription description, List<string> args)
        {
            if (description != null)
            {
                Console.WriteLine("Removing {0}", description);
                if( description.Uninstall() )
                {
                    Console.WriteLine("Done.");
                    return true;
                }
                Console.WriteLine("Warning: unable to completely remove existing installation: please check manually");
                return false;
            }
            else
            {
                Console.WriteLine("Warning: no installation found: please check manually");
                return false;
            }
        }

        private bool Help()
        {
            Console.WriteLine("USAGE: instic [OPTIONS]");
            Console.WriteLine("OPTIONS:");
            Console.WriteLine("/BACKUP [name] .... create a backup with a new name");
            Console.WriteLine("/RESTORE <name> ... installed named version");
            Console.WriteLine("/UNINSTALL ........ uninstall existing installation");
            Console.WriteLine("/SNAPSHOT ......... create a new snapshot (max. NMAX snapshots)");
            Console.WriteLine("/REVERT [n] ....... revert to last-known-good (or snapshot)");
            return true;
        }

        private bool Restore(ProjectDescription description, List<string> args)
        {
            if( args.Count != 1 )
            {
                Console.WriteLine("Error: bad parameters for /RESTORE <name>");
                return false;
            }

            List<string> candidates = new List<string>();

            foreach (string file in Directory.GetFiles(BaseDirectory))
            {
                if (file.ToLower().Contains(args[0].ToLower()))
                {
                    candidates.Add(file);
                }
            }
            if (candidates.Count == 1)
            {
                return SwitchToThisOneInstallation(description, candidates[0]);
            }
            else if (candidates.Count > 1)
            {
                Console.WriteLine("Ambiguous specification. Possible matches are:");
                foreach (string candidate in candidates)
                {
                    Console.WriteLine(Path.GetFileName(candidate));
                }
            }
            else if (candidates.Count == 0)
            {
                Console.WriteLine("No match found. Possible candidates are:");
                ListInstallations(description);
            }
            return false;
        }

        private bool Revert(ProjectDescription description, List<string> args)
        {
            int nRevertIndex = 0;

            if (args.Count == 1)
            {
                nRevertIndex = int.Parse(args[0]);
            }
            else if(args.Count > 1)
            {
                Console.WriteLine("Error: bad parameters for /REVERT <name>");
                return false;
            }

            if (description == null)
            {
                Console.WriteLine("ERROR, no installation.xml exists: /REVERT is only possible for instic-installations");
                return false;
            }

            string snapshotFilename;
            if( !description.IsValidSnapshotIndex(BaseDirectory, nRevertIndex, out snapshotFilename))
            {
                Console.WriteLine("ERROR, {0} is not an existing snapshot index", nRevertIndex);
                return false;
            }

            Console.WriteLine("Removing existing installation");
            description.Uninstall();

            Console.WriteLine("Reverting back to snapshot #{0}", nRevertIndex);
            return ProjectDescription.FromArchive(snapshotFilename).Restore(BaseDirectory, InstallationFile);
        }

        private bool SwitchToThisOneInstallation(ProjectDescription description, string name, int nRevertIndex = -1)
        {
            if( description != null )
            {
                Console.WriteLine("Removing this: {0}", description);
                description.Uninstall();
            }
            Console.WriteLine("Restoring this: {0}", name);
            return ProjectDescription.FromArchive(name).Restore(BaseDirectory, InstallationFile);
        }

        private bool ListInstallations(ProjectDescription description)
        {

            foreach (string file in Directory.GetFiles(BaseDirectory))
            {
                Console.WriteLine(Path.GetFileName(file));
            }
            return false;
        }

        static void Main(string[] args)
        {
            new Program().Run(args);
        }

        public void ShowText(string message)
        {
            Console.WriteLine(message);
        }
    }
}


text:
void GameManager::Update(float dt)
{
	if (entitesSize != GameEntities.size() || entitesSize == -1 || gameObjectsSize != GameObjects->size() || activeScene->ObjectsDirty)
	{
		EntitiesDirty = true;
		activeScene->ObjectsDirty = false;
		GameEntities.clear();
	}
	for (int i = 0; i < GameObjects->size(); i++)
	{
		if (GameObjects->at(i)->ToDelete == true)
		{
			delete GameObjects->at(i);
			GameObjects->erase(GameObjects->begin() + i);
			i--;
			continue;
		}
		GameObjects->at(i)->Update(dt);
		std::vector<Component*>* objectComponents = &GameObjects->at(i)->components;
		for (int p = 0; p < objectComponents->size(); p++)
		{
			objectComponents->at(p)->Update(dt);
		}
		if (EntitiesDirty == true && GameObjects->at(i)->entity != nullptr)
		{
			GameEntities.push_back(GameObjects->at(i)->entity);
		}
	}
	for (int i = 0; i < activeScene->ParticleEmitters.size(); i++)
	{
		if (activeScene->ParticleEmitters.at(i)->dead)
		{
			delete activeScene->ParticleEmitters.at(i);
			activeScene->ParticleEmitters.erase(activeScene->ParticleEmitters.begin() + i);
			i--;
		}
	}

	if (activeScene)
	{
		activeScene->Update();
	}
	gameObjectsSize = GameObjects->size();
	entitesSize = GameEntities.size();
}

void GameManager::SetActiveScene(Scene * nextScene)
{
	if (activeScene)
	{
		activeScene->End();
		delete activeScene;
	}

	activeScene = nextScene;
	activeScene->Initialize();
	GameObjects = &activeScene->GameObjects;
	GameEntities.clear();
	EntitiesDirty			= true;
	DirectionalLightsDirty	= true;
	PointLightsDirty		= true;
	ParticleEmittersDirty	= true;
	entitesSize = -1;
	gameObjectsSize = -1;
}

GameManager::GameManager()
{
	EntitiesDirty			= true;
	DirectionalLightsDirty = true;
	PointLightsDirty = true;
	ParticleEmittersDirty = true;
	entitesSize = -1;
	gameObjectsSize = -1;
}

GameManager::~GameManager()
{
	delete activeScene;
}


text:
package com.togocms.pns;

import java.util.List;

import com.caucho.hessian.client.HessianProxyFactory;
import com.togocms.pns.api.PushNotificationService;

public class PushNotification {
	private PushNotificationService service;
	private String apiKey;
	private String title;
	private String alert;
	private Long id;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public PushNotification(String apiKey) throws Exception {
		this(apiKey, "http://pns.togocms.com/pns-service.app");
	}

	public PushNotification(String apiKey, String serverUrl) throws Exception {
		this.apiKey = apiKey;
		this.service = (PushNotificationService) new HessianProxyFactory().create(PushNotificationService.class, serverUrl);
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getAlert() {
		return alert;
	}

	public void setAlert(String alert) {
		this.alert = alert;
	}

	public Long sendBroadcast() throws Exception {
		com.togocms.pns.api.PushNotification notification = setup();
		service.sendBroadcastNotification(apiKey, notification);
		return getId();
	}

	public Long sendGroup(List<Long> ids) throws Exception {
		com.togocms.pns.api.PushNotification notification = setup();
		service.sendGroupNotification(apiKey, notification, ids);
		return getId();
	}

	public Long send(Long id) throws Exception {
		com.togocms.pns.api.PushNotification notification = setup();
		service.sendNotification(apiKey, notification, id);
		return getId();
	}

	private com.togocms.pns.api.PushNotification setup() {
		com.togocms.pns.api.PushNotification notification = new com.togocms.pns.api.PushNotification();
		notification.setTitle(getTitle());
		notification.setAlert(getAlert());
		return notification;
	}
}


text: RSpotify::authenticate(ENV["spotify_client_id"], ENV["spotify_secret"])


text:
include('const.js');
include('utils.js');
include('dom.js');
include('geometry.js');
include('view/observable.js');

(function() {

    var self = uki.Attachment = uki.newClass(uki.view.Observable, /** @lends uki.Attachment.prototype */ {
        /**
         * Attachment serves as a connection between a uki view and a dom container.
         * It notifies its view with parentResized on window resize.
         * Attachment supports part of uki.view.Base API like #domForChild or #rectForChild
         *
         * @param {Element} dom Container element
         * @param {uki.view.Base} view Attached view
         * @param {uki.geometry.Rect} rect Initial size
         *
         * @see uki.view.Base#parentResized
         * @name uki.Attachment
         * @base uki.view.Observable
         * @constructor
         */
        init: function( dom, view, rect ) {
            uki.initNativeLayout();

            this._dom     = dom = dom || root;
            this._view    = view;
            this._rect = Rect.create(rect) || this.rect();

            uki.dom.offset.initialize();

            view.parent(this);

            if (dom != root && dom.tagName != 'BODY') {
                var computedStyle = dom.runtimeStyle || dom.ownerDocument.defaultView.getComputedStyle(dom, null);
                if (!computedStyle.position || computedStyle.position == 'static') dom.style.position = 'relative';
            }
            self.register(this);

            this.layout();
        },

        /**
         * Returns document.body if attached to window. Otherwise returns dom
         * uki.view.Base api
         *
         * @type Element
         */
        domForChild: function() {
            return this._dom === root ? doc.body : this._dom;
        },

        /**
         * uki.view.Base api
         *
         * @type uki.geometry.Rect
         */
        rectForChild: function(child) {
            return this.rect();
        },

        /**
         * uki.view.Base api
         */
        scroll: function() {
            // TODO: support window scrolling
        },

        /**
         * uki.view.Base api
         */
        scrollTop: function() {
            // TODO: support window scrolling
            return this._dom.scrollTop || 0;
        },

        /**
         * uki.view.Base api
         */
        scrollLeft: function() {
            // TODO: support window scrolling
            return this._dom.scrollLeft || 0;
        },

        /**
         * uki.view.Base api
         */
        parent: function() {
            return null;
        },

        /**
         * On window resize resizes and laysout its child view
         */
        layout: function() {
            var oldRect = this._rect;

            // if (rect.eq(this._rect)) return;
            this._rect = this.rect();

            this._view.parentResized(oldRect, this._rect);
            if (this._view._needsLayout) this._view.layout();
            this.trigger('layout', {source: this, rect: this._rect});
        },

        /**
         * @return {Element} Container dom
         */
        dom: function() {
            return this._dom;
        },

        /**
         * @return {Element} Child view
         */
        view: function() {
            return this._view;
        },

        /**
         * @private
         * @return {uki.geometry.Rect} Size of the container
         */
        rect: function() {
            var width = this._dom === root || this._dom === doc.body ? MAX(getRootElement().clientWidth, this._dom.offsetWidth || 0) : this._dom.offsetWidth,
                height = this._dom === root || this._dom === doc.body ? MAX(getRootElement().clientHeight, this._dom.offsetHeight || 0) : this._dom.offsetHeight;

            return new Rect(width, height);
        }
    });

    function getRootElement() {
        return doc.compatMode == "CSS1Compat" && doc.documentElement || doc.body;
    }

    self.instances = [];

    self.register = function(a) {
        if (self.instances.length == 0) {
            uki.dom.bind(root, 'resize', function() {
                uki.each(self.instances, function() { this.layout(); });
            });
        }
        self.instances.push(a);
    };

    self.childViews = function() {
        return uki.map(self.instances, 'view');
    };

    uki.top = function() {
        return [self];
    };
})();


text:
layout: post
title: "Confessions of a Technical Lead"
date: 2017-02-21
categories: [general]
tags: [leadership]
---

One question I inevitably get no matter what team I'm on is "What is your job as a tech lead?"
![What would you say you do here?]({{ "/assets/posts/images/meme_bobs.jpg" | absolute_url }})

My default answer is, "I burp the manager" which is usually followed by either a smile or a puzzled look.  When one of my junior developers recently
asked me this it got me thinking, how would I describe my job? Well, I figured why not break it down.

## What is a tech lead?
The answer varies depending on who you ask but I like to think that a tech lead can be loosely defined as

`Tech Lead = Leader + Developer + Architect`

As a leader you must... lead your team.  Leading a team is a very broad statement and can be difficult to pin down what exactly that means but that's
leadership.  As a leader you manage conflict, build relationships, work with and guide the business, and keep the train running.  And that's just the
tip of the iceberg.

As a developer you need to be hands on, aware of best practices, set the technical approaches, and help answer questions.  It's your job to help build
the product/project and tell the stupid computer what it needs to do.  There's also the less glamorous side of coding like documentation, dependency
management, and CICD pipelines.

As an architect you have to be aware of the big picture and think about non-technical requirements.  How does the product/project fit in the long term
journey?  What are the integration touch points?  How can the product be deployed and maintained?  What are the technical, legal, and business risks
involved?  Like leadership this is but the tip of the iceberg.

## Do you code as a tech lead?
As much as possible!  However you need to put the team's need first.  As a tech lead it's your responsibility to mend relationships with other teams,
prepare upcoming work, and do the "non-technical" stuff that keeps the team running.  The challenge is to be up to date with the technical challenges
that your team is facing and keep your skill sharp.

## Is it meeting hell?
It ebbs and flows but you *must* make it a priority to code and be with your team!  Some days (weeks?) are nothing but meetings, others are nothing but
hands on keyboard.  You need to assess your team and determine how long you can be away and who you can delegate to.

## What leadership style is the best?
This is probably the hardest question to answer because it really just depends on you and your team.  A strong overbearing leader on a team that has
been beaten down will destroy what moral the team has.  In contrast, a happy go lucky leader will quickly run into cowboy and sprawl problems and lose
any perceived influence if not careful.  TLDR, it's a lot like parenting;  give your team just enough rope to mature and make the right decisions but
be firm and put the guardrails back up when needed.

## Do you tailor your style to the person you're working with?
Absolutely yes.  As a tech lead you need to know how to reach your team.  Some people just need you to coach them and be supportive.  Others need a lot
of hand holding and clear/concise direction.

## Do you have to be the "best" developer to be a tech lead?
No.  There's always someone better than you, deal with it.  You do need to know when things are being over engineered and when good enough is all you need.

## What do you mean "burp the manager"?
As a tech lead you play many roles.  You're the voice of reason that talks business of the ledge.  You're the one that stay positive when things are down.
"Burping the manager" is just a sarcastic way to say "it will be ok".

I'm only scratching the surface of what being a tech lead is like.  You wear many hats and it's not the most glamorous of jobs at times but it can be a
very rewarding position.  Be the rock your team needs.


text:
class Api::LtiContentItemSelectionController < Api::ApiApplicationController

  include ContentItemSupport
  # ###########################################################
  # Used to generate a content item selection response
  def create
    render json: generate_content_item_data("fake_id", params[:content_item_return_url], params[:content_item])
  end

end


text:
#ifndef UNFACT_TREE_SET_HPP
#define UNFACT_TREE_SET_HPP

#include <unfact/base.hpp>
#include <unfact/arena.hpp>
#include <unfact/algorithm.hpp>
#include <unfact/red_black.hpp>

UNFACT_NAMESPACE_BEGIN

/*
 * tree_set_t is a std::set-like generic collection based on red_black_t.
 * API does not align STL style.
 * it is not intentional, but jusr short of effort. we welcome your contribution ;-)
 *
 * for ordering criteria, see the comment for red_black_t.
 *
 * WARNING:
 * tree_set_t returns non-const iterator for your convenience.
 * but such iterators give you the way to modify item on the container.
 * changing item can cause ORDER INCONSISTENCY for the set, so you should do it carefully.
 */

/*
 * tree_set_skeleton_t is a helper class to implement tree_set_t and its variant.
 * tree_set_skeleton_t has only root node, but does not have sharable elements,
 * including arena and comparator.
 *
 */
template<class Key, class Comparator=less_t<Key>, class Subclass=none_t,
				 class Concurrent=null_concurrent_t>
class tree_set_skeleton_t
{
public:
	typedef Concurrent concurrent_type;
	typedef typename concurrent_type::spin_lock_type lock_type;
	typedef basic_arena_t<concurrent_type> arena_type;
  typedef tree_set_skeleton_t self_type;
  typedef Key key_type;
  typedef Comparator comparator_type;
  typedef Subclass subclass_type;
  typedef typename red_black_t<key_type, comparator_type, subclass_type>::self_type node_type;
  typedef typename node_type::removal_unbalance_t removal_unbalance_type;
  typedef red_black_dfs_iterator_t<key_type, comparator_type, subclass_type> dfs_iterator_type;
  typedef node_type item_type;

  class const_iterator_t : public red_black_iterator_base_t<const_iterator_t,
																														key_type, comparator_type, subclass_type>
  {
  public:
		typedef red_black_iterator_base_t<const_iterator_t, key_type, comparator_type, subclass_type> base_type;
		typedef const typename node_type::key_type  value_type;
		typedef const typename node_type::key_type* pointer_type;

		explicit const_iterator_t(node_type* n=0) : base_type(n) {}
		value_type& operator*() const { return base_type::node()->key(); }
		pointer_type operator->() const { return &(base_type::node()->key()); }
  };

  class iterator_t : public red_black_iterator_base_t<iterator_t,
																											key_type, comparator_type, subclass_type>
  {
  public:
		typedef red_black_iterator_base_t<iterator_t, key_type, comparator_type, subclass_type> base_type;
		typedef typename node_type::key_type  value_type;
		typedef typename node_type::key_type* pointer_type;

		iterator_t() : base_type(0) {}
		explicit iterator_t(node_type* n) : base_type(n) {}

		value_type& operator*() const { return base_type::node()->key(); }
		pointer_type operator->() const { return &(base_type::node()->key()); }

		// down covnertion
		operator const_iterator_t() const { return const_iterator_t(base_type::node()); }
  };

	template<class Synchronized>
  iterator_t begin(const Synchronized& sync) { return iterator_t(begin_node(sync)); }
  iterator_t begin() { return begin(synchronized_t()); }
	template<class Synchronized>
  const_iterator_t begin(const Synchronized& sync) const { return const_iterator_t(begin_node(sync)); }
  const_iterator_t begin() const { return begin(synchronized_t()); }
	template<class Synchronized>
  iterator_t end(const Synchronized&) { return iterator_t(0); }
  iterator_t end() { return end(synchronized_t()); }
	template<class Synchronized>
  const_iterator_t end(const Synchronized&) const { return const_iterator_t(0); }
  const_iterator_t end() const { return end(synchronized_t()); }
	template<class Synchronized>
  dfs_iterator_type dfs_begin(const Synchronized& sync) const { return dfs_iterator_type(root(sync)); }
  dfs_iterator_type dfs_begin() const { return dfs_begin(synchronized_t()); }
	template<class Synchronized>
  dfs_iterator_type dfs_end(const Synchronized&) const { return dfs_iterator_type(0); }
  dfs_iterator_type dfs_end() const { return dfs_end(synchronized_t()); }

  template<class FindKey, class Synchronized>
  const_iterator_t find(const comparator_type& compare, const FindKey& k, const Synchronized& sync) const { return const_iterator_t(find_node(compare, k, sync)); }
  template<class FindKey>
  const_iterator_t find(const comparator_type& compare, const FindKey& k) const { return find(compare, k, synchronized_t()); }
  template<class FindKey, class Synchronized>
  iterator_t find(const comparator_type& compare, const FindKey& k, const Synchronized& sync) { return iterator_t(find_node(compare, k, sync)); }
  template<class FindKey>
  iterator_t find(const comparator_type& compare, const FindKey& k) { return find(compare, k, synchronized_t()); }

  /*
   * @return end() when there is already same key
   *         or iterator that points inserted key
   */
	template<class NewKey, class Synchronized>
  iterator_t insert(arena_type* arena, const comparator_type& compare, const NewKey& key,
										const Synchronized& sync)
  {
		node_type* toins = new_node(arena, key);
		UF_ALERT_AND_RETURN_UNLESS(toins, iterator_t(0), "failed to allocate new node!");

		iterator_t ret = insert_node(compare, toins, sync);
		if (ret.atend()) {
			delete_node(arena, toins);
		}

		return ret;
  }

	template<class NewKey>
  iterator_t insert(arena_type* arena, const comparator_type& compare, const NewKey& key)
	{
		return insert(arena, compare, key, synchronized_t());
	}

  /*
   * remove node pointed by the iterator.
   * the iterator "i" goes invalid after removal.
   */
  template<class Iterator, class Synchronized> // Iterator should be iterator_t or const_iterator_t
  void remove(arena_type* arena, Iterator i, const Synchronized& sync)
  {
		if (i.atend()) {
			return;
		}

		remove_node(i.node(), sync);
		delete_node(arena, i.node());
  }

  template<class Iterator>
  void remove(arena_type* arena, Iterator i)
	{
		remove(arena, i, synchronized_t());
	}

  /*
   * same as insert(), except this method returns existing iterator instead of end() iter
   * when specified key is already inserted.
   */
	template<class NewKey, class Synchronized>
  iterator_t ensure(arena_type* arena, const comparator_type& compare, const NewKey& key,
										const Synchronized& sync)
  {
		iterator_t found = end(sync);
		while (found.atend()) {
			iterator_t found = find(compare, key, sync);
			if (found.good()) {
				return found;
			}

			node_type* toins = new_node(arena, key);
			UF_ALERT_AND_RETURN_UNLESS(toins, iterator_t(0), "failed to allocate new node!");
			iterator_t ret = insert_node(compare, toins, sync);
			if (ret.atend()) {
				/*
				 * another thread have already inserted same node:
				 * so we remove ours and retry find again.
				 */
				delete_node(arena, toins);
			}
		}

		return found;
  }

	template<class NewKey>
  iterator_t ensure(arena_type* arena, const comparator_type& compare, const NewKey& key)
	{
		return ensure(arena, compare, key, synchronized_t());
	}

  template<class Iterator>
  void insert(arena_type* arena, const comparator_type& compare, Iterator beg, Iterator end)
  {
		for (Iterator i=beg; i!=end; ++i) {
			iterator_t inserted = insert(arena, compare, *i);
			UF_HONOR_OR_RETURN_VOID(!inserted.atend());
		}
  }

	/*
	 * CAUTION:
	 * clear() semantics goes complicated on concurrent world.
	 * our policy following:
	 * - during clear() is called, no other threads enver call neither remove() nor clear().
	 *   because all existing iterators go invalid.
	 * - insert() is OK. iserted nodes are live after clear()
	 */
  void clear(arena_type* arena)
  {
		node_type* old_root = pop_root();
		if (!old_root) {
			return;
		}

		removal_unbalance_type unb;
		for (dfs_iterator_type i = dfs_iterator_type(old_root), end = dfs_iterator_type(0); i != end; /* */) {
			dfs_iterator_type toremove = i++;
			node_type::remove_unbalanced(old_root, toremove.node(), &unb);
			delete_node(arena, toremove.node());
		}
  }

	template<class Synchronized>
  bool invariant(const Synchronized&) const
	{
		lock_scope_t<const self_type, Synchronized> l(this);
		return (0 == m_root) || m_root->invariant();
	}

	bool invariant() const { return invariant(synchronized_t()); }

	template<class Synchronized>
  bool empty(const Synchronized&) const { return 0 == lock_scope_t<const self_type, synchronized_t>(this)->m_root; }
	bool empty() const { return empty(synchronized_t()); }

	template<class Synchronized>
  size_t count(const Synchronized&) const
	{
		lock_scope_t<const self_type, synchronized_t> l(this);
		return m_root ? m_root->size() : 0;
	}

	size_t count() const { return count(synchronized_t()); }

	template<class Synchronized>
	node_type* root(const Synchronized&) const { return lock_scope_t<const self_type, Synchronized>(this)->m_root; }
  node_type* root() const { return root(synchronized_t()); }

	void acquire() const { m_lock.acquire(); }
	void release() const { m_lock.release(); }

  tree_set_skeleton_t()	: m_root(0) {}

  ~tree_set_skeleton_t()
  {
		/*
		 * all nodes should be released before destruction.
		 * it is user's responsibility
		 */
		UF_ASSERT(!m_root);
  }

	template<class Synchronized>
	void exchange(tree_set_skeleton_t& that, const Synchronized&)
	{
		if (this == &that)  { return; } // ESSENTIAL: deadlock in such case
		lock_scope_t<self_type, Synchronized> lo(&that);
		lock_scope_t<self_type, Synchronized> lt(this);
		unfact::exchange(m_root, that.m_root);
	}

	void exchange(tree_set_skeleton_t& that) { exchange(synchronized_t()); }

public: // impelemntation detail

	template<class Synchronized>
  node_type* begin_node(const Synchronized&) const
	{
		lock_scope_t<const self_type, Synchronized> l(this);
		return m_root ? m_root->minimum() : 0;
	}

  node_type* begin_node() const { begin_node(synchronized_t()); }

	template<class Synchronized>
	node_type* pop_root(const Synchronized&)
	{
		lock_scope_t<const self_type, Synchronized> l(this);
		node_type* ret = m_root;
		m_root = 0;
		return ret;
	}

	node_type* pop_root()	{ return pop_root(synchronized_t()); }

	template<class Synchronized>
  iterator_t insert_node(const comparator_type& compare, node_type* node, const Synchronized&)
	{
		lock_scope_t<const self_type, Synchronized> l(this);

		if (!m_root) {
			node->set_black();
			m_root = node;
			return iterator_t(node);
		}

		bool ok = node_type::insert(m_root, node, &m_root, compare);
		if (!ok) {
			return end();
		}

		return iterator_t(node);
	}

  iterator_t insert_node(const comparator_type& compare, node_type* node)
	{
		return insert_node(compare, node, synchronized_t());
	}

	template<class Synchronized>
  void remove_node(node_type* node, const Synchronized&)
	{
		lock_scope_t<const self_type, Synchronized> l(this);
		/* NOTE:
		 * non-null root assumption is OK even in concurrent world.
		 * Because we should have at least one node if we have node to remove.
		 */
		UF_ASSERT(m_root);
		node_type::remove(m_root, node, &m_root);
	}

	void remove_node(node_type* node) { remove_node(node, synchronized_t()); }

  template<class FindKey, class Synchronized>
  node_type* find_node(const comparator_type& compare, const FindKey& k, const Synchronized&) const
  {
		lock_scope_t<const self_type, Synchronized> l(this);
		return (m_root ? const_cast<node_type*>(m_root->find(k, compare)) : 0);
  }

  template<class FindKey>
  node_type* find_node(const comparator_type& compare, const FindKey& k) const
	{
		return find_node(compare, k, synchronized_t());
	}

  void delete_node(arena_type* arena, node_type* node)
  {
		node->~node_type();
		arena->deallocate(reinterpret_cast<byte_t*>(node));
  }

	template<class NewKey>
  node_type* new_node(arena_type* arena, const NewKey& key)
  {
		void* mem = arena->allocate();
		UF_ALERT_AND_RETURN_UNLESS(mem, 0, "faile to allocate memory for new node!");
		return new (mem) node_type(key);
  }

private:
  tree_set_skeleton_t(const tree_set_skeleton_t&);
  tree_set_skeleton_t& operator=(tree_set_skeleton_t&);
private:
	mutable lock_type  m_lock;
  node_type* m_root;
};

/*
 * tree_set_t is a self-contained container.
 * actual API implementation is done by tree_set_skeleton_t,
 * so tree_set_t is just a aggregation of its building blocks like arena and comparator
 */
template<class Key, class Comparator=less_t<Key>, class Concurrent=null_concurrent_t>
class tree_set_t
{
public:
  typedef tree_set_t self_type;
  typedef Key key_type;
  typedef Comparator comparator_type;
	typedef Concurrent concurrent_type;
	typedef basic_arena_t<concurrent_type> arena_type;
  typedef tree_set_skeleton_t<key_type, comparator_type, none_t, concurrent_type> skeleton_type;
  typedef typename skeleton_type::iterator_t iterator;
  typedef typename skeleton_type::const_iterator_t const_iterator;
	typedef typename skeleton_type::item_type item_type;

  iterator begin() { return m_skeleton.begin(); }
  const_iterator begin() const { return m_skeleton.begin(); }
  iterator end() { return m_skeleton.end(); }
  const_iterator end() const { return m_skeleton.end(); }

  template<class FindKey>
  const_iterator find(const FindKey& k) const { return m_skeleton.find(m_compare, k); }
  template<class FindKey>
  iterator find(const FindKey& k) { return m_skeleton.find(m_compare, k); }

  template<class FindKey>
  bool contains(const FindKey& k) const { return end() != find(k); } /* thread-safe: end() is stateless*/

  template<class Iterator>
  void remove(Iterator i) { m_skeleton.remove(&m_arena, i); }
	template<class NewKey>
  iterator insert(const NewKey& key) { return m_skeleton.insert(&m_arena, m_compare, key);  }
	template<class NewKey>
  iterator ensure(const NewKey& key) { return m_skeleton.ensure(&m_arena, m_compare, key);  }
  template<class Iterator>
  void insert(Iterator beg, Iterator end) { return m_skeleton.insert(&m_arena, m_compare, beg, end); }
  void clear() { m_skeleton.clear(&m_arena); }
  bool empty() const { return m_skeleton.empty(); }
  size_t size() const { return m_arena.size(); }

	void acquire() const { m_skeleton.acquire(); }
	void release() const { m_skeleton.release(); }

  explicit tree_set_t(allocator_t* allocator, size_t page_size=DEFAULT_PAGE_SIZE, const comparator_type& compare=less_t<key_type>())
		: m_arena(allocator, sizeof(item_type), page_size), m_compare(compare) {}

  ~tree_set_t() { clear(); }

  tree_set_t(const tree_set_t& other)
		: m_arena(other.m_arena.allocator(), sizeof(item_type), other.m_arena.page_size()),
			m_compare(other.m_compare)
  {
		insert(other.begin(), other.end());
  }

  tree_set_t& operator=(const tree_set_t& other)
  {
		tree_set_t other_copy = other;
		other_copy.exchange(*this);
		return *this;
  }

	template<class Synchronized>
  void exchange(tree_set_t& other, const Synchronized& sync)
  {
		if (this == &other)  { return; } // ESSENTIAL: deadlock in such case

		m_arena.exchange(other.m_arena, sync);
		m_skeleton.exchange(other.m_skeleton, sync);
		lock_scope_t<self_type, Synchronized> tl(this);
		lock_scope_t<self_type, Synchronized> ol(&other);
		unfact::exchange(m_compare, other.m_compare);
  }

  void exchange(tree_set_t& other) { exchange(other, synchronized_t()); }

  bool invariant() const { return m_skeleton.invariant(); }
  allocator_t* allocator() const { return m_arena.allocator(); }

public: // implementation detail: export just for testing and debuggin

	template<class Synchronized>
  size_t count(const Synchronized& sync) const
	{
		size_t n = m_skeleton.count(sync);
		size_t m = m_arena.size(sync);
		UF_ASSERT(n == m);
		return n;
	}

  size_t count() const { return count(synchronized_t()); }

private:
  arena_type m_arena;
  comparator_type m_compare;
  skeleton_type m_skeleton;
};

UNFACT_NAMESPACE_END

#endif//UNFACT_TREE_SET_HPP

/* -*-
	 Local Variables:
	 mode: c++
	 c-tab-always-indent: t
	 c-indent-level: 2
	 c-basic-offset: 2
	 tab-width: 2
	 End:
	 -*- */


text:
<?php

namespace RedLocker;

class Lock
{
	protected $manager;

	public $resource;
	public $token;
	public $n = 0;
	public $expiry;

	public function __construct(LockManager $manager, $resource)
	{
		$this->manager  = $manager;
		$this->resource = $resource;
		$this->token    = mt_rand();
	}

	public function release()
	{
		return $this->manager->unlock($this);
	}
}

// end of script


text:
import * as React from "react";
import * as ReactDOM from "react-dom";
import { Context, Dispatcher } from "almin";
import AlminReactContainer from "almin-react-container";
import { appStoreGroup, debuggable } from "./store/AppStoreGroup";
import { appLocator } from "./AppLocator";
import { AppContainer } from "./component/container/AppContainer";
import localForage from "localforage";
import { createSystemReadyToLaunchAppUseCase } from "./use-case/System/SystemReadyToLaunchAppUseCase";
import { createReloadAllStreamUseCase } from "./use-case/GitHubSearchStream/ReloadAllStreamUseCase";
import { runDOMBootstrap } from "./bootstrap";
import { AlminLogger } from "almin-logger";
import { initializeIcons } from "@uifabric/icons";
import { createAppUserOpenItemUseCase } from "./use-case/App/AppUserOpenItemUseCase";

function allRequire(context: any) {
    context.keys().forEach(context);
}

allRequire((require as any).context("./", true, /\.css$/));

initializeIcons();
// instances
const dispatcher = new Dispatcher();
// context connect dispatch with stores
const context = new Context({
    dispatcher,
    store: appStoreGroup,
    options: {
        strict: true,
        performanceProfile: process.env.NODE_ENV !== "production"
    }
});
// setup localForage
localForage.config({
    name: "Faao"
});
if (process.env.NODE_ENV !== "production") {
    (window as any)["alminContext"] = context;
    const logger = new AlminLogger();
    logger.startLogging(context);
    // enable debug mode
    debuggable();
}
// set context to a single object.
appLocator.context = context;
// initialize
runDOMBootstrap();
// start render
const AppWrapContainer = AlminReactContainer.create(AppContainer, context);
ReactDOM.render(<AppWrapContainer />, document.getElementById("js-app"), async () => {
    // render and restore repositories
    await context.useCase(createSystemReadyToLaunchAppUseCase()).execute();
    // re-open last item
    const lastActiveItem = context.getState().app.activeItem;
    if (lastActiveItem) {
        await context.useCase(createAppUserOpenItemUseCase()).execute(lastActiveItem);
    }
    // reload all stream at first
    await context.useCase(createReloadAllStreamUseCase()).execute();
});


text:
{% extends 'layouts/default.html' %}
{% import 'helpers/render.html' as render %}

{% set page_title = 'Gateways' %}
{% set new_title = 'New Gateway' %}
{% set new_url = url_for('.gateways_new') %}

{% set show_network = current_user.has_role('super-admin') %}

{% block content %}

        {% if instances %}

                        {% if show_network %}
                            Network
                        {% endif %}
                        ID
                        Title
                        Created At

                        Actions

                    {% for instance in instances %}

                            {% if show_network %}
                                {{ render.render(instance.network) }}
                            {% endif %}
                            {{ instance.id }}
                            {{ render.render(instance.title) }}
                            {{ render.datetime(instance.created_at) }}

                                    Delete

                    {% endfor %}

        {% endif %}

{% endblock %}


text:
/*
Determine the configuration file to load by examining the
NODE_ENV environment variable.
*/

// Default environment is 'development'.
var envName = process.env.NODE_ENV || 'development';

var envConfigPath = './env/' + envName + '.js';

module.exports = require(envConfigPath);


text:
@interface GREYDispatchQueueIdlingResourceTest : GREYBaseTest
@end

@implementation GREYDispatchQueueIdlingResourceTest

- (void)testQueueName {
  NSString *queueName = @"queueName";
  dispatch_queue_t queue =
      dispatch_queue_create("GREYDispatchQueueIdlingResourceTest", DISPATCH_QUEUE_SERIAL);

  GREYDispatchQueueIdlingResource *idlingRes =
      [GREYDispatchQueueIdlingResource resourceWithDispatchQueue:queue
                                                            name:queueName];
  XCTAssertEqual(queueName, [idlingRes idlingResourceName], @"Name differs");
}

- (void)testIdlingResourceWeaklyHoldsQueueAndDeregistersItselfAfterOperationsHaveCompleted {
  GREYDispatchQueueIdlingResource *dispatchQueueIdlingResource;
  GREYUIThreadExecutor *sharedThreadExecutor = [GREYUIThreadExecutor sharedInstance];
  XCTestExpectation *expectation = [self expectationWithDescription:@"Async block fired"];
  dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

  @autoreleasepool {
    __autoreleasing dispatch_queue_t queue =
        dispatch_queue_create("GREYDispatchQueueIdlingResourceTestDealloc", DISPATCH_QUEUE_SERIAL);

    dispatchQueueIdlingResource =
        [GREYDispatchQueueIdlingResource resourceWithDispatchQueue:queue
                                                              name:@"test"];
    [[GREYUIThreadExecutor sharedInstance] registerIdlingResource:dispatchQueueIdlingResource];
    XCTAssertTrue([sharedThreadExecutor grey_isTrackingIdlingResource:dispatchQueueIdlingResource]);

    dispatch_async(queue, ^{
      dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC));
      dispatch_semaphore_wait(semaphore, timeout);
      [expectation fulfill];
    });
  }
  XCTAssertFalse([dispatchQueueIdlingResource isIdleNow]);
  XCTAssertTrue([sharedThreadExecutor grey_isTrackingIdlingResource:dispatchQueueIdlingResource]);

  dispatch_semaphore_signal(semaphore);
  [self waitForExpectationsWithTimeout:1.0 handler:nil];

  // Wait for the queue to idle to avoid the race condition where the expectation has been fulfilled
  // by the async task and the main thread resumes before that async task completes. This is the
  // best we can do since we cannot keep a reference to the queue to drain it.
  GREYCondition *idleResourceCondition =
      [GREYCondition conditionWithName:@"GREYDispatchQueueIdlingResourceTestDealloc is idle"
                                 block:^BOOL {
        return [dispatchQueueIdlingResource isIdleNow];
      }];

  XCTAssertTrue([idleResourceCondition waitWithTimeout:1.0]);
  XCTAssertFalse([sharedThreadExecutor grey_isTrackingIdlingResource:dispatchQueueIdlingResource]);
}

@end


text:
<!doctype html>

<meta charset="UTF-8" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0" />
<title>leaflet-tilelayer-clip</title>
<link rel="stylesheet" href="//cdn.leafletjs.com/leaflet-0.7.3/leaflet.css" />


text:
using System;
using System.Runtime.Serialization;

namespace Codentia.Common
{
    /// <summary>
    /// InvalidEmailAddressException class - exception class for Email Validation
    /// </summary>
    [Serializable]
    public class InvalidEmailAddressException : ArgumentException
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="InvalidEmailAddressException"/> class.
        /// </summary>
        /// <param name="message">Internal message</param>
        public InvalidEmailAddressException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="InvalidEmailAddressException"/> class.
        /// </summary>
        /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
        /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
        public InvalidEmailAddressException(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="InvalidEmailAddressException"/> class.
        /// </summary>
        /// <param name="message">Internal message</param>
        /// <param name="innerException">Inner Exception</param>
        public InvalidEmailAddressException(string message, Exception innerException)
            : base(message, innerException)
        {
        }
    }
}


text:
namespace courier {
namespace internal {

struct CheckOpString {
  explicit CheckOpString(std::string* str) : str_(str) {}
  explicit operator bool() const { return PREDICT_FALSE(str_ != nullptr); }
  std::string* const str_;
};

template <typename T1, typename T2>
CheckOpString MakeCheckOpString(const T1& v1, const T2& v2,
                                const char* exprtext) {
  std::ostringstream oss;
  oss << exprtext << " (" << v1 << " vs. " << v2 << ")";
  return CheckOpString(new std::string(oss.str()));
}

#define DEFINE_CHECK_OP_IMPL(name, op)                                    \
  template <typename T1, typename T2>                                     \
  inline CheckOpString name##Impl(const T1& v1, const T2& v2,             \
                                  const char* exprtext) {                 \
    if (PREDICT_TRUE(v1 op v2)) {                                         \
      return CheckOpString(nullptr);                                      \
    } else {                                                              \
      return (MakeCheckOpString)(v1, v2, exprtext);                       \
    }                                                                     \
  }                                                                       \
  inline CheckOpString name##Impl(int v1, int v2, const char* exprtext) { \
    return (name##Impl<int, int>)(v1, v2, exprtext);                      \
  }
DEFINE_CHECK_OP_IMPL(Check_EQ, ==)
DEFINE_CHECK_OP_IMPL(Check_NE, !=)
DEFINE_CHECK_OP_IMPL(Check_LE, <=)
DEFINE_CHECK_OP_IMPL(Check_LT, <)
DEFINE_CHECK_OP_IMPL(Check_GE, >=)
DEFINE_CHECK_OP_IMPL(Check_GT, >)
#undef DEFINE_CHECK_OP_IMPL

class LogMessage {
 public:
  LogMessage(const char* file, int line) {
    std::clog << "[" << file << ":" << line << "] ";
  }

  ~LogMessage() { std::clog << "\n"; }

  std::ostream& stream() && { return std::clog; }
};

class LogMessageFatal {
 public:
  LogMessageFatal(const char* file, int line) {
    stream_ << "[" << file << ":" << line << "] ";
  }

  LogMessageFatal(const char* file, int line, const CheckOpString& result) {
    stream_ << "[" << file << ":" << line << "] Check failed: " << *result.str_;
  }

  ~LogMessageFatal() NORETURN;

  std::ostream& stream() && { return stream_; }

 private:
  std::ostringstream stream_;
};

inline LogMessageFatal::~LogMessageFatal() {
  std::cerr << stream_.str() << std::endl;
  std::abort();
}

struct NullStream {};

template <typename T>
NullStream&& operator<<(NullStream&& s, T&&) {
  return std::move(s);
}

enum class LogSeverity {
  kFatal,
  kNonFatal,
};

LogMessage LogStream(
    std::integral_constant<LogSeverity, LogSeverity::kNonFatal>);
LogMessageFatal LogStream(
    std::integral_constant<LogSeverity, LogSeverity::kFatal>);

struct Voidify {
  void operator&(std::ostream&) {}
};

class LogEveryNState {
 public:
  bool ShouldLog(int n);
  uint32_t counter() { return counter_.load(std::memory_order_relaxed); }

 private:
  std::atomic<uint32_t> counter_{0};
};

class LogFirstNState {
 public:
  bool ShouldLog(int n);
  uint32_t counter() { return counter_.load(std::memory_order_relaxed); }

 private:
  std::atomic<uint32_t> counter_{0};
};

class LogEveryPow2State {
 public:
  bool ShouldLog(int ignored);
  uint32_t counter() { return counter_.load(std::memory_order_relaxed); }

 private:
  std::atomic<uint32_t> counter_{0};
};

}  // namespace internal
}  // namespace courier

#define COURIER_CHECK_OP_LOG(name, op, val1, val2, log)                \
  while (::courier::internal::CheckOpString _result =                  \
             ::courier::internal::name##Impl(val1, val2,               \
                                             #val1 " " #op " " #val2)) \
  log(__FILE__, __LINE__, _result).stream()

#define COURIER_CHECK_OP(name, op, val1, val2) \
  COURIER_CHECK_OP_LOG(name, op, val1, val2,   \
                       ::courier::internal::LogMessageFatal)

#define COURIER_CHECK_EQ(val1, val2) COURIER_CHECK_OP(Check_EQ, ==, val1, val2)
#define COURIER_CHECK_NE(val1, val2) COURIER_CHECK_OP(Check_NE, !=, val1, val2)
#define COURIER_CHECK_LE(val1, val2) COURIER_CHECK_OP(Check_LE, <=, val1, val2)
#define COURIER_CHECK_LT(val1, val2) COURIER_CHECK_OP(Check_LT, <, val1, val2)
#define COURIER_CHECK_GE(val1, val2) COURIER_CHECK_OP(Check_GE, >=, val1, val2)
#define COURIER_CHECK_GT(val1, val2) COURIER_CHECK_OP(Check_GT, >, val1, val2)

#define COURIER_QCHECK_EQ(val1, val2) COURIER_CHECK_OP(Check_EQ, ==, val1, val2)
#define COURIER_QCHECK_NE(val1, val2) COURIER_CHECK_OP(Check_NE, !=, val1, val2)
#define COURIER_QCHECK_LE(val1, val2) COURIER_CHECK_OP(Check_LE, <=, val1, val2)
#define COURIER_QCHECK_LT(val1, val2) COURIER_CHECK_OP(Check_LT, <, val1, val2)
#define COURIER_QCHECK_GE(val1, val2) COURIER_CHECK_OP(Check_GE, >=, val1, val2)
#define COURIER_QCHECK_GT(val1, val2) COURIER_CHECK_OP(Check_GT, >, val1, val2)

#define COURIER_CHECK(condition)                                   \
  while (auto _result = ::courier::internal::CheckOpString(        \
             (condition) ? nullptr : new std::string(#condition))) \
  ::courier::internal::LogMessageFatal(__FILE__, __LINE__, _result).stream()

#define COURIER_QCHECK(condition) COURIER_CHECK(condition)

#define COURIER_FATAL ::courier::internal::LogSeverity::kFatal
#define COURIER_QFATAL ::courier::internal::LogSeverity::kFatal
#define COURIER_INFO ::courier::internal::LogSeverity::kNonFatal
#define COURIER_WARNING ::courier::internal::LogSeverity::kNonFatal
#define COURIER_ERROR ::courier::internal::LogSeverity::kNonFatal

#define COURIER_LOG(level)                                                 \
  decltype(::courier::internal::LogStream(                                 \
      std::integral_constant<::courier::internal::LogSeverity, level>()))( \
      __FILE__, __LINE__)                                                  \
      .stream()

#define COURIER_VLOG(level) ::courier::internal::NullStream()

#define COURIER_LOG_IF(level, condition)                                 \
  !(condition)                                                           \
      ? static_cast<void>(0)                                             \
      : ::courier::internal::Voidify() &                                 \
            decltype(::courier::internal::LogStream(                     \
                std::integral_constant<::courier::internal::LogSeverity, \
                                       level>()))(__FILE__, __LINE__)    \
                .stream()

#define COURIER_LOGGING_INTERNAL_STATEFUL_CONDITION(kind, condition, arg) \
  for (bool logging_internal_stateful_condition_do_log(condition);        \
       logging_internal_stateful_condition_do_log;                        \
       logging_internal_stateful_condition_do_log = false)                \
    for (static ::courier::internal::Log##kind##State                     \
             logging_internal_stateful_condition_state;                   \
         logging_internal_stateful_condition_do_log &&                    \
         logging_internal_stateful_condition_state.ShouldLog(arg);        \
         logging_internal_stateful_condition_do_log = false)              \
      for (const uint32_t COUNTER ABSL_ATTRIBUTE_UNUSED =                 \
               logging_internal_stateful_condition_state.counter();       \
           logging_internal_stateful_condition_do_log;                    \
           logging_internal_stateful_condition_do_log = false)

#define COURIER_LOG_EVERY_N(level, n)                          \
  COURIER_LOGGING_INTERNAL_STATEFUL_CONDITION(EveryN, true, n) \
  COURIER_LOG(level)

#define COURIER_LOG_FIRST_N(level, n)                          \
  COURIER_LOGGING_INTERNAL_STATEFUL_CONDITION(FirstN, true, n) \
  COURIER_LOG(level)

#define COURIER_LOG_EVERY_POW_2(level)                            \
  COURIER_LOGGING_INTERNAL_STATEFUL_CONDITION(EveryPow2, true, 0) \
  COURIER_LOG(level)

#endif  // COURIER_PLATFORM_DEFAULT_LOGGING_H_


text:
using System;
using System.IO;
using System.Threading;
using Windows.UI.Xaml.Controls;

namespace Microsoft.AspNet.SignalR.Client.Samples
{
    public class TextBoxWriter : TextWriter
    {
        private SynchronizationContext _context;
        private TextBox _textView;

        public TextBoxWriter(SynchronizationContext context, TextBox textView)
        {
            _context = context;
            _textView = textView;
        }

        public override void WriteLine(string value)
        {
            _context.Post(delegate
            {
                _textView.Text = _textView.Text + value + Environment.NewLine;
            }, state: null);
        }

        public override void WriteLine(string format, params object[] args)
        {
            _context.Post(delegate
            {
                _textView.Text = _textView.Text + string.Format(format, args) + Environment.NewLine;
            }, state: null);
        }

        #region implemented abstract members of TextWriter

        public override System.Text.Encoding Encoding
        {
            get
            {
                throw new NotImplementedException();
            }
        }

        #endregion

        public override void Write(char value)
        {
            throw new NotImplementedException();
        }
    }
}


text:
@protocol LFMAlbum <NSObject>

// TODO: Images S to XL
- (NSString *)musicBrianzId;
- (NSString *)name;
- (NSNumber *)playcount;
- (NSURL *)lfmPage;

@end


text:
package com.opengamma.financial.config;

import com.opengamma.core.change.BasicChangeManager;
import com.opengamma.core.change.ChangeEvent;
import com.opengamma.core.change.ChangeListener;
import com.opengamma.core.change.ChangeManager;
import com.opengamma.core.change.ChangeProvider;
import com.opengamma.core.change.ChangeType;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionDefinition;
import com.opengamma.engine.function.FunctionReinitializer;
import com.opengamma.id.ObjectId;
import com.opengamma.id.VersionCorrection;
import com.opengamma.util.ArgumentChecker;

/**
 * A {@link ChangeProvider} that translates configuration changes from document identifiers to type summaries.
 * <p>
 * This can be used for re-initialization of functions that look up configuration items by name.
 */
public abstract class AbstractConfigChangeProvider implements ChangeProvider {

  /**
   * The scheme used in object identifiers that this generates change notifications for.
   */
  public static final String CONFIG_TYPE_SCHEME = "ConfigItemType";

  /**
   * Requests the function be reinitialized whenever configurations of the given type change.
   *
   * @param context the compilation context, not null
   * @param function the function, not null
   * @param type the type to watch
   */
  public static void reinitOnChanges(final FunctionCompilationContext context, final FunctionDefinition function, final Class<?> type) {
    final FunctionReinitializer reinit = context.getFunctionReinitializer();
    if (reinit != null) {
      reinit.reinitializeFunction(function, ObjectId.of(CONFIG_TYPE_SCHEME, type.getName()));
    }
  }

  private final ChangeListener _changeListener = new ChangeListener() {
    @Override
    public void entityChanged(final ChangeEvent event) {
      switch (event.getType()) {
        case ADDED:
          configAdded(event);
          break;
        case CHANGED:
          configChanged(event);
          break;
        case REMOVED:
          configRemoved(event);
          break;
        default:
          throw new UnsupportedOperationException(event.toString());
      }
    }
  };

  private final BasicChangeManager _changeManager = new BasicChangeManager() {

    @Override
    public synchronized void addChangeListener(final ChangeListener listener) {
      ArgumentChecker.notNull(listener, "listener");
      if (getListeners().isEmpty()) {
        getUnderlying().changeManager().addChangeListener(_changeListener);
      }
      super.addChangeListener(listener);
    }

    @Override
    public synchronized void removeChangeListener(final ChangeListener listener) {
      super.removeChangeListener(listener);
      if (getListeners().isEmpty()) {
        getUnderlying().changeManager().removeChangeListener(_changeListener);
      }
    }

  };

  protected abstract ChangeProvider getUnderlying();

  protected VersionCorrection getNewVersion(final ChangeEvent event) {
    return VersionCorrection.of(event.getVersionFrom(), event.getVersionInstant());
  }

  protected VersionCorrection getOldVersion(final ChangeEvent event) {
    return VersionCorrection.of(event.getVersionFrom().minusNanos(1L), event.getVersionInstant());
  }

  protected abstract void configAdded(ChangeEvent event);

  protected abstract void configChanged(ChangeEvent event);

  protected abstract void configRemoved(ChangeEvent event);

  private void notifyListeners(final ChangeEvent event, final Class<?> clazz, final ChangeType type) {
    _changeManager.entityChanged(type, ObjectId.of(CONFIG_TYPE_SCHEME, clazz.getName()), event.getVersionFrom(), event.getVersionTo(), event.getVersionInstant());
  }

  protected void added(final ChangeEvent event, final Class<?> type) {
    notifyListeners(event, type, ChangeType.ADDED);
  }

  protected void changed(final ChangeEvent event, final Class<?> type) {
    notifyListeners(event, type, ChangeType.CHANGED);
  }

  protected void removed(final ChangeEvent event, final Class<?> type) {
    notifyListeners(event, type, ChangeType.REMOVED);
  }

  // ChangeProvider

  @Override
  public ChangeManager changeManager() {
    return _changeManager;
  }

}


text:
use strict;
use warnings;
use DBI qw( :sql_types );
use Getopt::Long;
use Bio::EnsEMBL::Registry;
use Bio::EnsEMBL::ApiVersion;
use HTML::Entities;

use FindBin qw($Bin);
use vars qw($SERVERROOT);

BEGIN {
    $SERVERROOT = "$Bin";
}

my $xhost;
my $xport;
my $xuser;
my $xpass;
my $db_version;
my $host;
my $user;
my $port;
my $species;
my $dontdrop;

GetOptions( "xhost|xh=s" => \$xhost,
            "xport=i" => \$xport,
            "xuser|xu=s" => \$xuser,
	    "xpass|xp=s" => \$xpass,
	    "host|h=s",\$host,
	    "user|u=s",\$user,
	    "port=i",\$port,
	    "species|s=s",\$species,
	    "db_version=i",\$db_version,
	    "dontdrop|d", \$dontdrop,
	    "help" ,     \&usage,

);

usage() if (!defined $xhost || !defined $xuser || !defined $xpass || !defined $host || !defined $user || !defined $species);

$port ||= 3306;
$xport ||= 3306;
$db_version ||= software_version();

my $registry = "Bio::EnsEMBL::Registry";

$registry->load_registry_from_db( -host => $host, -port => $port,-user => $user, -db_version => $db_version, -species => $species);

my $dba = $registry->get_DBAdaptor($species, "core");

if (!$dba) {
    die("$species database version $db_version not found on host $host port $port");
}

my $dbh;

#create and connect to the xref_mindmap database
my $dsn = "DBI:mysql:host=$xhost;";
if ($xport) {
   $dsn .= "port=$xport;";
}
my $xdbname = 'xref_mindmap_'.$species.'_'.$db_version;

$dbh = DBI->connect( $dsn, $xuser, $xpass,
                          { 'PrintError' => 1, 'RaiseError' => 1 } );

my @objects_with_xrefs = ('Gene', 'Transcript', 'Translation');

my %object_display_names = ('Gene' => 'Gene', 'Transcript' => 'Transcript', 'Translation' => 'Protein');

print STDOUT "Creating database $xdbname\n";

eval {
     $dbh->do("drop database if exists $xdbname");
     $dbh->do("create database $xdbname");

     my $cmd = "mysql -h $xhost";
     if ($xport) {
		$cmd .= " -P $xport";
     }
     $cmd .= " -u $xuser --password=$xpass $xdbname <  $SERVERROOT/sql/tables.sql";
     system($cmd) == 0 or die("error encountered when creating schema for database $xdbname\n");

     $dbh->do("use $xdbname");

};

if ($@) {
     die("An SQL error occured while creating database $xdbname:\n$@");
}

#copy the external_db information

my $external_db_info_sth = $dba->dbc()->prepare("select external_db_id, db_name, db_display_name from external_db");
my $insert_external_db_info_sth = $dbh->prepare("insert into external_db_type (external_db_id, db_name, db_display_name) values (?,?,?)");

$external_db_info_sth->execute();

while ( my ($external_db_id, $db_name, $db_display_name) = $external_db_info_sth->fetchrow_array() ) {

    $insert_external_db_info_sth->execute($external_db_id, $db_name, $db_display_name);

}
$external_db_info_sth->finish();
$insert_external_db_info_sth->finish();

#populate db types in external_db_type

my $cmd = "mysql -h $xhost";
if ($xport) {
    $cmd .= " -P $xport";
}
$cmd .= " -u $xuser --password=$xpass $xdbname <  $SERVERROOT/sql/update.sql";
system($cmd) == 0 or die("error encountered when updating database $xdbname\n");

#get distinct db_names for an object type
my $external_db_sth = $dba->dbc()->prepare("select distinct external_db_id from object_xref join xref using(xref_id) join external_db using(external_db_id) where ensembl_object_type = ? and info_type != 'UNMAPPED' order by db_name");

#get xref types for an object type and external db
my $xref_types_sth = $dba->dbc()->prepare("select distinct info_type from object_xref join xref using(xref_id) where ensembl_object_type = ? and external_db_id = ? and info_type != 'UNMAPPED'");

#get master xref db_names
my $master_db_sth =  $dba->dbc()->prepare("select distinct e.external_db_id from object_xref ox join xref x1 on (ox.xref_id = x1.xref_id) join dependent_xref on (x1.xref_id = dependent_xref_id) join xref x2 on (master_xref_id = x2.xref_id) join external_db e on (x2.external_db_id = e.external_db_id) where ensembl_object_type = ? and  x1.external_db_id = ? and x1.info_type != 'UNMAPPED'");

#get species from which xrefs were projected
my $projected_from_species_sth = $dba->dbc()->prepare("select distinct substr(info_text,1,locate(' ', info_text, locate(' ', info_text)+1 )) from object_xref join xref using(xref_id) where info_text like 'from%' and ensembl_object_type = ? and external_db_id = ? and info_type = 'PROJECTION'");

#xref_mindmap db statements

my $insert_object_xref_linkage = $dbh->prepare("insert into object_xref_linkage values(?,?,?,?,?)");

my $insert_object_external_db_node = $dbh->prepare("insert into object_external_db_node values (?,?,?)");

my $link_type_sth = $dbh->prepare("select link_type_id from link_type where link_type = ?");

foreach my $object (@objects_with_xrefs) {

    $external_db_sth->execute($object);
    my @db_ids;
    while (my ($db_id) = $external_db_sth->fetchrow_array() ) {
	push @db_ids, $db_id;
    }

    foreach my $db_id (@db_ids) {
	$xref_types_sth->execute($object, $db_id);

	#store the xref db node
	$insert_object_external_db_node->execute($object,$db_id, $object.$db_id);

	while (my ($link_type) = $xref_types_sth->fetchrow_array() ) {

	    #get link_type_id
	    $link_type_sth->execute($link_type);
	    my ($link_type_id) = $link_type_sth->fetchrow_array();

	    if ($link_type_id) {

		if ($link_type eq 'DEPENDENT') {

		   $master_db_sth->execute($object,$db_id);
		   while (my ($master_db_id) = $master_db_sth->fetchrow_array() ) {

		       $insert_object_xref_linkage->execute($db_id,$object,$link_type_id, $master_db_id, undef);
		   }

		} elsif ($link_type eq 'PROJECTION') {

		    $projected_from_species_sth->execute($object, $db_id);
		    while (my ($linked_node_text) = $projected_from_species_sth->fetchrow_array()) {
			$insert_object_xref_linkage->execute($db_id,$object,$link_type_id, undef, $linked_node_text);
		    }

		} else {

		    $insert_object_xref_linkage->execute($db_id,$object,$link_type_id, undef, undef);

		}

	    }

	}

    }

}

#populate 'generated_from' link types in object_xref_linkage - this is for xrefs to do with gene and transcript naming

my $naming_dbs_sth = $dbh->prepare("select external_db_id, db_name from external_db_type where db_name like ?");
my $db_id_sth = $dbh->prepare("select external_db_id from external_db_type where db_name = ?");

$link_type_sth->execute('GENERATED_FROM');
my ($link_type_id) = $link_type_sth->fetchrow_array();

foreach my $object (@objects_with_xrefs) {

    $naming_dbs_sth->execute('%'.$object.'\_name');
    while (my ($db_id, $db_name) = $naming_dbs_sth->fetchrow_array() ) {

	if ($db_name =~ m/(.*)\_$object\_name/i) {

	    my $linked_db_name = $1;
	    if ($linked_db_name) {

	       #find the linked db id
	       $db_id_sth->execute($linked_db_name);
	       my ($linked_db_id) = $db_id_sth->fetchrow_array();

	       if ($linked_db_id) {
		    $insert_object_xref_linkage->execute($db_id,$object,$link_type_id, $linked_db_id, undef);
	       }

	    }
	}
    }

    foreach my $name ( ('Vega','Ensembl')) {
	$naming_dbs_sth->execute('Clone\_based\_'.$name.'\_'.$object);
	my ($db_id, $db_name) = $naming_dbs_sth->fetchrow_array();
	if ($db_id) {
	    $insert_object_xref_linkage->execute($db_id,$object,$link_type_id, undef, "$name clone name");
	}
    }

}
$naming_dbs_sth->finish();

#check if there are any rows in the interpro table

my $interpro_sth = $dba->dbc()->prepare("select count(1) from interpro");

$interpro_sth->execute();
my ($interpro_count) = $interpro_sth->fetchrow_array();

if ($interpro_count > 0) {

    my $interpro = 'Interpro';

    $db_id_sth->execute($interpro);
    my ($interpro_db_id) = $db_id_sth->fetchrow_array();

    $link_type_sth->execute('PROTEIN_FEATURES');
    my ($link_type_id) = $link_type_sth->fetchrow_array();

     my $object = 'Translation';
    $insert_object_external_db_node->execute($object,$interpro_db_id, $object.$interpro_db_id);

    $insert_object_xref_linkage->execute($interpro_db_id,$object,$link_type_id, undef, undef);
}

$interpro_sth->finish();
$db_id_sth->finish();

$external_db_sth->finish();
$xref_types_sth->finish();
$master_db_sth->finish();
$projected_from_species_sth->finish();

$insert_object_xref_linkage->finish();
$insert_object_external_db_node->finish();
$link_type_sth->finish();

#create the .mm file based on info from xref_mindmap db

my $file_name = $species .'_xrefs_'. $db_version .'.mm';

open( FH, ">$file_name" ) or die("Can't open $file_name\n");

print STDOUT "Writing to file $file_name\n";

my $header = <<HEADER;
<map version='0.9.0'>

<node TEXT='External References' ID='ID_000000001' COLOR='#18898b' STYLE='fork'>

<hook NAME='MapStyle' max_node_width='600'/>
<edge STYLE='bezier' COLOR='#808080' WIDTH='thin'/>
HEADER

print FH $header;

my $category_and_db_name_nodes_sth = $dbh->prepare("select db_type, external_db_id, db_display_name, mindmap_tag_id from object_external_db_node join external_db_type using(external_db_id) join db_type using(db_type_id) where ensembl_object_type = ? order by db_type, db_display_name;");

my $db_linkage_types_sth = $dbh->prepare("select link_description, linked_external_db_id, linked_node_text from object_xref_linkage join link_type using(link_type_id) where ensembl_object_type = ? and external_db_id = ? and link_description is not null order by link_description, linked_external_db_id, linked_node_text");

#this is used to link to dbs from the closest level (e.g. if Orphanet xrefs for a Gene are dependent on HGNC xrefs
#we will try to link to the Gene HGNC node then transcript etc..

my $object_distance_sth = $dbh->prepare("select to_object from object_distance where from_object = ? order by distance");

my $node_id_sth = $dbh->prepare("select mindmap_tag_id from object_external_db_node where ensembl_object_type = ? and external_db_id = ?");

my $node_id_count = 1;

foreach my $object (@objects_with_xrefs) {
    $node_id_count++;
    my $node_id = 'ID_'.$node_id_count;
    #write out the object node
    my $object_node = "<node TEXT='".$object_display_names{$object}."' POSITION='right' ID='".$node_id."' COLOR='#cc3300' STYLE='fork'>

<edge STYLE='bezier' COLOR='#808080' WIDTH='thin'/>
";
    print FH $object_node;

    $category_and_db_name_nodes_sth->execute($object);

    my $last_type = 'none';
    while (my ($db_type, $db_id, $db_display_name, $tag_id) = $category_and_db_name_nodes_sth->fetchrow_array() ) {

	if ($db_type ne $last_type) {

	    if ($last_type ne 'none') {
		print FH "</node>\n";  #db type node end tag
	    }
	    $node_id_count++;
	    $node_id = 'ID_'.$node_id_count;
	    #write out new db type node
	    my $db_type_node = "<node TEXT='".encode_entities($db_type)."' ID='".$node_id."' COLOR='#669900'>

";
	    print FH $db_type_node;
	}

	#write out the db name node
	$node_id_sth->execute($object,$db_id);
	($node_id) = $node_id_sth->fetchrow_array();
	my $db_name_node = "<node TEXT='".encode_entities($db_display_name)."' ID='".$node_id."'>
";
	print FH $db_name_node;

	$db_linkage_types_sth->execute($object,$db_id);

	my $last_link_desc = 'none';
	while (my ($link_description, $linked_db_id, $linked_node_text)
	       = $db_linkage_types_sth->fetchrow_array() ){

	    if ($link_description ne $last_link_desc) {
		if ($last_link_desc ne 'none') {
		    print FH "</node>\n";  #link type node end tag
		}
		#write out the link node
		$node_id_count++;
		$node_id = 'ID_'.$node_id_count;
		my $link_node = "<node TEXT='".encode_entities($link_description)."' ID='".$node_id."'>
";
		print FH $link_node;

	    }

	    if ($linked_db_id) {

		#find the node id to link to
		my @closest_level;
		$object_distance_sth->execute($object);

		while (my ($object_type) = $object_distance_sth->fetchrow_array() ) {
		    push @closest_level, $object_type;
		}

		my $linked_node_id;
		foreach my $object_type (@closest_level) {

		    $node_id_sth->execute($object_type,$linked_db_id);
		    ($linked_node_id) = $node_id_sth->fetchrow_array();
		    last if ($linked_node_id);
		}

		if ($linked_node_id) {
		    #write out arrow link to the node
		    my $arrow_link_node = "<arrowlink DESTINATION='".$linked_node_id."' STARTARROW='NONE' ENDARROW='DEFAULT'/>
";
		    print FH $arrow_link_node;
		}

	    } elsif ($linked_node_text) {

		#write out the node
		$node_id_count++;
		$node_id = 'ID_'.$node_id_count;
		my $node = "<node TEXT='".encode_entities($linked_node_text)."' ID='".$node_id."'/>
";
		print FH $node;

	    }

	    $last_link_desc = $link_description;

	}
	if ($last_link_desc ne 'none') {
	    print FH "</node>\n";  #link type node end tag
	}

	print FH "</node>\n";  #db name node end tag

	$last_type = $db_type;
    }
    if ($last_type ne 'none') {
	print FH "</node>\n";  #db type node end tag
    }

    print FH "</node>\n" #object node end tag;

}

$category_and_db_name_nodes_sth->finish();
$db_linkage_types_sth->finish();
$object_distance_sth->finish();
$node_id_sth->finish();

#external references end tag and map end tag
my $footer = <<FOOTER;
</node>
</map>
FOOTER

print FH $footer;

close(FH);

if (!$dontdrop) {

    print STDOUT "Dropping database $xdbname\n";
    eval {
	$dbh->do("drop database if exists $xdbname");
    };
    if ($@) {
	die("An SQL error occured while dropping database $xdbname:\n$@");
    }
}

$dbh->disconnect();

sub usage {
  my $indent = ' ' x length($0);
  print <<EOF; exit(0);

The script populates a stable_id lookup database with all stable ids found in databases
on a specified server (or servers) for a specified db release.
Stable ids are copied for objects listed in hash %group_objects

Options -lhost -luser -lpass are mandatory and specify the credentials for the server on which a stable id lookup database exists or is to be created (if using option -create). If an argument for option -ldbname is not provided, the default name for the database wil be used: 'ensembl_stable_id_lookup_xx', where xx is the database release (option -db_version).

Options -host -user -port specify the credentials of the server(s) where stable ids are to be copied from.

To run the script cd into the directory where the script lives eg:
cd ensembl/misc-scripts/stable_id_lookup/

This command will create database ensembl_stable_id_lookup_67 on server ens-staging1 and will copy stable ids from databases for release 67 found on ens-staging1 and ens-staging2:

populate_stable_id_lookup.pl -lhost ens-staging1 -luser ensadmin -lpass xxxx -create -db_version 67 -host ens-staging1 -host ens-staging2 -user ensro

Usage:

  $0 -xhost host_name -xuser user_name -xpass password
  $indent [-xport port_number]
  $indent -host host_name -user user_name
  $indent [-port port_number] [-db_version]
  $indent -species species_name
  $indent [-dontdrop]
  $indent [-help]

  -h|host              Database host where the species db lives

  -u|user              Database user where the species db lives

  -port                Database port the species db lives

  -xh|xhost            Database host where the xref mindmap db is to be created

  -xu|xuser            Database user where the xref mindmap db is to be created

  -xp|xpass            Database password where the xref mindmap db is to be created

  -xport               Database port where the xref mindmap db is to be created

  -s|species           Species name to generate xref mindmap for

  -d|dontdrop          Don\'t drop the xref_mindmap db at the end of the script

  -db_version          If not specified, software_version() returned by the ApiVersion module will be used

  -help                This message

EOF

}


text:
namespace TraktApiSharp.Enums
{
    /// Determines the type of an object in a comment.
    public sealed class TraktObjectType : TraktEnumeration
    {
        /// An invalid object type.
        public static TraktObjectType Unspecified { get; } = new TraktObjectType();

        /// The comment contains a movie.
        public static TraktObjectType Movie { get; } = new TraktObjectType(1, "movie", "movies", "Movie");

        /// The comment contains a show.
        public static TraktObjectType Show { get; } = new TraktObjectType(2, "show", "shows", "Show");

        /// The comment contains a season.
        public static TraktObjectType Season { get; } = new TraktObjectType(4, "season", "seasons", "Season");

        /// The comment contains an episode.
        public static TraktObjectType Episode { get; } = new TraktObjectType(8, "episode", "episodes", "Episode");

        /// The comment contains a list.
        public static TraktObjectType List { get; } = new TraktObjectType(16, "list", "lists", "List");

        /// The comment contains a movie, show, season, list or an episode.
        public static TraktObjectType All { get; } = new TraktObjectType(32, "all", "all", "All");

        ///
        /// Initializes a new instance of the <see cref="TraktObjectType" /> class.<para />
        /// The initialized <see cref="TraktObjectType" /> is invalid.
        ///
        public TraktObjectType()
        {
        }

        private TraktObjectType(int value, string objectName, string uriName, string displayName) : base(value, objectName, uriName, displayName)
        {
        }
    }
}


text:
/** @jsx React.DOM */

var React = require('react');

module.exports = NotificationBar = React.createClass({
  render: function(){
    var count = this.props.count;
    return (

 0 ? ' active' : '')}>

There are {count} new tweets! Click here to see them.

    )
  }
});


text:
{$web=M("web")->information}
<!DOCTYPE HTML>

<meta charset="UTF-8">
<title>{include "inc/title.html"}</title>
<link href="/css/style.css" rel="stylesheet" type="text/css">
<meta name="description" content="{$web['description']}">
<meta name="keywords" content="{$web['key']}">
<meta name="generator" content="FengCms" />
<meta name="author" content="FengCms">

{include "scrap/header.html"}

	<hgroup id="hgroup">

标签云

		{include "inc/where.html"}

	</hgroup>

			{loop M("tags")->index() $k $v}
			{$v['name']}
			{/loop}

{include "scrap/footer.html"}