text:
<?php
  // Consulta de Titulaciones por Raul Villar Ramos
  session_start(); // se inicia el manejo de sesiones

  //Cancerbero
  require_once '../cancerbero/cancerbero.php';
  $cerb = new Cancerbero('AP_ConsultaTitulaciones');
  $cerb->handleAuto();

  //Includes iniciales
  require_once '../views/templateEngine.php'; // se carga la clase TemplateEngine
  require_once '../cancerbero/php/DBManager.php'; // se carga el driver de cancerbero
  require_once 'navbar.php'; //Inclusi�n de navbar. Omitible si no la necesita
  require_once '../model/driver.php'; //Inclusi�n de Driver de las clases de "model". Omitible si no las usamos
  require_once '../model/Titulacion.php';
  require_once 'comboboxes.php';

  //Instanciacion de Driver
  $db = Driver::getInstance(); //Esto permite el uso de las clases de "model" (Usuario.php, Apunte.php etc...)

  //Instancias
  $titulaciones = new Titulacion($db);
  $titulaciones= $titulaciones->all();

  //Instancias TemplateEngine, renderizan elementos
  $renderMain = new TemplateEngine();
  $renderPlantilla = new TemplateEngine();
  $renderPlantilla->status = "<br/>"; //Se usa este campo para mostrar mensajes de error o avisos, salto de l�nea por defecto

  //FUNCIONES DEL CONTROLADOR
  //visualiza Titulaciones y permite insercion o borrado a traves de ficheros auxiliares.

  //RENDERIZADO FINAL
  $renderPlantilla->titulaciones = $titulaciones;
  $renderMain->title = "Consulta de Titulaciones"; //Titulo y cabecera de la pagina
  $renderMain->navbar = renderNavBar(); //Inserci�n de navBar en la pagina. Omitible si no la necesita
  $renderMain->content = $renderPlantilla->render('consultaTitulaciones_v.php'); //Inserci�n del contenido de la p�gina

  echo $renderMain->renderMain(); // Dibujado de la p�gina al completo

 ?>

redpajama_set_name: RedPajamaGithub


text:
package keyring

import (
	"fmt"
	"os/exec"
	"strings"
)

const (
	execPathKeychain = "/usr/bin/security"
)

type macOSXKeychain struct{}

// func (*MacOSXKeychain) IsAvailable() bool {
// 	return exec.Command(execPathKeychain).Run() != exec.ErrNotFound
// }

// Set stores stores user and pass in the keyring under the defined service
// name.
func (k macOSXKeychain) Get(service, username string) (string, error) {
	out, err := exec.Command(
		execPathKeychain,
		"find-generic-password",
		"-s", service,
		"-wa", username).CombinedOutput()
	if err != nil {
		if strings.Contains(fmt.Sprintf("%s", out), "could not be found") {
			err = ErrNotFound
		}
		return "", err
	}
	return strings.TrimSpace(fmt.Sprintf("%s", out)), nil
}

// Get gets a secret from the keyring given a service name and a user.
func (k macOSXKeychain) Set(service, username, password string) error {
	return exec.Command(
		execPathKeychain,
		"add-generic-password",
		"-U", //update if exists
		"-s", service,
		"-a", username,
		"-w", password).Run()
}

// Delete deletes a secret, identified by service & user, from the keyring.
func (k macOSXKeychain) Delete(service, username string) error {
	out, err := exec.Command(
		execPathKeychain,
		"delete-generic-password",
		"-s", service,
		"-a", username).CombinedOutput()
	if strings.Contains(fmt.Sprintf("%s", out), "could not be found") {
		err = ErrNotFound
	}
	return err
}

func init() {
	provider = macOSXKeychain{}
}


text:
import React from 'react';
import { viewPokemonOnMap } from '../actions/mapActions';

export default class Pokemon extends React.Component {
	handleClick () {
		this.props.dispatch(viewPokemonOnMap(this.props.data));
	}

	render () {
		const data = this.props.data;
		const mapUrl = 'https://www.google.co.uk/maps/search/' + data.lat + ',' + data.lng;
		const despawn = new Date(data.expires * 1000);
		const hours = despawn.getHours();
		const minutes = '0' + despawn.getMinutes();
		const seconds = '0' + despawn.getSeconds();
		const formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

		return (

					{data.name}

					Atk:{data.attack} | Def:{data.defence} | Sta:{data.stamina}

					IV : {data.iv}%

					Expires: {formattedTime}

						 View on Map

						 Get Directions

		);
	}
}


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

package com.google.api.ads.adwords.jaxws.v201809.o;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             A {@link SearchParameter} that specifies the level of search volume expected in results,
 *             and it has a direct relationship to {@link AttributeType#SEARCH_VOLUME SEARCH_VOLUME}. Absence of
 *             a {@link SearchVolumeSearchParameter} in a {@link TargetingIdeaSelector} is equivalent to having
 *             no constraint on search volume specified.
 *
This element is supported by following {@link IdeaType}s: KEYWORD.
 *
This element is supported by following {@link RequestType}s: IDEAS, STATS.
 *
 *
 *
Java class for SearchVolumeSearchParameter complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="SearchVolumeSearchParameter">
 *   <complexContent>
 *     <extension base="{https://adwords.google.com/api/adwords/o/v201809}SearchParameter">
 *       <sequence>
 *         <element name="operation" type="{https://adwords.google.com/api/adwords/o/v201809}LongComparisonOperation" minOccurs="0"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SearchVolumeSearchParameter", propOrder = {
    "operation"
})
public class SearchVolumeSearchParameter
    extends SearchParameter
{

    protected LongComparisonOperation operation;

    /**
     * Gets the value of the operation property.
     *
     * @return
     *     possible object is
     *     {@link LongComparisonOperation }
     *
     */
    public LongComparisonOperation getOperation() {
        return operation;
    }

    /**
     * Sets the value of the operation property.
     *
     * @param value
     *     allowed object is
     *     {@link LongComparisonOperation }
     *
     */
    public void setOperation(LongComparisonOperation value) {
        this.operation = value;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Pluteus ferrugineus Henn. & E. Nyman

### Remarks
null


text:
namespace XPump.Model
{
    using System;
    using System.Collections.Generic;

    public partial class shiftsales
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public shiftsales()
        {
            this.salessummary = new HashSet<salessummary>();
            this.shiftsttak = new HashSet<shiftsttak>();
        }

        public int id { get; set; }
        public System.DateTime saldat { get; set; }
        public bool closed { get; set; }
        public int shift_id { get; set; }
        public string creby { get; set; }
        public System.DateTime cretime { get; set; }
        public string chgby { get; set; }
        public Nullable<System.DateTime> chgtime { get; set; }
        public string apprby { get; set; }
        public Nullable<System.DateTime> apprtime { get; set; }
        public string prnby { get; set; }
        public Nullable<System.DateTime> prntime { get; set; }
        public int prncnt { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<salessummary> salessummary { get; set; }
        public virtual shift shift { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<shiftsttak> shiftsttak { get; set; }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _04.CompareSortAlgorithms
{
    class CompareSortAlgorithms
    {
        static void Main(string[] args)
        {
            // Performance for int values
            int[] arr = new int[] { 6, 78, 32, 25, 90, 567, 5, 89, 95, 4 };
            Console.WriteLine("Performance for int values:");
            TestInsertionSortPerformance(arr);
            TestSelectionSortPerformance(arr);
            TestQuickSortPerformance(arr);
            Console.WriteLine();

            // Performance for random values
            Random rnd = new Random();
            int[] arr3 = new int[10];
            for (int i = 0; i < arr3.Length; i++)
            {
                arr3[i] = rnd.Next(100);
            }
            Console.WriteLine("Performance for random int values:");
            TestInsertionSortPerformance(arr3);
            TestSelectionSortPerformance(arr3);
            TestQuickSortPerformance(arr3);
            Console.WriteLine();

            // Performance for sorted values
            int[] arr4 = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            Console.WriteLine("Performance for sorted int values:");
            TestInsertionSortPerformance(arr4);
            TestSelectionSortPerformance(arr4);
            TestQuickSortPerformance(arr4);
            Console.WriteLine();

            // Performance for values sorted in reversed order
            int[] arr5 = new int[] { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
            Console.WriteLine("Performance for sorted in reversed order int values:");
            TestInsertionSortPerformance(arr5);
            TestSelectionSortPerformance(arr5);
            TestQuickSortPerformance(arr5);
            Console.WriteLine();

            // Performance for double values
            double[] arr1 = new double[] { 6.8, 78.4, 32.1, 25.4, 90.9, 567.7, 5.1, 89.8, 95.4, 4.3 };
            Console.WriteLine("Performance for double values:");
            TestInsertionSortPerformance(arr1);
            TestSelectionSortPerformance(arr1);
            TestQuickSortPerformance(arr1);
            Console.WriteLine();

            // Performance for string values
            string[] arr2 = new string[] { "sort", "swap", "algorithm", "number", "add", "string", "array", "double", "quick", "select" };
            Console.WriteLine("Performance for string values:");
            TestInsertionSortPerformance(arr2);
            TestSelectionSortPerformance(arr2);
            TestQuickSortPerformance(arr2);
            Console.WriteLine();
        }

        static void TestInsertionSortPerformance<T>(T[] arr) where T : IComparable<T>
        {
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < 100000; i++)
            {
                InsertionSort(arr);
            }
            sw.Stop();
            Console.WriteLine("The performance of Insertion Sort Algorithm: {0}", sw.Elapsed);
        }

        static void TestSelectionSortPerformance<T>(T[] arr) where T : IComparable<T>
        {
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < 100000; i++)
            {
                SelectionSort(arr);
            }
            sw.Stop();
            Console.WriteLine("The performance of Selection Sort Algorithm: {0}", sw.Elapsed);
        }

        static void TestQuickSortPerformance<T>(T[] arr) where T : IComparable<T>
        {
            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < 100000; i++)
            {
                QuickSort(arr, 0, arr.Length - 1);
            }
            sw.Stop();
            Console.WriteLine("The performance of Quick Sort Algorithm: {0}", sw.Elapsed);
        }

        private static void InsertionSort<T>(T[] arr) where T : IComparable<T>
        {
            Debug.Assert(arr != null, "The array is not initialized!");
            Debug.Assert(arr.Length > 0, "The array is empty!");
            for (int index = 0; index < arr.Length - 1; index++)
            {
                int j = index + 1;

                while (j > 0)
                {
                    if (arr[j - 1].CompareTo(arr[j]) < 0)
                    {
                        Swap(ref arr[j - 1], ref arr[j]);
                    }
                    j--;
                }
            }
        }

        private static void SelectionSort<T>(T[] arr) where T : IComparable<T>
        {
            Debug.Assert(arr != null, "The array is not initialized!");
            Debug.Assert(arr.Length > 0, "The array is empty!");
            for (int index = 0; index < arr.Length - 1; index++)
            {
                int minElementIndex = FindMinElementIndex(arr, index, arr.Length - 1);
                Swap(ref arr[index], ref arr[minElementIndex]);
            }
        }

        private static int FindMinElementIndex<T>(T[] arr, int startIndex, int endIndex)
            where T : IComparable<T>
        {
            Debug.Assert(arr != null, "The array is not initialized!");
            Debug.Assert(arr.Length > 0, "The array is empty!");
            Debug.Assert(0 <= startIndex && startIndex <= arr.Length - 1, "Invalid start index!");
            Debug.Assert(0 <= endIndex && endIndex <= arr.Length - 1, "Invalid end index!");
            Debug.Assert(startIndex <= endIndex, "Start index must be smaller than end index!");
            int minElementIndex = startIndex;
            for (int i = startIndex + 1; i <= endIndex; i++)
            {
                if (arr[i].CompareTo(arr[minElementIndex]) < 0)
                {
                    minElementIndex = i;
                }
            }
            return minElementIndex;
        }

        private static void Swap<T>(ref T x, ref T y)
        {
            T oldX = x;
            x = y;
            y = oldX;
        }

        private static void QuickSort<T>(T[] arr, int left, int right) where T : IComparable<T>
        {
            Debug.Assert(arr != null, "The array is not initialized!");
            Debug.Assert(arr.Length > 0, "The array is empty!");
            if (left < right)
            {
                int pivot = Partition(arr, left, right);

                if (pivot > 1)
                {
                    QuickSort(arr, left, pivot - 1);
                }

                if (pivot + 1 < right)
                {
                    QuickSort(arr, pivot + 1, right);
                }
            }
        }

        private static int Partition<T>(T[] arr, int left, int right) where T : IComparable<T>
        {
            T pivot = arr[left];
            while (true)
            {
                while (arr[left].CompareTo(pivot) < 0)
                    left++;

                while (arr[right].CompareTo(pivot) > 0)
                    right--;

                if (left < right)
                {
                    Swap(ref arr[left], ref arr[right]);
                }
                else
                {
                    return right;
                }
            }
        }
    }
}


text:
port-redirector
===============

Windows service, redirecting incoming TCP connection (forwarding) basing on the incoming data

as example, used detection and redirectiong of RDP connections.


text:
#include "src/android_internal/power_stats.h"

#include "perfetto/ext/base/utils.h"

#include <string.h>

#include <algorithm>
#include <memory>
#include <vector>

// Legacy HAL interfacte for devices shipped before Android S.
#include <android/hardware/power/stats/1.0/IPowerStats.h>

// AIDL interface for Android S+.
#include <android/hardware/power/stats/IPowerStats.h>

#include <binder/IServiceManager.h>

namespace perfetto {
namespace android_internal {

namespace hal = android::hardware::power::stats::V1_0;
namespace aidl = android::hardware::power::stats;

namespace {

// Common interface for data from power stats service.  Devices prior to
// Android S, uses the HAL interface while device from Android S or later
// uses the AIDL interfact.
class PowerStatsDataProvider {
 public:
  virtual bool GetAvailableRails(RailDescriptor*, size_t* size_of_arr) = 0;
  virtual bool GetRailEnergyData(RailEnergyData*, size_t* size_of_arr) = 0;

  // Available from Android S+.
  virtual bool GetEnergyConsumerInfo(EnergyConsumerInfo* consumers,
                                     size_t* size_of_arr) = 0;
  virtual bool GetEnergyConsumed(EnergyEstimationBreakdown* breakdown,
                                 size_t* size_of_arr) = 0;
  virtual ~PowerStatsDataProvider() = default;
};

class PowerStatsHalDataProvider : public PowerStatsDataProvider {
 public:
  bool GetAvailableRails(RailDescriptor*, size_t* size_of_arr) override;
  bool GetRailEnergyData(RailEnergyData*, size_t* size_of_arr) override;
  bool GetEnergyConsumerInfo(EnergyConsumerInfo* consumers,
                             size_t* size_of_arr) override;
  bool GetEnergyConsumed(EnergyEstimationBreakdown* breakdown,
                         size_t* size_of_arr) override;

  PowerStatsHalDataProvider() = default;
  ~PowerStatsHalDataProvider() override = default;

 private:
  android::sp<hal::IPowerStats> svc_;
  hal::IPowerStats* MaybeGetService();
};

class PowerStatsAidlDataProvider : public PowerStatsDataProvider {
 public:
  static constexpr char INSTANCE[] =
      "android.hardware.power.stats.IPowerStats/default";

  bool GetAvailableRails(RailDescriptor*, size_t* size_of_arr) override;
  bool GetRailEnergyData(RailEnergyData*, size_t* size_of_arr) override;
  bool GetEnergyConsumerInfo(EnergyConsumerInfo* consumers,
                             size_t* size_of_arr) override;
  bool GetEnergyConsumed(EnergyEstimationBreakdown* breakdown,
                         size_t* size_of_arr) override;

  PowerStatsAidlDataProvider() = default;
  ~PowerStatsAidlDataProvider() override = default;

 private:
  android::sp<aidl::IPowerStats> svc_;

  aidl::IPowerStats* MaybeGetService();
  void ResetService();
};

PowerStatsDataProvider* GetDataProvider() {
  static std::unique_ptr<PowerStatsDataProvider> data_provider;
  if (data_provider == nullptr) {
    const android::sp<android::IServiceManager> sm =
        android::defaultServiceManager();
    if (sm->isDeclared(
            android::String16(PowerStatsAidlDataProvider::INSTANCE))) {
      data_provider = std::make_unique<PowerStatsAidlDataProvider>();
    } else {
      data_provider = std::make_unique<PowerStatsHalDataProvider>();
    }
  }
  return data_provider.get();
}

}  // anonymous namespace

bool GetAvailableRails(RailDescriptor* descriptor, size_t* size_of_arr) {
  return GetDataProvider()->GetAvailableRails(descriptor, size_of_arr);
}

bool GetRailEnergyData(RailEnergyData* data, size_t* size_of_arr) {
  return GetDataProvider()->GetRailEnergyData(data, size_of_arr);
}

bool GetEnergyConsumerInfo(EnergyConsumerInfo* consumers, size_t* size_of_arr) {
  return GetDataProvider()->GetEnergyConsumerInfo(consumers, size_of_arr);
}

bool GetEnergyConsumed(EnergyEstimationBreakdown* breakdown,
                       size_t* size_of_arr) {
  return GetDataProvider()->GetEnergyConsumed(breakdown, size_of_arr);
}

/*** Power Stats HAL Implemenation *******************************************/

using android::hardware::hidl_vec;
using android::hardware::Return;

hal::IPowerStats* PowerStatsHalDataProvider::MaybeGetService() {
  if (svc_ == nullptr) {
    svc_ = hal::IPowerStats::tryGetService();
  }
  return svc_.get();
}

bool PowerStatsHalDataProvider::GetAvailableRails(
    RailDescriptor* rail_descriptors,
    size_t* size_of_arr) {
  const size_t in_array_size = *size_of_arr;
  *size_of_arr = 0;
  hal::IPowerStats* svc = MaybeGetService();
  if (svc == nullptr) {
    return false;
  }

  hal::Status status;
  auto rails_cb = [rail_descriptors, size_of_arr, &in_array_size, &status](
                      hidl_vec<hal::RailInfo> r, hal::Status s) {
    status = s;
    if (status == hal::Status::SUCCESS) {
      *size_of_arr = std::min(in_array_size, r.size());
      for (int i = 0; i < *size_of_arr; ++i) {
        const hal::RailInfo& rail_info = r[i];
        RailDescriptor& descriptor = rail_descriptors[i];

        descriptor.index = rail_info.index;
        descriptor.sampling_rate = rail_info.samplingRate;

        strlcpy(descriptor.rail_name, rail_info.railName.c_str(),
                sizeof(descriptor.rail_name));
        strlcpy(descriptor.subsys_name, rail_info.subsysName.c_str(),
                sizeof(descriptor.subsys_name));
      }
    }
  };

  Return<void> ret = svc->getRailInfo(rails_cb);
  return status == hal::Status::SUCCESS;
}

bool PowerStatsHalDataProvider::GetRailEnergyData(
    RailEnergyData* rail_energy_array,
    size_t* size_of_arr) {
  const size_t in_array_size = *size_of_arr;
  *size_of_arr = 0;

  hal::IPowerStats* svc = MaybeGetService();
  if (svc == nullptr) {
    return false;
  }

  hal::Status status;
  auto energy_cb = [rail_energy_array, size_of_arr, &in_array_size, &status](
                       hidl_vec<hal::EnergyData> m, hal::Status s) {
    status = s;
    if (status == hal::Status::SUCCESS) {
      *size_of_arr = std::min(in_array_size, m.size());
      for (int i = 0; i < *size_of_arr; ++i) {
        const hal::EnergyData& measurement = m[i];
        RailEnergyData& element = rail_energy_array[i];

        element.index = measurement.index;
        element.timestamp = measurement.timestamp;
        element.energy = measurement.energy;
      }
    }
  };

  Return<void> ret = svc_->getEnergyData(hidl_vec<uint32_t>(), energy_cb);
  return status == hal::Status::SUCCESS;
}

bool PowerStatsHalDataProvider::GetEnergyConsumerInfo(EnergyConsumerInfo*,
                                                      size_t*) {
  return false;
}

bool PowerStatsHalDataProvider::GetEnergyConsumed(EnergyEstimationBreakdown*,
                                                  size_t*) {
  return false;
}

/*** End of Power Stats HAL Implemenation *************************************/

/*** Power Stats AIDL Implemenation *******************************************/
aidl::IPowerStats* PowerStatsAidlDataProvider::MaybeGetService() {
  if (svc_ == nullptr) {
    svc_ = android::checkDeclaredService<aidl::IPowerStats>(
        android::String16(INSTANCE));
  }
  return svc_.get();
}

void PowerStatsAidlDataProvider::ResetService() {
  svc_.clear();
}

bool PowerStatsAidlDataProvider::GetAvailableRails(RailDescriptor* descriptor,
                                                   size_t* size_of_arr) {
  const size_t in_array_size = *size_of_arr;
  *size_of_arr = 0;

  aidl::IPowerStats* svc = MaybeGetService();
  if (svc_ == nullptr) {
    return false;
  }

  std::vector<aidl::Channel> results;
  android::binder::Status status = svc->getEnergyMeterInfo(&results);
  if (!status.isOk()) {
    if (status.transactionError() == android::DEAD_OBJECT) {
      // Service has died.  Reset it to attempt to acquire a new one next time.
      ResetService();
    }
    return false;
  }

  size_t max_size = std::min(in_array_size, results.size());
  for (const auto& result : results) {
    if (*size_of_arr >= max_size) {
      break;
    }
    auto& cur = descriptor[(*size_of_arr)++];
    cur.index = result.id;
    cur.sampling_rate = 0;
    strlcpy(cur.rail_name, result.name.c_str(), sizeof(cur.rail_name));
    strlcpy(cur.subsys_name, result.subsystem.c_str(), sizeof(cur.subsys_name));
  }
  return true;
}

bool PowerStatsAidlDataProvider::GetRailEnergyData(RailEnergyData* data,
                                                   size_t* size_of_arr) {
  const size_t in_array_size = *size_of_arr;
  *size_of_arr = 0;

  aidl::IPowerStats* svc = MaybeGetService();
  if (svc == nullptr) {
    return false;
  }

  std::vector<int> ids;
  std::vector<aidl::EnergyMeasurement> results;
  android::binder::Status status = svc->readEnergyMeter(ids, &results);
  if (!status.isOk()) {
    if (status.transactionError() == android::DEAD_OBJECT) {
      // Service has died.  Reset it to attempt to acquire a new one next time.
      ResetService();
    }
    return false;
  }

  size_t max_size = std::min(in_array_size, results.size());
  for (const auto& result : results) {
    if (*size_of_arr >= max_size) {
      break;
    }
    auto& cur = data[(*size_of_arr)++];
    cur.index = result.id;
    cur.timestamp = result.timestampMs;
    cur.energy = result.energyUWs;
  }
  return true;
}

bool PowerStatsAidlDataProvider::GetEnergyConsumerInfo(
    EnergyConsumerInfo* consumers,
    size_t* size_of_arr) {
  const size_t in_array_size = *size_of_arr;
  *size_of_arr = 0;

  aidl::IPowerStats* svc = MaybeGetService();
  if (svc == nullptr) {
    return false;
  }
  std::vector<aidl::EnergyConsumer> results;
  android::binder::Status status = svc->getEnergyConsumerInfo(&results);

  if (!status.isOk()) {
    if (status.transactionError() == android::DEAD_OBJECT) {
      // Service has died.  Reset it to attempt to acquire a new one next time.
      ResetService();
    }
    return false;
  }
  size_t max_size = std::min(in_array_size, results.size());
  for (const auto& result : results) {
    if (*size_of_arr >= max_size) {
      break;
    }
    auto& cur = consumers[(*size_of_arr)++];
    cur.energy_consumer_id = result.id;
    cur.ordinal = result.ordinal;
    strlcpy(cur.type, aidl::toString(result.type).c_str(), sizeof(cur.type));
    strlcpy(cur.name, result.name.c_str(), sizeof(cur.name));
  }
  return true;
}
bool PowerStatsAidlDataProvider::GetEnergyConsumed(
    EnergyEstimationBreakdown* breakdown,
    size_t* size_of_arr) {
  const size_t in_array_size = *size_of_arr;
  *size_of_arr = 0;

  aidl::IPowerStats* svc = MaybeGetService();
  if (svc == nullptr) {
    return false;
  }

  std::vector<int> ids;
  std::vector<aidl::EnergyConsumerResult> results;
  android::binder::Status status = svc->getEnergyConsumed(ids, &results);

  if (!status.isOk()) {
    if (status.transactionError() == android::DEAD_OBJECT) {
      // Service has died.  Reset it to attempt to acquire a new one next time.
      ResetService();
    }
    return false;
  }

  size_t max_size = std::min(in_array_size, results.size());
  // Iterate through all consumer ID.
  for (const auto& result : results) {
    if (*size_of_arr >= max_size) {
      break;
    }
    auto& cur = breakdown[(*size_of_arr)++];
    cur.energy_consumer_id = result.id;
    cur.uid = ALL_UIDS_FOR_CONSUMER;
    cur.energy_uws = result.energyUWs;

    // Iterate through all UIDs for this consumer.
    for (const auto& attribution : result.attribution) {
      if (*size_of_arr >= max_size) {
        break;
      }
      auto& cur = breakdown[(*size_of_arr)++];
      cur.energy_consumer_id = result.id;
      cur.uid = attribution.uid;
      cur.energy_uws = attribution.energyUWs;
    }
  }
  return true;
}
/*** End of Power Stats AIDL Implemenation ************************************/

}  // namespace android_internal
}  // namespace perfetto


text:
#ifndef SOLIST_H
#define SOLIST_H

#define SO_NAME_MAX_PATH_SIZE 512	/* FIXME: Should be dynamic */

/* Forward declaration for target specific link map information.  This
   struct is opaque to all but the target specific file.  */
struct lm_info;

struct so_list
  {
    /* The following fields of the structure come directly from the
       dynamic linker's tables in the inferior, and are initialized by
       current_sos.  */

    struct so_list *next;	/* next structure in linked list */

    /* A pointer to target specific link map information.  Often this
       will be a copy of struct link_map from the user process, but
       it need not be; it can be any collection of data needed to
       traverse the dynamic linker's data structures. */
    struct lm_info *lm_info;

    /* Shared object file name, exactly as it appears in the
       inferior's link map.  This may be a relative path, or something
       which needs to be looked up in LD_LIBRARY_PATH, etc.  We use it
       to tell which entries in the inferior's dynamic linker's link
       map we've already loaded.  */
    char so_original_name[SO_NAME_MAX_PATH_SIZE];

    /* shared object file name, expanded to something GDB can open */
    char so_name[SO_NAME_MAX_PATH_SIZE];

    /* The following fields of the structure are built from
       information gathered from the shared object file itself, and
       are set when we actually add it to our symbol tables.

       current_sos must initialize these fields to 0.  */

    bfd *abfd;
    char symbols_loaded;	/* flag: symbols read in yet? */
    char from_tty;		/* flag: print msgs? */
    struct objfile *objfile;	/* objfile for loaded lib */
    struct section_table *sections;
    struct section_table *sections_end;
    struct section_table *textsection;
  };

struct target_so_ops
  {
    /* Adjust the section binding addresses by the base address at
       which the object was actually mapped.  */
    void (*relocate_section_addresses) (struct so_list *so,
                                        struct section_table *);

    /* Free the the link map info and any other private data
       structures associated with a so_list entry.  */
    void (*free_so) (struct so_list *so);

    /* Reset or free private data structures not associated with
       so_list entries.  */
    void (*clear_solib) (void);

    /* Target dependent code to run after child process fork.  */
    void (*solib_create_inferior_hook) (void);

    /* Do additional symbol handling, lookup, etc. after symbols
       for a shared object have been loaded.  */
    void (*special_symbol_handling) (void);

    /* Construct a list of the currently loaded shared objects.  */
    struct so_list *(*current_sos) (void);

    /* Find, open, and read the symbols for the main executable.  */
    int (*open_symbol_file_object) (void *from_ttyp);

    /* Determine if PC lies in the dynamic symbol resolution code of
       the run time loader */
    int (*in_dynsym_resolve_code) (CORE_ADDR pc);

    /* Extra hook for finding and opening a solib.  Convenience function
       for remote debuggers finding host libs */
    int (*find_and_open_solib) (char *soname,
        unsigned o_flags, char **temp_pathname);

  };

void free_so (struct so_list *so);

/* Find solib binary file and open it.  */
extern int solib_open (char *in_pathname, char **found_pathname);

/* FIXME: gdbarch needs to control this variable */
extern struct target_so_ops *current_target_so_ops;

#define TARGET_SO_RELOCATE_SECTION_ADDRESSES \
  (current_target_so_ops->relocate_section_addresses)
#define TARGET_SO_FREE_SO (current_target_so_ops->free_so)
#define TARGET_SO_CLEAR_SOLIB (current_target_so_ops->clear_solib)
#define TARGET_SO_SOLIB_CREATE_INFERIOR_HOOK \
  (current_target_so_ops->solib_create_inferior_hook)
#define TARGET_SO_SPECIAL_SYMBOL_HANDLING \
  (current_target_so_ops->special_symbol_handling)
#define TARGET_SO_CURRENT_SOS (current_target_so_ops->current_sos)
#define TARGET_SO_OPEN_SYMBOL_FILE_OBJECT \
  (current_target_so_ops->open_symbol_file_object)
#define TARGET_SO_IN_DYNSYM_RESOLVE_CODE \
  (current_target_so_ops->in_dynsym_resolve_code)
#define TARGET_SO_FIND_AND_OPEN_SOLIB \
  (current_target_so_ops->find_and_open_solib)

#endif


text:
& (Join-Path -Path $PSScriptRoot -ChildPath 'Initialize-Tests.ps1' -Resolve)

function GivenSession
{
    $script:session = New-ProGetTestSession
    $script:baseDirectory = (split-path -Path $TestDrive.FullName -leaf)
    $feed = Test-ProGetFeed -Session $session -Name $baseDirectory -Type 'Asset'
    if( !$feed )
    {
        New-ProGetFeed -Session $session -Name $baseDirectory -Type 'Asset'
    }
}

function GivenAssets
{
    param(
        [string[]]
        $Name,
        [string]
        $WithContent = 'test'
    )
    foreach($file in $Name)
    {
        New-Item -Path (Join-Path -Path $TestDrive.FullName -ChildPath $file) -Type 'file' -value $WithContent -Force
        Set-ProGetAsset -Session $session -DirectoryName $baseDirectory -Path $file -FilePath (Join-Path -Path $TestDrive.FullName -ChildPath $file)
    }
}

function WhenAssetIsRemoved
{
    param(
        [string]
        $Filter,
        [string]
        $Subdirectory
    )
    $Global:Error.Clear()
    Remove-ProGetAsset -Session $session -DirectoryName $baseDirectory -Path $Subdirectory -Filter $Filter -ErrorAction SilentlyContinue
}

function ThenNoErrorShouldBeThrown
{
    It 'should not throw an error' {
        $Global:Error | Should -BeNullOrEmpty
    }
}

function ThenAssetShouldExist
{
    param(
        [string[]]
        $Name,
        [string]
        $directory
    )
    foreach($file in $Name)
    {
        it ('should contain the file {0}' -f $file) {
            Get-ProGetAsset -session $session -DirectoryName $baseDirectory -Path $directory | Where-Object { $_.name -match $file } | should -not -BeNullOrEmpty
        }
    }
}

function ThenAssetShouldNotExist
{
    param(
        [string[]]
        $Name,
        [string]
        $directory
    )
    foreach($file in $Name)
    {
        it ('should not contain the file {0}' -f $file) {
            Get-ProGetAsset -session $session -DirectoryName $baseDirectory -Path $directory | Where-Object { $_.name -match $file } | should -BeNullOrEmpty
        }
    }
}
Describe 'Remove-ProGetAsset.When Asset is removed successfully'{
    GivenSession
    GivenAssets -Name 'foo','bar'
    WhenAssetIsRemoved -filter 'foo'
    ThenAssetShouldNotExist -Name 'foo'
    ThenAssetShouldExist -Name 'bar'
    ThenNoErrorShouldBeThrown
}

Describe 'Remove-ProGetAsset.When Asset is removed from a subdirectory successfully'{
    GivenSession
    GivenAssets -Name 'bar/foo'
    WhenAssetIsRemoved -filter 'foo' -Subdirectory 'bar'
    ThenAssetShouldNotExist -Name 'foo' -directory 'bar'
    ThenNoErrorShouldBeThrown
}

Describe 'Remove-ProGetAsset.When multiple Assets are removed successfully'{
    GivenSession
    GivenAssets -Name 'foo','bar'
    WhenAssetIsRemoved
    ThenAssetShouldNotExist -Name 'foo','bar'
    ThenNoErrorShouldBeThrown
}

Describe 'Remove-ProGetAsset.When filtered assets are removed successfully'{
    GivenSession
    GivenAssets -Name 'foo','bar','foobar'
    WhenAssetIsRemoved -Filter 'foo*'
    ThenAssetShouldNotExist -Name 'foo','foobar'
    ThenAssetShouldExist -Name 'bar'
    ThenNoErrorShouldBeThrown
}

Describe 'Remove-ProGetAsset.When Asset does not exist' {
    GivenSession
    GivenAssets -Name 'foo'
    WhenAssetIsRemoved -Filter 'bar'
    ThenAssetShouldNotExist -Name 'bar'
    ThenAssetShouldExist -Name 'foo'
    ThenNoErrorShouldBeThrown
}

Describe 'Remove-ProGetAsset.When Asset is removed removed twice'{
    GivenSession
    GivenAssets -Name 'foo'
    WhenAssetIsRemoved -Filter 'foo'
    WhenAssetIsRemoved -Filter 'foo'
    ThenAssetShouldNotExist -Name 'foo'
    ThenNoErrorShouldBeThrown
}


text:
describe "brew list", :integration_test do
  let(:formulae) { %w[bar foo qux] }

  it "prints all installed Formulae" do
    formulae.each do |f|
      (HOMEBREW_CELLAR/f/"1.0/somedir").mkpath
    end

    expect { brew "list" }
      .to output("#{formulae.join("\n")}\n").to_stdout
      .and not_to_output.to_stderr
      .and be_a_success
  end
end


text:
var THREE = require('../../lib/three.min.js');
THREE.OrbitControls = require('../../lib/OrbitControls.js');
var Style = require('./../core/Pretzel.Style.js');
var Stats = require('../../lib/stats.min.js');
var DecoratorFactory = require('./Pretzel.DecoratorFactory.js');

/**
 *
 * @param divId {String}
 * @constructor
 */
var Viewer = function (divId) {
    this.divId = divId;
    this.scene = null;
    this.camera = null;
    this.renderer = null;
    this.container = null;
    this.controls = null;
    this.clock = null;
    //this.stats = null;
    console.log(divId + " created")
};

Viewer.prototype = {
    constructor: Viewer,

    /**
     *
     * Init needs to be called before anything to setup the scene
     * This function setup scene, camera, renderer, container, controls, and stats
     */
    init: function () {
        //Main scene
        this.scene = new THREE.Scene();
        var SCREEN_WIDTH = document.getElementById(this.divId).clientWidth,
            SCREEN_HEIGHT = document.getElementById(this.divId).clientHeight;
        //Camera
        var VIEW_ANGLE = 45, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 1, FAR = 10000;
        this.camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
        this.scene.add(this.camera);
        this.camera.position.set(-1000, 1000, 0);
        this.camera.lookAt(new THREE.Vector3(0, 0, 0));

        //Viewer
        this.renderer = new THREE.WebGLRenderer({antialias: true, alpha: false});
        this.renderer.setSize(SCREEN_WIDTH, SCREEN_HEIGHT);
        this.renderer.setClearColor(0xffffff);
        this.renderer.shadowMapEnabled = true;
        this.renderer.shadowMapSoft = true;

        // prepare container
        this.container = document.getElementById(this.divId);
        this.container.appendChild(this.renderer.domElement);

        //Orbit control
        this.controls = new THREE.OrbitControls(this.camera, this.renderer.domElement);
        this.controls.target = new THREE.Vector3(0, 0, 0);

        // prepare clock
        this.clock = new THREE.Clock();

        //FPS stats
        //this.stats = new Stats();
        //this.stats.domElement.style.position = 'absolute';
        //this.stats.domElement.style.bottom = '0px';
        //this.stats.domElement.style.zIndex = 10;
        //this.container.appendChild(this.stats.domElement);

        //Directional light
        var dLight = new THREE.DirectionalLight(0xffffff);
        dLight.position.set(1, 1000, 1);
        dLight.castShadow = true;
        dLight.shadowCameraVisible = false;
        dLight.shadowDarkness = 0.2;
        dLight.shadowMapWidth = dLight.shadowMapHeight = 1000;
        this.scene.add(dLight);

        // add simple ground
        //var groundGeometry = new THREE.PlaneGeometry(5000, 5000, 1, 1);
        var groundGeometry = new THREE.PlaneBufferGeometry(3000, 3000, 1, 1);
        var ground = new THREE.Mesh(groundGeometry, new THREE.MeshPhongMaterial({color: 0xefefef}));
        ground.position.y = -200;
        ground.rotation.x = -Math.PI / 2;
        ground.receiveShadow = false;
        this.scene.add(ground);
    },

    /**
     *
     * @param v1 {THREE.Vector3}
     * @param v2 {THREE.Vector3}
     * @param _style {Style}
     * @private
     */
    _renderTube: function (v1, v2, style) {
        var tube = new THREE.Mesh(new THREE.TubeGeometry(new THREE.LineCurve3(v1, v2), 0, style.getRadius()), style.getMaterial());
        tube.castShadow = tube.receiveShadow = false;
        this.scene.add(tube);
    },

    /**
     *
     * @param v1 {THREE.Vector3{
     * @param _style {Style}
     * @private
     */
    _renderSphere: function (v1, style) {
        var sphere = new THREE.Mesh(new THREE.SphereGeometry(style.getRadius(), 7, 7), style.getMaterial());
        sphere.castShadow = sphere.receiveShadow = false;
        sphere.position.x = v1.x;
        sphere.position.y = v1.y;
        sphere.position.z = v1.z;
        this.scene.add(sphere);
    },

    /**
     *
     * @param v1
     * @param v2
     * @param style
     * @private
     */
    _renderLine: function (v1, v2, style) {
        var lineGeometry = new THREE.Geometry();
        lineGeometry.vertices.push(v1);
        lineGeometry.vertices.push(v2);
        var line = new THREE.Line(lineGeometry, style.material);
        this.scene.add(line);
    },

    /**
     *
     */
    update: function () {
        this.controls.update(this.clock.getDelta());

        //this.stats.update();
        // smoothly move the particleLight
        var timer = Date.now() * 0.000025;
        //particleLight.position.x = Math.sin(timer * 5) * 300;
        //particleLight.position.z = Math.cos(timer * 5) * 300;
    },

    /**
     *
     */
    render: function () {
        if (this.renderer) {
            this.renderer.render(this.scene, this.camera);
        }
    },

    /**
     *
     */
    animate: function () {
        var a = this.animate();
        window.requestAnimationFrame(function () {
            a;
        });
        this.render();
        this.update();
    },

    /**
     *
     * @param structure {Pretzel.Structure}
     */
    viewStructure: function (structure) {
        var points = structure.getAnchors();

        for (var i = 0; i < points.length - 1; i++) {
            this._renderTube(points[i], points[i + 1], structure.getStyle());
            this._renderSphere(points[i], structure.getStyle());
        }
        this._renderSphere(points[points.length - 1], structure.getStyle());
    },

    /**
     *
     * @param decorator
     */
    viewDecorator: function (decorator) {
        if (decorator.type == DecoratorFactory.TYPE.SEGMENT_DECORATOR) {
            this.viewStructure(decorator);
        } else if (decorator.type == DecoratorFactory.TYPE.POINT_DECORATOR) {
            this._renderSphere(decorator.getAnchors()[0], decorator.style);
        } else if (decorator.type == DecoratorFactory.TYPE.ASSOCIATE_DECORATOR) {
            this._renderLine(decorator.getAnchors()[0], decorator.getAnchors()[1], decorator.getStyle());
        }
    },

    /**
     *
     * @param bag {Pretzel.Bag}
     */
    viewBag: function (bag) {

    },

    initializeVisual: function () {
        this.render();
        this.animate();
    }
};

module.exports = Viewer;


text:
<?php

namespace Krtv\Bundle\AppBundle\Entity\Transfer;

use Doctrine\ORM\Mapping as ORM;
use Krtv\Bundle\AppBundle\Entity\ProviderAccount;

/**
 * Class TransferChange
 * @package Krtv\Bundle\AppBundle\Entity\Transfer
 *
 * @ORM\Entity()
 * @ORM\Table(name="transfer_bridge_messages")
 * @ORM\HasLifecycleCallbacks()
 */
class BridgeMessage
{
    const STATE_NEW         = 0;
    const STATE_SCHEDULED   = 1;
    const STATE_IN_PROGRESS = 2;
    const STATE_COMPLETED   = 3;
    const STATE_ERROR       = -1;

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Krtv\Bundle\AppBundle\Entity\ProviderAccount")
     */
    private $provider;

    /**
     * @ORM\Column(type="array")
     */
    private $data;

    /**
     * @ORM\Column(type="integer")
     */
    private $state;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     *
     */
    public function __construct()
    {
        $this->state     = self::STATE_NEW;
        $this->createdAt = new \DateTime();
    }

    /**
     * @return int
     */
    public function getState()
    {
        return $this->state;
    }

    /**
     * @param int $state
     */
    public function setState($state)
    {
        $this->state = $state;
    }

    /**
     * @return array
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param \DOMElement $data
     */
    public function setData(\DOMElement $data)
    {
        $this->data = $this->xmlToArray($data);
    }

    /**
     * @return ProviderAccount
     */
    public function getProvider()
    {
        return $this->provider;
    }

    /**
     * @param ProviderAccount $provider
     */
    public function setProvider(ProviderAccount $provider)
    {
        $this->provider = $provider;
    }

    /**
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * @param \DateTime $createdAt
     */
    public function setCreatedAt(\DateTime $createdAt)
    {
        $this->createdAt = $createdAt;
    }

    /**
     * @param $root
     * @return array
     */
    private function xmlToArray($root)
    {
        $result = array();

        if ($root->hasAttributes()) {
            $attributes = $root->attributes;
            foreach ($attributes as $attr) {
                $result['@attributes'][$attr->name] = $attr->value;
            }
        }

        if ($root->hasChildNodes()) {
            $children = $root->childNodes;
            if ($children->length == 1) {
                $child = $children->item(0);
                if ($child->nodeType == XML_TEXT_NODE) {
                    $result['_value'] = $child->nodeValue;
                    return count($result) == 1
                        ? $result['_value']
                        : $result;
                }
            }
            $groups = array();
            foreach ($children as $child) {
                if (!isset($result[$child->nodeName])) {
                    $result[$child->nodeName] = $this->xmlToArray($child);
                } else {
                    if (!isset($groups[$child->nodeName])) {
                        $result[$child->nodeName] = array($result[$child->nodeName]);
                        $groups[$child->nodeName] = 1;
                    }
                    $result[$child->nodeName][] = $this->xmlToArray($child);
                }
            }
        }

        return $result;
    }
}


text:
/*
 TODO: Make it possible to link to external xml files containing module configurations
 TODO: Reading of modification mode - is there any use for configuration of modification mode?
 TODO: XML Schema.
*/

package com.teletalk.jserver.property;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;

import com.teletalk.jserver.JServer;
import com.teletalk.jserver.JServerConstants;
import com.teletalk.jserver.SubComponent;
import com.teletalk.jserver.load.LoadManager;
import com.teletalk.jserver.log.CriticalErrorAppenderComponent;
import com.teletalk.jserver.log.FileAppenderComponent;
import com.teletalk.jserver.net.sns.client.SnsClientManager;
import com.teletalk.jserver.net.sns.server.SnsManager;
import com.teletalk.jserver.periodic.PeriodicActionManager;
import com.teletalk.jserver.rmi.RmiManager;
import com.teletalk.jserver.spring.SpringApplicationContext;
import com.teletalk.jserver.statistics.StatisticsManager;
import com.teletalk.jserver.tcp.http.HttpServer;

/**
 * PersistentPropertyStorage implementation that stores configuration to an XML-file.
 *
 * @since 1.3.2
 *
 * @author Tobias Löfstrand
 */
public class XmlConfigurationFile implements PersistentPropertyStorage
{
   private static final String JSERVER_ROOT_TAG = "JServer";

   private static final String CONFIGURATION_MANAGER_TAG = JServerConstants.CONFIGURATION_MANAGER_ALIAS;

   private static final String EVENT_QUEUE_TAG = JServerConstants.EVENT_QUEUE_ALIAS;

   private static final String LOG_MANAGER_TAG = JServerConstants.LOG_MANAGER_ALIAS;

   private static final String DEFAULT_FILE_LOGGER_TAG = JServerConstants.DEFAULT_FILE_LOGGER_ALIAS; // Since 2.1

   private static final String DEFAULT_CRITICAL_ERROR_LOGGER_TAG = JServerConstants.DEFAULT_CRITICAL_ERROR_LOGGER_ALIAS; // Since 2.1

   private static final String MAIN_HTTP_SERVER_TAG = JServerConstants.MAIN_HTTP_SERVER_ALIAS;

   private static final String RMI_MANAGER_TAG = JServerConstants.RMI_MANAGER_ALIAS;

   private static final String PERIODIC_ACTION_MANAGER_TAG = JServerConstants.PERIODIC_ACTION_MANAGER_ALIAS;

   private static final String LOAD_MANAGER_TAG = JServerConstants.LOAD_MANAGER_ALIAS;

   private static final String STATISTICS_MANAGER_TAG = JServerConstants.STATISTICS_MANAGER_ALIAS; // Since 2.1

   private static final String SPRING_APPLICATION_CONTEXT_TAG = JServerConstants.SPRING_APPLICATION_CONTEXT_ALIAS; // Since 2.1

   private static final String SNS_CLIENT_TAG = JServerConstants.SNS_CLIENT_MANAGER_ALIAS; // Since 2.1 (20050503)

   private static final String SNS_SERVER_TAG = JServerConstants.SNS_MANAGER_ALIAS; // Since 2.1 (20050503)

   private static final String RMI_ADMINISTRATION_TAG = JServerConstants.RMI_ADMINISTRATION_ALIAS; // Administration

   private static final HashSet ComponentTagNames = new HashSet();

   static
   {
      ComponentTagNames.add(CONFIGURATION_MANAGER_TAG);
      ComponentTagNames.add(LOG_MANAGER_TAG);
      ComponentTagNames.add(DEFAULT_FILE_LOGGER_TAG);
      ComponentTagNames.add(DEFAULT_CRITICAL_ERROR_LOGGER_TAG);
      ComponentTagNames.add(EVENT_QUEUE_TAG);
      ComponentTagNames.add(MAIN_HTTP_SERVER_TAG);
      ComponentTagNames.add(RMI_MANAGER_TAG);
      ComponentTagNames.add(PERIODIC_ACTION_MANAGER_TAG);
      ComponentTagNames.add(LOAD_MANAGER_TAG);
      ComponentTagNames.add(STATISTICS_MANAGER_TAG);
      ComponentTagNames.add(SPRING_APPLICATION_CONTEXT_TAG);
      ComponentTagNames.add(SNS_CLIENT_TAG);
      ComponentTagNames.add(SNS_SERVER_TAG);
      ComponentTagNames.add(RMI_ADMINISTRATION_TAG);
   }

   private static final String SUB_SYSTEM_TAG = "SubSystem"; // REMOVE?

   private static final String SUB_COMPONENT_TAG = "SubComponent"; // REMOVE?

   private static final String COMPONENT_TAG = "Component";

   private static final String PROPERTY_TAG = "property";

   private static final String PROPERTY_META_DATA_TAG = "metaData";

   private static final String COMPONENT_NAME_ATTRIBUTE = "name";

   private static final String COMPONENT_CLASS_ATTRIBUTE = "class";

   private static final String PROPERTY_NAME_ATTRIBUTE = "name";

   private static final String PROPERTY_VALUE_ATTRIBUTE = "value";

   private static final String PROPERTY_META_DATA_NAME_ATTRIBUTE = "name";

   //private static final String PROPERTY_MODIFICATION_MODE_ATTRIBUTE = "mode";

   private static final String CONFIGURATION_BACKUP_FILE_EXTENSION = ".bak";

   private static final String CONFIGURATION_ERROR_BACKUP_FILE_EXTENSION = ".err";

   /**   The default filename for properties. */
   public static String DEFAULT_CONFIGURATION_FILE_NAME = "jserver.xml";

   private String configurationFileName;

   private PropertyManager propertyManager;
   private String fullName;

   private DocumentBuilder xmlDocumentBuilder = null;

   private Transformer xmlTransformer = null;

   private Document configurationFileDocument;

   /**
    * Creates a new XmlConfigurationFile.
    */
   public XmlConfigurationFile()
   {
      this(null);
   }

   /**
    * Creates a new XmlConfigurationFile.
    */
   public XmlConfigurationFile(final String propertiesFileName)
   {
      this.configurationFileName = propertiesFileName;
      if( this.configurationFileName == null ) this.configurationFileName = DEFAULT_CONFIGURATION_FILE_NAME;
   }

   /**
    * Sets the name of the file used for persistent storage of properties.
    *
    * @param propertiesFileName
    */
   public void setPersistentPropertyStorageFile(final String propertiesFileName)
   {
      this.configurationFileName = propertiesFileName;
      if( this.configurationFileName == null ) this.configurationFileName = DEFAULT_CONFIGURATION_FILE_NAME;
   }

   /**
    * Initializes this PersistentPropertyStorage.
    *
    * @param propertyManager the PropertyManager object to which this PersistentPropertyStorage is to belong to.
    */
   public void init(final PropertyManager propertyManager)
   {
      this.propertyManager = propertyManager;

      this.fullName = propertyManager.getFullName() + ".XmlConfigurationFile";

      DocumentBuilderFactory docFactory = null;

      // Get document builder factory
      try
      {
         docFactory = DocumentBuilderFactory.newInstance();
         docFactory.setValidating(false);
         docFactory.setIgnoringComments(false);
         docFactory.setIgnoringElementContentWhitespace(false);
         //docFactory.setExpandEntityReferences(false);

         xmlDocumentBuilder = null;

         // Get document builder
         try
         {
            xmlDocumentBuilder = docFactory.newDocumentBuilder();
         }
         catch (ParserConfigurationException pce)
         {
            this.propertyManager.logError(this.fullName, "Initialization error - failed to create DocumentBuilder.", pce);
            System.out.println("Initialization error - failed to create DocumentBuilder.");
            pce.printStackTrace();
         }
      }
      catch(Exception e)
      {
         this.propertyManager.logError(this.fullName, "Initialization error - failed to create DocumentBuilder/DocumentBuilderFactory.", e);
         System.out.println("Initialization error - failed to create DocumentBuilder/DocumentBuilderFactory.");
         e.printStackTrace();
      }

      TransformerFactory transFactory = null;

      // Get transformer factory
      try
      {
         transFactory = TransformerFactory.newInstance();

         // Get transformer
         try
         {
            xmlTransformer = transFactory.newTransformer();
            xmlTransformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, JSERVER_ROOT_TAG);
            xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
            xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
            xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");
         }
         catch (TransformerConfigurationException tce)
         {
            this.propertyManager.logError("Initialization error - failed to create Transformer!", tce);
            System.out.println("Initialization error - failed to create Transformer!");
            tce.printStackTrace();
         }
      }
      catch(Exception e)
      {
         this.propertyManager.logError(this.fullName, "Initialization error - failed to create Transformer/TransformerFactory!", e);
         System.out.println("Initialization error - failed to create Transformer/TransformerFactory!");
         e.printStackTrace();
      }
   }

   /**
    * Parses a component element.
    */
   private void parseComponentElement(final Element element, final String componentName)
   {
      final NodeList childNodes = element.getChildNodes();
      Element childElement;
      String childElementName;
      String childComponentName;
      String childComponentClass;
      boolean predefinedComponent;
      String predefinedComponentName;

      if( childNodes != null )
      {
         for(int i=0; i<childNodes.getLength(); i++)
         {
            if( childNodes.item(i) instanceof Element )
            {
               childElement = (Element)childNodes.item(i);
               childElementName = childElement.getNodeName();

               if( PROPERTY_TAG.equalsIgnoreCase(childElementName) )
               {
                  this.parsePropertyElement(childElement, componentName);
               }
               else
               {
                  predefinedComponentName = null;

                  if( COMPONENT_TAG.equalsIgnoreCase(childElementName) ||
                        SUB_SYSTEM_TAG.equalsIgnoreCase(childElementName) ||
                        SUB_COMPONENT_TAG.equalsIgnoreCase(childElementName) )
                  {
                     predefinedComponent = false;
                  }
                  else
                  {
                     predefinedComponent = true;
                     if( this.isCoreComponentTagName(childElementName) ) predefinedComponentName = childElementName;
                  }

                  childComponentName = childElement.hasAttribute(COMPONENT_NAME_ATTRIBUTE) ? childElement.getAttribute(COMPONENT_NAME_ATTRIBUTE) : predefinedComponentName;
                  if( childComponentName != null )
                  {
                     // Get component class (by "class" attribute)
                     if( !childElement.hasAttribute(COMPONENT_CLASS_ATTRIBUTE) ) childComponentClass = null;
                     else childComponentClass = childElement.getAttribute(COMPONENT_CLASS_ATTRIBUTE);

                     // Attempt to get implementation class attribute by SubComponent.IMPLEMENTATION_CLASS_NAME_PROPERTY name
                     if( (childComponentClass == null) && childElement.hasAttribute(SubComponent.IMPLEMENTATION_CLASS_NAME_PROPERTY) )
                     {
                        childComponentClass = childElement.getAttribute(SubComponent.IMPLEMENTATION_CLASS_NAME_PROPERTY);
                     }

                     childComponentName = SubComponent.validateName(childComponentClass, childComponentName);

                     // Make childComponentName in to full component name
                     childComponentName = componentName + "." + childComponentName;

                     if( predefinedComponent )
                     {
                        if( DEFAULT_FILE_LOGGER_TAG.equalsIgnoreCase(childElementName) )
                        {
                           if (childComponentClass == null) childComponentClass = FileAppenderComponent.class.getName();
                           propertyManager.registerDynamicCoreSystem(PropertyManager.DEFAULT_FILE_LOGGER_ALIAS, childComponentName);
                        }
                        if( DEFAULT_CRITICAL_ERROR_LOGGER_TAG.equalsIgnoreCase(childElementName) )
                        {
                           if( childComponentClass == null ) childComponentClass = CriticalErrorAppenderComponent.class.getName();
                           propertyManager.registerDynamicCoreSystem(PropertyManager.DEFAULT_CRITICAL_ERROR_LOGGER_ALIAS, childComponentName);
                        }
                        else if( MAIN_HTTP_SERVER_TAG.equalsIgnoreCase(childElementName) )
                        {
                           if( childComponentClass == null ) childComponentClass = HttpServer.class.getName();
                           propertyManager.registerDynamicCoreSystem(PropertyManager.MAIN_HTTP_SERVER_ALIAS, childComponentName);
                        }
                        else if( RMI_MANAGER_TAG.equalsIgnoreCase(childElementName) )
                        {
                           if( childComponentClass == null ) childComponentClass = RmiManager.class.getName();
                           propertyManager.registerDynamicCoreSystem(PropertyManager.RMI_MANAGER_ALIAS, childComponentName);
                        }
                        else if( PERIODIC_ACTION_MANAGER_TAG.equalsIgnoreCase(childElementName) )
                        {
                           if( childComponentClass == null ) childComponentClass = PeriodicActionManager.class.getName();
                           propertyManager.registerDynamicCoreSystem(PropertyManager.PERIODIC_ACTION_MANAGER_ALIAS, childComponentName);
                        }
                        else if( LOAD_MANAGER_TAG.equalsIgnoreCase(childElementName) )
                        {
                           if( childComponentClass == null ) childComponentClass = LoadManager.class.getName();
                           propertyManager.registerDynamicCoreSystem(PropertyManager.LOAD_MANAGER_ALIAS, childComponentName);
                        }
                        else if( STATISTICS_MANAGER_TAG.equalsIgnoreCase(childElementName) )
                        {
                           if( childComponentClass == null ) childComponentClass = StatisticsManager.class.getName();
                           propertyManager.registerDynamicCoreSystem(PropertyManager.STATISTICS_MANAGER_ALIAS, childComponentName);
                        }
                        else if( SPRING_APPLICATION_CONTEXT_TAG.equalsIgnoreCase(childElementName) )
                        {
                           if( childComponentClass == null ) childComponentClass = SpringApplicationContext.class.getName();
                           propertyManager.registerDynamicCoreSystem(PropertyManager.SPRING_APPLICATION_CONTEXT_ALIAS, childComponentName);
                        }
                        else if( SNS_CLIENT_TAG.equalsIgnoreCase(childElementName) )
                        {
                           if( childComponentClass == null ) childComponentClass = SnsClientManager.class.getName();
                           propertyManager.registerDynamicCoreSystem(PropertyManager.SNS_CLIENT_MANAGER_ALIAS, childComponentName);
                        }
                        else if( SNS_SERVER_TAG.equalsIgnoreCase(childElementName) )
                        {
                           if( childComponentClass == null ) childComponentClass = SnsManager.class.getName();
                           propertyManager.registerDynamicCoreSystem(PropertyManager.SNS_MANAGER_ALIAS, childComponentName);
                        }
                        else if( RMI_ADMINISTRATION_TAG.equalsIgnoreCase(childElementName) )
                        {
                           propertyManager.registerDynamicCoreSystem(PropertyManager.RMI_ADMINISTRATION_ALIAS, childComponentName);
                        }
                        /*else
                        {
                           // Unknown
                        }*/
                     }

                     if( childComponentClass != null )
                     {
                        this.propertyManager.addImplementationClassProperty(childComponentName, childComponentClass);
                     }

                     this.parseComponentElement(childElement, childComponentName);
                  }
                  else
                  {
                     this.propertyManager.logError("No name specified for " + childElementName + " tag under " + element.getTagName() + ". Configuration data will not be read for this component.");
                  }
               }
            }
         }
      }
   }

   /**
    */
   private void parsePropertyElement(final Element element, final String ownerName)
   {
      String name = element.getAttribute(PROPERTY_NAME_ATTRIBUTE);
      if( element.hasAttribute(PROPERTY_NAME_ATTRIBUTE) && (name != null) )
      {
         ArrayList values = new ArrayList();
         String bodyTextValue = null;
         HashMap metaData = new HashMap();
         boolean persistentMetaData = false;

         String attrValue = element.getAttribute(PROPERTY_VALUE_ATTRIBUTE);
         if( element.hasAttribute(PROPERTY_VALUE_ATTRIBUTE) )
         {
            values.add(attrValue);
         }

         NodeList childNodes = element.getChildNodes();
         Element childElement;
         String childElementName;
         String childElementBodyValue;
         String metaDataName;
         String metaDataValue;

         if( childNodes != null )
         {
            for(int i=0; i<childNodes.getLength(); i++)
            {
               if( childNodes.item(i) instanceof Element )
               {
                  childElement = (Element)childNodes.item(i);
                  childElementName = childElement.getNodeName();
                  childElementBodyValue = null;

                  NodeList childChildNodes = childElement.getChildNodes();
                  if( (childChildNodes != null) && (childChildNodes.getLength() > 0) && (childChildNodes.item(0) != null) )
                  {
                     childElementBodyValue = childChildNodes.item(0).getNodeValue();
                  }

                  if( PROPERTY_VALUE_ATTRIBUTE.equalsIgnoreCase(childElementName) && (childElementBodyValue != null) )
                  {
                     values.add(childElementBodyValue);
                  }
                  else if( PROPERTY_META_DATA_TAG.equalsIgnoreCase(childElementName) )
                  {
                     persistentMetaData = true;
                     metaDataName = null;
                     if( childElement.hasAttribute(PROPERTY_META_DATA_NAME_ATTRIBUTE) )
                     {
                        metaDataName = childElement.getAttribute(PROPERTY_META_DATA_NAME_ATTRIBUTE);
                     }

                     metaDataValue = childElementBodyValue; //childElement.getAttribute(PROPERTY_VALUE_ATTRIBUTE);

                     if( metaDataName != null )
                     {
                        if( (metaDataValue == null) && childElement.hasAttribute(PROPERTY_VALUE_ATTRIBUTE) )
                        {
                           metaDataValue = childElement.getAttribute(PROPERTY_VALUE_ATTRIBUTE);
                        }

                        metaData.put(metaDataName, metaDataValue);
                     }
                  }
               }
               else if( (childNodes.item(i) instanceof Text) && (i==0) )
               {
                  bodyTextValue = childNodes.item(i).getNodeValue();
               }
            }
         }

         Property property;

         if( values.size() > 1 )
         {
            property = new MultiStringProperty(name, (String[])values.toArray(new String[0]));
         }
         else
         {
            String value = null;
            if( values.size() > 0 )
            {
               value = (String)values.get(0);
            }
            else
            {
               value = bodyTextValue;
            }

            property = new StringProperty(name, value);
         }

         if( persistentMetaData )
         {
            property.setPersistentMetaData(true);
            property.putMetaData(metaData);
         }

         this.propertyManager.addPersistentProperty(property, ownerName);
      }
   }

   /**
    * Reads all the properties stored persistently in the persistent storage represented by this PersistentPropertyStorage.
    * This method must used the method PropertyManager.addPersistentProperty() to add properties that are read from persistent storage.
    */
   public void readProperties()
   {
      File propertyFile = null;

      try
      {
         propertyFile = new File(configurationFileName + CONFIGURATION_BACKUP_FILE_EXTENSION); // Check if  backup propertyfile exists (and if so, use it)

         if( !propertyFile.exists() ) // If temporary property file didn't exist, try to use the standard one
         {
            propertyFile = new File(configurationFileName);
         }

         if( propertyFile.exists() )
         {
            this.propertyManager.logInfo(fullName, "Attempting to read configuration from '" + propertyFile.getAbsolutePath() + "'.");

            this.configurationFileDocument= this.openXMLDocument(propertyFile);

            // Get root tag
            final Element jserverRootTag = (this.configurationFileDocument != null) ? (Element)this.configurationFileDocument.getElementsByTagName(JSERVER_ROOT_TAG).item(0) : null;

            if( (this.configurationFileDocument != null) && (jserverRootTag != null) )
            {
               JServer jserver = JServer.getJServer();
               if( jserver != null )
               {
                  String jserverName = jserverRootTag.getAttribute(COMPONENT_NAME_ATTRIBUTE);
                  if( (jserverName != null) && (jserverName.trim().length() > 0) )
                  {
                     jserver.rename(jserverName);
                  }
               }
               this.parseComponentElement(jserverRootTag, JServerConstants.JSERVER_TOP_SYSTEM_ALIAS);
            }
            else
            {
               this.propertyManager.logError("Root tag '" + JSERVER_ROOT_TAG + "' not found!");
               System.out.println("Root tag '" + JSERVER_ROOT_TAG + "' not found!");
            }
         }
         else
         {
				this.propertyManager.logWarning(fullName, "Configuration file (" + configurationFileName + ") not found!");
            System.out.println("Configuration file (" + configurationFileName + ") not found!");
         }
      }
      catch(Exception e)
      {
         if( propertyFile != null )
         {
            File errPropertyFile = new File(configurationFileName + CONFIGURATION_ERROR_BACKUP_FILE_EXTENSION);
            if( errPropertyFile.exists() ) errPropertyFile = new File(configurationFileName + CONFIGURATION_ERROR_BACKUP_FILE_EXTENSION + System.currentTimeMillis());
            propertyFile.renameTo(errPropertyFile);
         }
         this.propertyManager.logError("Configuration document parsing failed - Exception while parsing.", e);
         System.out.println("Configuration document parsing failed - Exception while parsing.");
         e.printStackTrace();
      }
   }

   /**
    * Writes properties to the persistent storage represented by this PersistentPropertyStorage. The map specified
    * by parameter <code>properties</code> contains names of property groups (SubComponents and SubSystems) mapped
    * with lists (java.lang.List objects) of properties.
    *
    * @param persistentProperties the properties to be save to persistent storage.
    */
   public boolean writeProperies(final Map persistentProperties)
   {
      File propertyFile = new File(this.configurationFileName);
      File backupPropertyFile = new File(this.configurationFileName + CONFIGURATION_BACKUP_FILE_EXTENSION);
      if( backupPropertyFile.exists() ) backupPropertyFile.delete();
      propertyFile.renameTo(backupPropertyFile);

		try
		{
         Element jserverRootTag;
			if( this.configurationFileDocument == null )
         {
            this.configurationFileDocument = this.xmlDocumentBuilder.newDocument();
            jserverRootTag = this.configurationFileDocument.createElement(JSERVER_ROOT_TAG);
            this.configurationFileDocument.appendChild(jserverRootTag);
         }
         else
         {
            //  Get root tag
            jserverRootTag = (this.configurationFileDocument != null) ? (Element)this.configurationFileDocument.getElementsByTagName(JSERVER_ROOT_TAG).item(0) : null;
         }

			if( (this.configurationFileDocument != null) && (jserverRootTag != null) )
			{
            JServer jserver = JServer.getJServer();
            if( jserver != null )
            {
               jserverRootTag.setAttribute(COMPONENT_NAME_ATTRIBUTE, jserver.getName());
            }

				this.updateComponentElement(jserverRootTag, JServerConstants.JSERVER_TOP_SYSTEM_ALIAS, persistentProperties, true, 0);

            FileOutputStream fout = new FileOutputStream(propertyFile);
            StreamResult streamResult = new StreamResult(fout); // StreamResult(OutputStream) is used instead of StreamResult(File) due to strange errors in some environments...
            xmlTransformer.transform(new DOMSource(this.configurationFileDocument), streamResult);
            fout.flush();
            try{
            fout.close();
            }catch(Exception e){}
            streamResult = null;
            System.runFinalization();
            Thread.yield();

            backupPropertyFile.delete();

            return true;
			}

         return false;
		}
		catch(Exception e)
		{
         this.propertyManager.logError(this.fullName, "Error while storing configuration!", e);

         return false;
		}
   }

	/**
	 */
	private boolean updateComponentElement(final Element element, final String componentName, final Map persistentProperties, final int indentLevel)
	{
	   return updateComponentElement(element, componentName, persistentProperties, false, indentLevel);
	}

	/**
	 */
	private boolean updateComponentElement(final Element element, final String componentName, final Map persistentProperties, final boolean isRoot, final int indentLevel)
	{
   	final NodeList childNodes = element.getChildNodes();
		Element childElement;
		String childElementName;
		String childComponentName;
      String predefinedComponentName;
		Property property;
		boolean propertyElementsExists = false;
		List componentProperties = (List)persistentProperties.get(componentName);
		//boolean addJServerPropertiesComment = isRoot && ((childNodes == null) || (childNodes.getLength() == 0)) && (componentProperties != null) && (componentProperties.size() > 0);

      HashSet existingProperyChildElements = new HashSet();
      HashSet existingComponentChildElements = new HashSet();

      // Check if property implementationClass is set
      property = this.getPropertyByName(componentProperties, SubComponent.IMPLEMENTATION_CLASS_NAME_PROPERTY);
      if( (property != null) && !this.isCoreComponentTagName(element.getNodeName()) )
      {
         // Check if "implementationClass" or "class" is used as attribute name...
         if( element.hasAttribute(SubComponent.IMPLEMENTATION_CLASS_NAME_PROPERTY) )
         {
            element.removeAttribute(SubComponent.IMPLEMENTATION_CLASS_NAME_PROPERTY);
         }
         element.setAttribute(COMPONENT_CLASS_ATTRIBUTE, property.getValueAsString());
      }

		if( childNodes != null )
		{
			// Update existing elements
         for(int i=0; i<childNodes.getLength(); i++)
			{
				if( childNodes.item(i) instanceof Element )
				{
					childElement = (Element)childNodes.item(i);
					childElementName = childElement.getNodeName();

					if( PROPERTY_TAG.equalsIgnoreCase(childElementName) )
					{
                  property = this.getPropertyByName(componentProperties, childElement.getAttribute(PROPERTY_NAME_ATTRIBUTE));
                  if( !childElement.hasAttribute(PROPERTY_NAME_ATTRIBUTE) ) property = null;
                  if( (property != null) && property.isPersistent() )
                  {
                     try
                     {
                        existingProperyChildElements.add(property.getName());
                        this.updatePropertyElement(childElement, property);

                        propertyElementsExists = true;
                     }
                     catch(Exception e)
                     {
                        this.propertyManager.logError(this.fullName, "Unable to update property " + property + ".", e);
                     }
                  }
                  else if( property == null ) // If persistent property has been removed (by for instance a call to SubComponent.initFromConfiguredProperty or to PropertyManager.removePersistentProperty directly).
                  {
                     element.removeChild(childElement);
                  }
					}
					else
					{
                  predefinedComponentName = null;

                  if( !COMPONENT_TAG.equalsIgnoreCase(childElementName) &&
                        !SUB_SYSTEM_TAG.equalsIgnoreCase(childElementName) &&
                        !SUB_COMPONENT_TAG.equalsIgnoreCase(childElementName) )
                  {
                     if( this.isCoreComponentTagName(childElementName) ) predefinedComponentName = childElementName;
                  }

                  childComponentName = childElement.hasAttribute(COMPONENT_NAME_ATTRIBUTE) ? childElement.getAttribute(COMPONENT_NAME_ATTRIBUTE) : predefinedComponentName;

                  if( childComponentName != null )
						{
                     existingComponentChildElements.add(childComponentName);

                     //  Make childComponentName in to full component name
                     childComponentName = componentName + "." + childComponentName;

                     try
                     {
   							this.updateComponentElement(childElement, childComponentName, persistentProperties, indentLevel+1);
                     }
                     catch(Exception e)
                     {
                        this.propertyManager.logError(this.fullName, "Unable to update component " + childComponentName + ".", e);
                     }
						}
					}
				}
			}
      }

      String name;
      Element newElement;

      Node node = null;
      Node addBeforeNode = null;
      if( (childNodes != null) && (childNodes.getLength() > 0) )
      {
         for(int i=0; i<childNodes.getLength(); i++)
         {
            node = childNodes.item(i);

            if( !(node instanceof Text) && !(PROPERTY_TAG.equalsIgnoreCase(node.getNodeName())) )
            {
               addBeforeNode = node;
               break;
            }
         }
      }

      /*if( addJServerPropertiesComment )
      {
         Comment comment = this.configurationFileDocument.createComment("JServer top system properties begin");
         element.appendChild(this.configurationFileDocument.createTextNode("\n   ")); // Create empty line
         element.appendChild(comment);
         element.appendChild(this.configurationFileDocument.createTextNode("\n   ")); // Create empty line
      }*/

      // Add new properties
      if( componentProperties != null )
      {
         for(int i=0; i<componentProperties.size(); i++)
         {
            property = (Property)componentProperties.get(i);

            try
            {
               if( (property != null) && property.isPersistent() && !property.isUsingDefaultValue()
                     && (!existingProperyChildElements.contains(property.getName())) )
               {
                  propertyElementsExists = true;

                  newElement = this.configurationFileDocument.createElement(PROPERTY_TAG);
                  newElement.setAttribute(PROPERTY_NAME_ATTRIBUTE, property.getName());
                  if( addBeforeNode != null )
                  {
                     element.insertBefore(newElement, addBeforeNode);
                  }
                  else
                  {
                     element.appendChild(newElement);
                  }

                  this.updatePropertyElement(newElement, property);
               }
            }
            catch(Exception e)
            {
               this.propertyManager.logError(this.fullName, "Unable to store property " + property + ".", e);
            }
         }
      }

      /*if( addJServerPropertiesComment )
      {
         Comment comment = this.configurationFileDocument.createComment("JServer top system properties end");
         element.appendChild(this.configurationFileDocument.createTextNode("\n   ")); // Create empty line
         element.appendChild(comment);
         element.appendChild(this.configurationFileDocument.createTextNode("\n   ")); // Create empty line
         element.appendChild(this.configurationFileDocument.createTextNode("\n   ")); // Create empty line
      }*/

      String indent = "";
      for(int i=0; i<indentLevel; i++) indent += "   ";

      // Add new components
      ArrayList subComponentNames = getSubComponentNames(persistentProperties, componentName);
      String fullName;

      for(int i=0; i<subComponentNames.size(); i++)
      {
         name = (String)subComponentNames.get(i);

         if( (name != null) && (!existingComponentChildElements.contains(name)) )
         {
            fullName = componentName + "." + name;

            try
            {
               newElement = this.configurationFileDocument.createElement(this.getTagNameForComponent(fullName));
               newElement.setAttribute(COMPONENT_NAME_ATTRIBUTE, name);

               if( this.updateComponentElement(newElement, fullName, persistentProperties, indentLevel+1) )
               {
                  element.appendChild(this.configurationFileDocument.createTextNode("\n   " + indent)); // Create empty line
                  element.appendChild(this.configurationFileDocument.createTextNode("\n   " + indent)); // Create empty line
                  element.appendChild(newElement);
                  /*element.appendChild(this.configurationFileDocument.createTextNode("\n" + indent)); // Create empty line
                  element.appendChild(this.configurationFileDocument.createTextNode("\n" + indent)); // Create empty line*/
                  propertyElementsExists = true;
               }
            }
            catch(Exception e)
            {
               this.propertyManager.logError(this.fullName, "Unable to store component " + fullName + ".", e);
            }
         }
      }

      return propertyElementsExists;
	}

   /**
    */
   private Property getPropertyByName(final List properties, final String propertyName)
   {
      if( properties != null )
      {
         Property property;

         for(int i=0; i<properties.size(); i++)
         {
            property = (Property)properties.get(i);
            if( (property != null) && (property.getName().equals(propertyName)) )
            {
               return property;
            }
         }
      }

      return null;
   }

   /**
    */
   private ArrayList getSubComponentNames(final Map persistentProperties, final String parentComponentName)
   {
      Iterator names = persistentProperties.keySet().iterator();
      String name;
      ArrayList subComponentNames = new ArrayList();

      while(names.hasNext())
      {
         name = (String)names.next();
         if( name != null )
         {
            if( (name.startsWith(parentComponentName)) && (name.length() > parentComponentName.length()) )
            {
               name = name.substring(parentComponentName.length() + 1, name.length());
               if( name.indexOf('.') < 0 ) // If direct sub component
               {
                  subComponentNames.add(name);
               }
            }
         }
      }

      return subComponentNames;
   }

   /**
    */
   private boolean isCoreComponentTagName(final String tagName)
   {
      return ComponentTagNames.contains( tagName );
   }

   /**
    */
   private String getTagNameForComponent(final String componentFullName)
   {
      JServer jserver = JServer.getJServer();
      SubComponent subComponent;
      if( jserver != null )
      {
         subComponent = jserver.findSubComponent(componentFullName);
         if( subComponent != null )
         {
            if( subComponent == jserver.getPropertyManager() ) return CONFIGURATION_MANAGER_TAG;
            else if( subComponent == jserver.getLogManager() ) return LOG_MANAGER_TAG;
            else if( subComponent == jserver.getDefaultFileLogger() ) return DEFAULT_FILE_LOGGER_TAG;
            else if( subComponent == jserver.getDefaultCriticalErrorLogger() ) return DEFAULT_CRITICAL_ERROR_LOGGER_TAG;
            else if( subComponent == jserver.getEventQueue() ) return EVENT_QUEUE_TAG;
            else if( subComponent == jserver.getMainHttpServer() ) return MAIN_HTTP_SERVER_TAG;
            else if( subComponent == jserver.getRmiManager() ) return RMI_MANAGER_TAG;
            else if( subComponent == jserver.getPeriodicActionManager() ) return PERIODIC_ACTION_MANAGER_TAG;
            else if( subComponent == jserver.getLoadManager() ) return LOAD_MANAGER_TAG;
            else if( subComponent == jserver.getStatisticsManager() ) return STATISTICS_MANAGER_TAG;
            else if( subComponent == jserver.getSpringApplicationContext() ) return SPRING_APPLICATION_CONTEXT_TAG;
            else if( subComponent == jserver.getSnsClientManager() ) return SNS_CLIENT_TAG;
            else if( subComponent == jserver.getSnsManager() ) return SNS_SERVER_TAG;
         }
      }

      return COMPONENT_TAG;
   }

   /**
    */
   private void updatePropertyElement(final Element element, final Property property)
   {
      String values[] = property.getValuesAsStrings();
      if( values == null ) values = new String[0];

      HashMap propertyMetaData = property.getMetaData();

      NodeList childNodes = element.getChildNodes();
      Node previousNode = null;
      Element childElement;
      String childElementName;
      String metaDataName;
      String newMetaDataValue;

      ArrayList elementsToRemove = new ArrayList();

      Element newElement;

      boolean hasValueNodes = false;

      // Remove all existing sub elements (value and meta data) to assure complete update
      if( childNodes != null )
      {
         for(int i=0; i<childNodes.getLength(); i++)
         {
            if( childNodes.item(i) instanceof Element )
            {
               childElement = (Element)childNodes.item(i);
               childElementName = childElement.getNodeName();

               // Value or Meta data
               if( PROPERTY_VALUE_ATTRIBUTE.equalsIgnoreCase(childElementName) || PROPERTY_META_DATA_TAG.equalsIgnoreCase(childElementName) )
               {
                  if( PROPERTY_VALUE_ATTRIBUTE.equalsIgnoreCase(childElementName) ) hasValueNodes = true;

                  // Remove white space before
                  if( (previousNode != null) && (previousNode instanceof Text) ) elementsToRemove.add(previousNode);

                  // Mark element for removal
                  elementsToRemove.add(childElement);
               }
            }

            previousNode = childNodes.item(i);
         }
      }

      // Remove elements marked for removal
      for(int i=0; i<elementsToRemove.size(); i++)
      {
         element.removeChild((Node)elementsToRemove.get(i));
      }

      // Add new value elements
      if( (values.length <= 1) && !hasValueNodes ) // Single value and no previous value elements...
      {
         String value = (values.length > 0) ? values[0] : "";
         if( value == null ) value = "";

         try
         {
            element.setAttribute(PROPERTY_VALUE_ATTRIBUTE, value);
         }
         catch(Exception e)
         {
            // Attempt to create subnode instead
            newElement = this.configurationFileDocument.createElement(PROPERTY_VALUE_ATTRIBUTE);
            newElement.appendChild(configurationFileDocument.createTextNode(value));

            element.appendChild(newElement);
         }
      }
      else // Multiple values (or single value that was previously specified through a value sub element)
      {
         if( element.hasAttribute(PROPERTY_VALUE_ATTRIBUTE) )
         {
            element.removeAttribute(PROPERTY_VALUE_ATTRIBUTE);
         }

         for(int i=0; i<values.length; i++)
         {
            newElement = this.configurationFileDocument.createElement(PROPERTY_VALUE_ATTRIBUTE);
            newElement.appendChild(configurationFileDocument.createTextNode(values[i]));
            element.appendChild(newElement);
         }
      }

      // Add meta data
      if( property.isPersistentMetaData() )
      {
	      Iterator it = propertyMetaData.keySet().iterator();

	      // Add new meta data elements
	      while(it.hasNext())
	      {
	         metaDataName = (String)it.next();

	         try
	         {
	            //if( (metaDataName != null) && (!existingMetaDataElements.contains(metaDataName)) && !(PropertyConstants.PROPERTY_DESCRIPTION_KEY.equals(metaDataName)) )
               if( (metaDataName != null) && !(PropertyConstants.PROPERTY_DESCRIPTION_KEY.equals(metaDataName)) )
	            {
	               if( propertyMetaData.get(metaDataName) instanceof String )
	               {
	                  newMetaDataValue = (String)propertyMetaData.get(metaDataName);

	                  newElement = this.configurationFileDocument.createElement(PROPERTY_META_DATA_TAG);
	                  newElement.setAttribute(PROPERTY_META_DATA_NAME_ATTRIBUTE, metaDataName);
	                  /*try
	                  {
	                     newElement.setAttribute(PROPERTY_VALUE_ATTRIBUTE, newMetaDataValue);
	                  }
	                  catch(Exception e)
	                  {*/
	                     newElement.appendChild(configurationFileDocument.createTextNode((newMetaDataValue != null) ? newMetaDataValue : ""));
	                  //}

	                  element.appendChild(newElement);
	               }
	            }
	         }
	         catch(Exception e)
	         {
	            this.propertyManager.logError(this.fullName, "Unable to add meta data element ('" + metaDataName + "') to property " + property + ".", e);
	         }
	      }
      }
   }

   /**
    * Opens the XML-document at the specified path.
    */
   private Document openXMLDocument(final File xmlFile)
   {
      // Get document
      Document doc = null;
      try
      {
         doc = xmlDocumentBuilder.parse(xmlFile);
      }
      catch (SAXException se)
      {
         this.propertyManager.logError(this.fullName, "Configuration file parsing failed - failed to create Document.", se);
         System.out.println("Configuration file parsing failed - failed to create Document.");
         se.printStackTrace();
         return null;
      }
      catch (IOException ioe)
      {
         this.propertyManager.logError(this.fullName, "Configuration file parsing failed - failed to create Document.", ioe);
         System.out.println("Configuration file parsing failed - failed to create Document.");
         ioe.printStackTrace();
         return null;
      }

      return doc;
   }
}


text:
// source:

package nl.uva.vlet.bootstrap;

/**
 * Wrapper class to bootstrap the GridproxyDailog .
 * @see nl.uva.vlet.bootstrap.Bootstrapper
 * @author Piter T. de Boer
 */
public class GridProxyDialog
{
	public static void main(String[] args)
    {
		Bootstrapper boot=new Bootstrapper();

		try
		{
           // boot.launch(nl.uva.vlet.gui.startVBrowser,args);
            boot.launch("nl.uva.vlet.gui.util.proxy.GridProxyDialog",args);
		}
		catch (Exception e)
		{
			  System.out.println("***Error: Exception:" + e);
	          e.printStackTrace();
		}

    }

}


text:
package de.github.GSGJ.com.impl.netty;

import de.github.GSGJ.API.netty.nettycom.LoopBackTimeStamp;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LoopBackTimeStamp ts = (LoopBackTimeStamp) msg;
        ts.setRecvTimeStamp(System.nanoTime());
        System.out.println("loop delay in ms : " + 1.0 * ts.timeLapseInNanoSecond() / 1000000L);
    }

    // Here is how we send out heart beat for idle to long
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.ALL_IDLE) { // idle for no read and write
                ctx.writeAndFlush(new LoopBackTimeStamp());
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }
}


text:
from django.conf.urls import url

from .views import GithubWebhookView

urlpatterns = [
    url(r'^github/$', GithubWebhookView.as_view(), name='github'),
]


text:
<?php

class Statistics {
	public function run($name) {
		if ($name == "platform.stop.9") {
			self::record();
		}
	}

	public static function getReportToday() {
		return self::getReport(time()-86400, time());
	}

	public static function getReport($start, $end) {
		$report = array();
		$report["summary"] = array();
		$report["summary"]["views"] = PageView::count("PageView", array("`cs_created` > $start", "`cs_created` < $end"));
		$report["summary"]["visitors"] = PageView::count("PageView", array("`cs_created` > $start", "`cs_created` < $end"), "ipaddress");
		return $report;
	}

	public static function getWeekGraph($start = null, $mode = "visitors") {
		if ($start == null) {
			$start = (strtotime("midnight")+86400)-(86400*7);
			$start = time()-(86400*7);
		}
		return self::getGraph($start, time(), 7, $mode);
	}

	public static function getGraph($start, $end, $subs, $mode) {
		$data = array();
		$interval = ($end-$start)/$subs;

		for ($now = $start; $now < $end; $now += $interval) {
			$data[$now] = array(
				"label" => "test",
				"value" => self::getGraphValue($now, $now+$interval, $mode)
			);
		}

		return Component::get("OpenLaunch.Graph", array(
			"data" => $data
		));
	}

	public static function getGraphValue($start, $end, $mode) {
		if ($mode == "visitors") {
			return PageView::count("PageView", array("`cs_created`>'$start'", "`cs_created`<'$end'"),"ipaddress");
		} else if ($mode == "views") {
			return PageView::count("PageView", array("`cs_created`>'$start'", "`cs_created`<'$end'"));
		}
	}

	public static function record() {
		if (Page::getPage() != null) PageView::create("PageView", array(
			"user" => Session::getPerson(),
			"page" => Page::getPage(),
			"browser" => Request::getBrowser(),
			"platform" => Request::getPlatform(),
			"ipaddress" => Request::getIPAddress(),
			"form" => Request::getForm()
		));
	}
}


text:
namespace gpu {

namespace {
// This overrides the base class to test behaviors of virtual functions.
class TestGPUInfoEnumerator : public gpu::GPUInfo::Enumerator {
 public:
  TestGPUInfoEnumerator()
      : gpu_device_active_(false),
        video_decode_accelerator_profile_active_(false),
        video_encode_accelerator_profile_active_(false),
        image_decode_accelerator_profile_active_(false),
        overlay_info_active_(false),
        aux_attributes_active_(false) {}

  void AddInt64(const char* name, int64_t value) override {}

  void AddInt(const char* name, int value) override {}

  void AddString(const char* name, const std::string& value) override {}

  void AddBool(const char* name, bool value) override {}

  void AddBinary(const char* name,
                 const base::span<const uint8_t>& blob) override {}

  void AddTimeDeltaInSecondsF(const char* name,
                              const base::TimeDelta& value) override {}

  // Enumerator state mutator functions
  void BeginGPUDevice() override { gpu_device_active_ = true; }

  void EndGPUDevice() override { gpu_device_active_ = false; }

  void BeginVideoDecodeAcceleratorSupportedProfile() override {
    video_decode_accelerator_profile_active_ = true;
  }

  void EndVideoDecodeAcceleratorSupportedProfile() override {
    video_decode_accelerator_profile_active_ = false;
  }

  void BeginVideoEncodeAcceleratorSupportedProfile() override {
    video_encode_accelerator_profile_active_ = true;
  }

  void EndVideoEncodeAcceleratorSupportedProfile() override {
    video_encode_accelerator_profile_active_ = false;
  }

  void BeginImageDecodeAcceleratorSupportedProfile() override {
    image_decode_accelerator_profile_active_ = true;
  }

  void EndImageDecodeAcceleratorSupportedProfile() override {
    image_decode_accelerator_profile_active_ = false;
  }

  void BeginOverlayInfo() override { overlay_info_active_ = true; }

  void EndOverlayInfo() override { overlay_info_active_ = false; }

  void BeginAuxAttributes() override { aux_attributes_active_ = true; }

  void EndAuxAttributes() override { aux_attributes_active_ = false; }

  // Accessor functions
  bool gpu_device_active() const { return gpu_device_active_; }

  bool video_decode_accelerator_profile_active() const {
    return video_decode_accelerator_profile_active_;
  }

  bool video_encode_accelerator_profile_active() const {
    return video_encode_accelerator_profile_active_;
  }

  bool image_decode_accelerator_profile_active() const {
    return image_decode_accelerator_profile_active_;
  }

  bool aux_attributes_active() const { return aux_attributes_active_; }

 private:
  bool gpu_device_active_;
  bool video_decode_accelerator_profile_active_;
  bool video_encode_accelerator_profile_active_;
  bool image_decode_accelerator_profile_active_;
  bool overlay_info_active_;
  bool aux_attributes_active_;
};
}  // namespace

// Makes sure that after EnumerateFields is called, the field edit states
// are inactive
TEST(GpuInfoTest, FieldEditStates) {
  GPUInfo gpu_info;
  TestGPUInfoEnumerator enumerator;
  gpu_info.EnumerateFields(&enumerator);
  EXPECT_FALSE(enumerator.gpu_device_active());
  EXPECT_FALSE(enumerator.video_decode_accelerator_profile_active());
  EXPECT_FALSE(enumerator.video_encode_accelerator_profile_active());
  EXPECT_FALSE(enumerator.image_decode_accelerator_profile_active());
  EXPECT_FALSE(enumerator.aux_attributes_active());
}

}  // namespace gpu