text:
cp ../chapter03/contacts.component.spec.ts ../website/src/app/contacts
cp ../chapter03/contacts-edit.component.spec.ts ../website/src/app/contacts/contact-edit

# Copy over the CI configuration
cp karma-ci.conf.js ../website

# Run the karma tests
cd ../website
npm install
./node_modules/.bin/karma start karma-ci.conf.js


text:
package client

import (
	"encoding/json"
	"fmt"
	"net/url"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/opts"
	flag "github.com/docker/docker/pkg/mflag"
	"github.com/docker/docker/pkg/parsers"
	"github.com/docker/docker/registry"
	"github.com/docker/docker/runconfig"
)

// CmdCommit creates a new image from a container's changes.
//
// Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
func (cli *DockerCli) CmdCommit(args ...string) error {
	cmd := cli.Subcmd("commit", "CONTAINER [REPOSITORY[:TAG]]", "Create a new image from a container's changes", true)
	flPause := cmd.Bool([]string{"p", "-pause"}, true, "Pause container during commit")
	flComment := cmd.String([]string{"m", "-message"}, "", "Commit message")
	flAuthor := cmd.String([]string{"a", "#author", "-author"}, "", "Author (e.g., \"John Hannibal Smith <hannibal@a-team.com>\")")
	flChanges := opts.NewListOpts(nil)
	cmd.Var(&flChanges, []string{"c", "-change"}, "Apply Dockerfile instruction to the created image")
	// FIXME: --run is deprecated, it will be replaced with inline Dockerfile commands.
	flConfig := cmd.String([]string{"#run", "#-run"}, "", "This option is deprecated and will be removed in a future version in favor of inline Dockerfile-compatible commands")
	cmd.Require(flag.Max, 2)
	cmd.Require(flag.Min, 1)
	cmd.ParseFlags(args, true)

	var (
		name            = cmd.Arg(0)
		repository, tag = parsers.ParseRepositoryTag(cmd.Arg(1))
	)

	//Check if the given image name can be resolved
	if repository != "" {
		if err := registry.ValidateRepositoryName(repository); err != nil {
			return err
		}
	}

	v := url.Values{}
	v.Set("container", name)
	v.Set("repo", repository)
	v.Set("tag", tag)
	v.Set("comment", *flComment)
	v.Set("author", *flAuthor)
	for _, change := range flChanges.GetAll() {
		v.Add("changes", change)
	}

	if *flPause != true {
		v.Set("pause", "0")
	}

	var (
		config   *runconfig.Config
		response types.ContainerCommitResponse
	)

	if *flConfig != "" {
		config = &runconfig.Config{}
		if err := json.Unmarshal([]byte(*flConfig), config); err != nil {
			return err
		}
	}
	stream, _, _, err := cli.call("POST", "/commit?"+v.Encode(), config, nil)
	if err != nil {
		return err
	}

	if err := json.NewDecoder(stream).Decode(&response); err != nil {
		return err
	}

	fmt.Fprintln(cli.out, response.ID)
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
Services

eevol is focused on mobile & web applications and business analysis.

Development

                        eevol provides full services for your mobile- & web-apps. During every step of the development the team aims for stability while maintaining flexibility for the customer. eevol helps you to get started and brings your idea to the App Stores directly to the people.

Project Management

                        eevol supports our clients in driving their project within scope, time, quality and budget. Our consultants have hands-on work experience with agile methods (Scrum) and reference methodologies (Quapital-Hermes, PRINCE2).

Business Analysis

                        eevol enables our clients to change their organizational context by providing process analysis, process re-engineering, change management and process-oriented quality management.


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.github.cc007.knowledgesystem.utils;

/**
 *
 * @author Rik Schaaf aka CC007 (http://coolcat007.nl/)
 */
public abstract class FileModelLoader extends ModelLoader{

    protected final String fileName;

    public FileModelLoader(String fileName) {
        this.fileName = fileName;
    }

}


text:
require 'objspace'

module QuickMem
  class Dumps

    def self.top_allocated_objects
      objects_by_size = Hash.new { 0 }
      ObjectSpace.each_object do |obj|
        objects_by_size[obj.class] += ObjectSpace.memsize_of(obj)
      end
      get_top_50(objects_by_size)
    end

    def self.count_top_allocated_objects
      objects_by_count = Hash.new { 0 }
      ObjectSpace.each_object do |obj|
        objects_by_count[obj.class] += 1
      end
      get_top_50(objects_by_count)
    end

    class << self
      private

      def get_top_50(a_hash)
        a_hash.sort_by(&:last).reverse![0..49].to_h
      end
    end

  end
end


text:
package org.apache.gearpump.services.util

import org.apache.gearpump.cluster.ApplicationStatus
import upickle.Js
import org.apache.gearpump.cluster.worker.WorkerId
import org.apache.gearpump.util.Graph

object UpickleUtil {

  // For implicit type, we need to add EXPLICIT return type, otherwise, upickle may NOT infer the
  // reader type automatically.
  // See issue https://github.com/lihaoyi/upickle-pprint/issues/102
  implicit val graphReader: upickle.default.Reader[Graph[Int, String]] = {
    upickle.default.Reader[Graph[Int, String]] {
      case Js.Obj(verties, edges) =>
        val vertexList = upickle.default.readJs[List[Int]](verties._2)
        val edgeList = upickle.default.readJs[List[(Int, String, Int)]](edges._2)
        Graph(vertexList, edgeList)
    }
  }

  implicit val appStatusReader: upickle.default.Reader[ApplicationStatus] =
    upickle.default.Reader[ApplicationStatus] {
      case Js.Str(str) =>
        str match {
          case "pending" => ApplicationStatus.PENDING
          case "active" => ApplicationStatus.ACTIVE
          case "succeeded" => ApplicationStatus.SUCCEEDED
          case "failed" => ApplicationStatus.FAILED
          case "terminated" => ApplicationStatus.TERMINATED
          case _ => ApplicationStatus.NONEXIST
        }
    }

  implicit val workerIdReader: upickle.default.Reader[WorkerId] = upickle.default.Reader[WorkerId] {
    case Js.Str(str) =>
      WorkerId.parse(str)
  }

  implicit val workerIdWriter: upickle.default.Writer[WorkerId] = upickle.default.Writer[WorkerId] {
    case workerId: WorkerId =>
      Js.Str(WorkerId.render(workerId))
  }

  implicit val appStatusWriter: upickle.default.Writer[ApplicationStatus] =
    upickle.default.Writer[ApplicationStatus] {
    case status: ApplicationStatus =>
      Js.Str(status.toString)
  }
}


text:
require 'net/ssh/buffered_io'
require 'net/ssh/errors'
require 'net/ssh/packet'
require 'net/ssh/ruby_compat'
require 'net/ssh/transport/cipher_factory'
require 'net/ssh/transport/hmac'
require 'net/ssh/transport/state'

module Net; module SSH; module Transport

  # A module that builds additional functionality onto the Net::SSH::BufferedIo
  # module. It adds SSH encryption, compression, and packet validation, as
  # per the SSH2 protocol. It also adds an abstraction for polling packets,
  # to allow for both blocking and non-blocking reads.
  module PacketStream
    PROXY_COMMAND_HOST_IP = '<no hostip for proxy command>'.freeze

    include BufferedIo

    def self.extended(object)
      object.__send__(:initialize_ssh)
    end

    # The map of "hints" that can be used to modify the behavior of the packet
    # stream. For instance, when authentication succeeds, an "authenticated"
    # hint is set, which is used to determine whether or not to compress the
    # data when using the "delayed" compression algorithm.
    attr_reader :hints

    # The server state object, which encapsulates the algorithms used to interpret
    # packets coming from the server.
    attr_reader :server

    # The client state object, which encapsulates the algorithms used to build
    # packets to send to the server.
    attr_reader :client

    # The name of the client (local) end of the socket, as reported by the
    # socket.
    def client_name
      @client_name ||= begin
        sockaddr = getsockname
        begin
          Socket.getnameinfo(sockaddr, Socket::NI_NAMEREQD).first
        rescue
          begin
            Socket.getnameinfo(sockaddr).first
          rescue
            begin
              Socket.gethostbyname(Socket.gethostname).first
            rescue
              lwarn { "the client ipaddr/name could not be determined" }
              "unknown"
            end
          end
        end
      end
    end

    # The IP address of the peer (remote) end of the socket, as reported by
    # the socket.
    def peer_ip
      @peer_ip ||=
        if respond_to?(:getpeername)
          addr = getpeername
          Socket.getnameinfo(addr, Socket::NI_NUMERICHOST | Socket::NI_NUMERICSERV).first
        else
          PROXY_COMMAND_HOST_IP
        end
    end

    # Returns true if the IO is available for reading, and false otherwise.
    def available_for_read?
      result = Net::SSH::Compat.io_select([self], nil, nil, 0)
      result && result.first.any?
    end

    # Returns the next full packet. If the mode parameter is :nonblock (the
    # default), then this will return immediately, whether a packet is
    # available or not, and will return nil if there is no packet ready to be
    # returned. If the mode parameter is :block, then this method will block
    # until a packet is available.
    def next_packet(mode=:nonblock)
      case mode
      when :nonblock then
        packet = poll_next_packet
        return packet if packet

        if available_for_read?
          if fill <= 0
            result = poll_next_packet
            if result.nil?
              raise Net::SSH::Disconnect, "connection closed by remote host"
            else
              return result
            end
          end
        end
        poll_next_packet

      when :block then
        loop do
          packet = poll_next_packet
          return packet if packet

          loop do
            result = Net::SSH::Compat.io_select([self]) or next
            break if result.first.any?
          end

          if fill <= 0
            raise Net::SSH::Disconnect, "connection closed by remote host"
          end
        end

      else
        raise ArgumentError, "expected :block or :nonblock, got #{mode.inspect}"
      end
    end

    # Enqueues a packet to be sent, and blocks until the entire packet is
    # sent.
    def send_packet(payload)
      enqueue_packet(payload)
      wait_for_pending_sends
    end

    # Enqueues a packet to be sent, but does not immediately send the packet.
    # The given payload is pre-processed according to the algorithms specified
    # in the client state (compression, cipher, and hmac).
    def enqueue_packet(payload)
      # try to compress the packet
      payload = client.compress(payload)

      # the length of the packet, minus the padding
      actual_length = 4 + payload.bytesize + 1

      # compute the padding length
      padding_length = client.block_size - (actual_length % client.block_size)
      padding_length += client.block_size if padding_length < 4

      # compute the packet length (sans the length field itself)
      packet_length = payload.bytesize + padding_length + 1

      if packet_length < 16
        padding_length += client.block_size
        packet_length = payload.bytesize + padding_length + 1
      end

      padding = Array.new(padding_length) { rand(256) }.pack("C*")

      unencrypted_data = [packet_length, padding_length, payload, padding].pack("NCA*A*")
      mac = client.hmac.digest([client.sequence_number, unencrypted_data].pack("NA*"))

      encrypted_data = client.update_cipher(unencrypted_data) << client.final_cipher
      message = encrypted_data + mac

      debug { "queueing packet nr #{client.sequence_number} type #{payload.getbyte(0)} len #{packet_length}" }
      enqueue(message)

      client.increment(packet_length)

      self
    end

    # Performs any pending cleanup necessary on the IO and its associated
    # state objects. (See State#cleanup).
    def cleanup
      client.cleanup
      server.cleanup
    end

    # If the IO object requires a rekey operation (as indicated by either its
    # client or server state objects, see State#needs_rekey?), this will
    # yield. Otherwise, this does nothing.
    def if_needs_rekey?
      if client.needs_rekey? || server.needs_rekey?
        yield
        client.reset! if client.needs_rekey?
        server.reset! if server.needs_rekey?
      end
    end

    protected

      # Called when this module is used to extend an object. It initializes
      # the states and generally prepares the object for use as a packet stream.
      def initialize_ssh
        @hints  = {}
        @server = State.new(self, :server)
        @client = State.new(self, :client)
        @packet = nil
        initialize_buffered_io
      end

      # Tries to read the next packet. If there is insufficient data to read
      # an entire packet, this returns immediately, otherwise the packet is
      # read, post-processed according to the cipher, hmac, and compression
      # algorithms specified in the server state object, and returned as a
      # new Packet object.
      def poll_next_packet
        if @packet.nil?
          minimum = server.block_size < 4 ? 4 : server.block_size
          return nil if available < minimum
          data = read_available(minimum)

          # decipher it
          @packet = Net::SSH::Buffer.new(server.update_cipher(data))
          @packet_length = @packet.read_long
        end

        need = @packet_length + 4 - server.block_size
        raise Net::SSH::Exception, "padding error, need #{need} block #{server.block_size}" if need % server.block_size != 0

        return nil if available < need + server.hmac.mac_length

        if need > 0
          # read the remainder of the packet and decrypt it.
          data = read_available(need)
          @packet.append(server.update_cipher(data))
        end

        # get the hmac from the tail of the packet (if one exists), and
        # then validate it.
        real_hmac = read_available(server.hmac.mac_length) || ""

        @packet.append(server.final_cipher)
        padding_length = @packet.read_byte

        payload = @packet.read(@packet_length - padding_length - 1)

        my_computed_hmac = server.hmac.digest([server.sequence_number, @packet.content].pack("NA*"))
        raise Net::SSH::Exception, "corrupted mac detected" if real_hmac != my_computed_hmac

        # try to decompress the payload, in case compression is active
        payload = server.decompress(payload)

        debug { "received packet nr #{server.sequence_number} type #{payload.getbyte(0)} len #{@packet_length}" }

        server.increment(@packet_length)
        @packet = nil

        return Packet.new(payload)
      end
  end

end; end; end


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

using System;
using DataAccessLayer;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;

namespace DataAccessLayerUnitTests
{
    /// Test fixture for CreativeEntity class.
    [TestClass]
    public class CreativeEntityFixture
    {
        /// Entity object with creative properties for testing.
        private Entity wrappedEntity;

        /// Per test initialization.
        [TestInitialize]
        public void InitializeTest()
        {
            this.wrappedEntity = new Entity
            {
                ExternalEntityId = new EntityProperty("ExternalEntityId", new EntityId()),
                ExternalName = new EntityProperty("ExternalName", TestEntityBuilder.ExternalName),
                EntityCategory = new EntityProperty("EntityCategory", CreativeEntity.CategoryName),
                ExternalType = new EntityProperty("ExternalType", "FooThingy"),
                CreateDate = new EntityProperty("CreateDate", DateTime.Now),
                LastModifiedDate = new EntityProperty("LastModifiedDate", DateTime.Now),
                LocalVersion = new EntityProperty("LocalVersion", 1),
                Key = MockRepository.GenerateStub<IStorageKey>()
            };
        }

        /// Test we can construct and validate from existing entity object.
        [TestMethod]
        public void ConstructFromIEntity()
        {
            var creativeEntity = new CreativeEntity(this.wrappedEntity);
            Assert.AreSame(this.wrappedEntity, creativeEntity.WrappedEntity);

            var blobEntityBase = this.wrappedEntity.BuildWrappedEntity();
            Assert.AreSame(this.wrappedEntity, blobEntityBase.SafeUnwrapEntity());
        }

        /// Test we do not double wrap.
        [TestMethod]
        public void ConstructFromIEntityDoesNotDoubleWrap()
        {
            var creativeEntity = new CreativeEntity(this.wrappedEntity);
            var creativeEntityWrap = new CreativeEntity(creativeEntity);
            Assert.AreSame(this.wrappedEntity, creativeEntityWrap.WrappedEntity);
        }

        /// Validate that entity construction fails if category is not Creative.
        [TestMethod]
        [ExpectedException(typeof(DataAccessTypeMismatchException))]
        public void FailValidationIfCategoryPropertyNotCampaign()
        {
            this.wrappedEntity.EntityCategory = "foobar";
            new CreativeEntity(this.wrappedEntity);
        }
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}

module KirstieHooksArchivePageSpec where

import           Test.Hspec
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BL
import           System.Directory
import           System.FilePath
import           System.Posix.Files

import Web.Kirstie.Model
import Web.Kirstie.DB
import Web.Kirstie.Hooks.ArchivePage

import Util

spec :: Spec
spec = do
  describe "Web.Kirstie.Hooks.ArchivePage" $ do
    it "all values" $ onTestSpace $ \conf pipe path -> do
      let template = BL.concat [ "{{config_data.blogUrl}}"
                               , "{{#articles}}"
                               , "{{aid}}", "{{title}}"
                               , "{{pubdate.date}}", "{{pubdate.year}}"
                               , "{{pubdate.month}}", "{{pubdate.day}}"
                               , "{{#tags}}"
                               , "{{tag}}", "{{encoded_tag}}"
                               , "{{/tags}}"
                               , "{{/articles}}" ]
          articles = [ minimal { articleTitle = "hoge"
                               , articleTags  = ["foo", "bar"] } ]
          expect   = BS.concat [ "http://www.example.com/"
                               , "0", "hoge"
                               , "1858-11-17", "1858", "Nov", "17"
                               , "foo", "foo", "bar", "bar" ]
          tempFile = templateDirectory conf </> "archive-page.html"
          htmlFile = htmlDirectory conf </> "archive.html"

      saveArticlesToDB conf articles
      createDirectories conf
      BL.writeFile tempFile template
      archivePage conf articles
      BS.readFile htmlFile `shouldReturn` expect

    it "empty database" $ onTestSpace $ \conf pipe path -> do
      let expect   = "http://www.example.com/"
          template = BL.concat [ "{{config_data.blogUrl}}"
                               , "{{#articles}}", "foo", "{{/articles}}" ]
          tempFile = templateDirectory conf </> "archive-page.html"
          htmlFile = htmlDirectory conf </> "archive.html"

      createDirectories conf
      BL.writeFile tempFile template
      archivePage conf []
      BS.readFile htmlFile `shouldReturn` expect

    it "all articles" $ onTestSpace $ \conf pipe path -> do
      let template = BL.concat ["{{#articles}}", "0", "{{/articles}}"]
          articles = map (\i -> minimal {articleIdNum = i}) [1..20]
          expect   = BS.concat $ replicate (length articles) "0"
          tempFile = templateDirectory conf </> "archive-page.html"
          htmlFile = htmlDirectory conf </> "archive.html"

      saveArticlesToDB conf articles
      createDirectories conf
      BL.writeFile tempFile template
      archivePage conf articles
      BS.readFile htmlFile `shouldReturn` expect

createDirectories :: Configure -> IO ()
createDirectories conf = do
  createDirectoryIfMissing False $ templateDirectory conf
  createDirectoryIfMissing False $ htmlDirectory conf


text:
/*
 * TZC programming is currently not done.
 */
void plat_arm_security_setup(void)
{
}


text:
/***********************************************************************
    created:    16/7/2013
    author:     Lukas E Meindl
*************************************************************************/
/***************************************************************************
 *   Copyright (C) 2004 - 2012 Paul D Turner & The CEGUI Development Team
 *
 *   Permission is hereby granted, free of charge, to any person obtaining
 *   a copy of this software and associated documentation files (the
 *   "Software"), to deal in the Software without restriction, including
 *   without limitation the rights to use, copy, modify, merge, publish,
 *   distribute, sublicense, and/or sell copies of the Software, and to
 *   permit persons to whom the Software is furnished to do so, subject to
 *   the following conditions:
 *
 *   The above copyright notice and this permission notice shall be
 *   included in all copies or substantial portions of the Software.
 *
 *   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 *   IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 *   OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 *   ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 *   OTHER DEALINGS IN THE SOFTWARE.
 ***************************************************************************/
#ifndef _SampleCustomShapesDrawingSample_h_
#define _SampleCustomShapesDrawingSample_h_

#include "Sample.h"

#include "CEGUI/ForwardRefs.h"
#include <glm/glm.hpp>

#include <deque>
#include <vector>

namespace CEGUI
{
    class Window;
    class DefaultWindow;
}

class CustomShapesDrawingSample : public Sample
{
public:
    CustomShapesDrawingSample();
    virtual ~CustomShapesDrawingSample() {}

    //! Initialises our sample
    bool initialise(CEGUI::GUIContext* guiContext) override;

    void deinitialise() override;

private:
    //! The general update function of our sample
    void update(float timeSinceLastUpdate) override;

    //! Updates the counted FPS and triggers the recreation of FPS Graph geometry if needed.
    void updateFPS(float timeSinceLastUpdate);

    //! Updates everything needed for the graphs including  the graphs themselves
    void updateFPSData(int randomFPS);

    //! Refreshes the maximum value that will be visualised in the graph
    void refreshFPSMaxGraphValue();

    //! Update the geometry used for the FPS graph
    void updateFPSGraphs();

    //! Event handler that triggers the redrawing of our GeometryBuffer-based graph.
    bool drawFPSGraphOverlay(const CEGUI::EventArgs& args);

    //! Sets up everything necessary to use and render our custom SVGImage.
    void setupCustomSVGImage();

    //! Sets up the background of the SVGImage-based graph
    void setupCustomSVGImageGraphBackground(CEGUI::SVGData& fpsSVGData);

    //! Sets up everything necessary to use and render our custom GeometryBuffer.
    void setupCustomGeometryGraph(CEGUI::GUIContext* guiContext);

    //! Positions the GeometryBuffer based graph
    void positionCustomGeometryFPSGraph();

    //! Sets up the background of the GeometryBuffer-based graph
    void setupCustomGeometryGraphBackground();

    //! Update the FPS graph geometry
    void updateCustomGeometryGraph(std::vector<glm::vec2> linePositions);

    //! Update the FPS graph SVGImage's Polyline
    void updateCustomSVGImagePolyline(std::vector<glm::vec2> linePositions);

    //! Creates the labels we will display next to the graph using the SVGImage
    void createCustomSVGImageFPSLabels();

    //! Updates the labels we will display next to the graph made with the GeometryBuffer
    void updateCustomGeometryFPSLabels();

    //! Creates the windows which will be used to display the SVGImage graph
    void createCustomSVGImageWindows();

    //! Creates the labels that we will use to display the FPS values next to the GeometryBuffer-based graph
    void createCustomGeometryFPSLabels();

    //! Updates the labels we will display next to the graph using the SVGImage
    void updateCustomSVGImageFPSLabels();

    //! Creator function for our Random-FPS checkbox
    void createCheckboxShowRealFPS();

    //! Creates a label that will display our last FPS value
    void createLastFPSLabel();

    //! Creates a label that contains a description of what is seen in the sample
    void createDescriptionLabel();

    //! The event handler for clicks on the Random-FPS checkbox.
    bool handleToggleButtonShowRandomisedFpsSelectionChanged(const CEGUI::EventArgs& args);

    //! Display size change handler
    bool handleDisplaySizeChange(const CEGUI::EventArgs& args);

    //! Handler for size changes of the custom-SVGImage FrameWindow
    bool handleSVGImageFrameWindowSizeChanged(const CEGUI::EventArgs& args);

    //! Our sample's root window.
    CEGUI::DefaultWindow*           d_root;

    //! Our window that renders the custom SVGImage.
    CEGUI::Window*                  d_customSVGImageWindow;

    //! A Framewindow to size and drag around. It contains our custom SVGImage window.
    CEGUI::Window*                  d_customSVGImageFrameWindow;

    //! The Polyline used to define our FPS graph lines. It will be added in the custom SVGImage's SVGData in our sample.
    CEGUI::SVGPolyline*             d_customPolyline;

    //! The GeometryBuffer that will be used to draw the FPS graph.
    CEGUI::GeometryBuffer*          d_FPSGraphGeometryBuffer;

    //! The FPS values we want to display.
    std::deque<unsigned int>        d_lastFPSValues;

    //! The number of samples we want to display in our FPS graph.
    unsigned int                    d_FPSGraphSamplesCount;

    //! Number of frames drawn so far.
    int                             d_FPSFrames;

    //! Fraction of second elapsed (used for counting frames per second).
    float                           d_FPSElapsed;

    //! The maximum FPS value the graph will be normalised to.
    unsigned int                    d_FPSMaxGraphValue;

    //! Defines if we should use actual FPS values or use random generated ones of a certain range for better display.
    bool                            d_useRealFPS;

    //! Width of the sample SVGImage
    float                           d_customSVGImageWidth;

    //! Height of the sample SVGImage
    float                           d_customSVGImageHeight;

    //! The vertices we generated to draw the static background of our GeometryBuffer based graph
    std::vector<CEGUI::ColouredVertex> d_customGeometryGraphBackgroundVertices;

    //! The width of the graph made using a GeometryBuffer
    float                           d_customGeometryGraphWidth;
    //! The height of the graph made using a GeometryBuffer
    float                           d_customGeometryGraphHeight;

    //! The window displaying the last FPS
    CEGUI::Window*                  d_lastFPSLabel;

    //! Labels that we will use to display the FPS next to the GeometryBuffer-based graph
    CEGUI::Window*                  d_customGeometryFPSLabel1;
    CEGUI::Window*                  d_customGeometryFPSLabel2;
    CEGUI::Window*                  d_customGeometryFPSLabel3;

    //! Labels that we will use to display the FPS next to the SVGImage-based graph
    CEGUI::Window*                  d_customSVGImageFPSLabel1;
    CEGUI::Window*                  d_customSVGImageFPSLabel2;
    CEGUI::Window*                  d_customSVGImageFPSLabel3;

    //! The custom SVGImage we will create to render one of the graphs
    CEGUI::SVGImage*                d_customSVGImage;
    //! The custom SVGData we will use for our custom SVGImage
    CEGUI::SVGData*                 d_customSVGData;
};

#endif  // end of guard _Sample_FirstWindow_h_


text:
<?php

namespace phpDocumentor\Reflection\ClassReflector;

use phpDocumentor\Reflection\BaseReflector;
use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock\Context;
use PHPParser_Node_Stmt_Class;
use PHPParser_Node_Stmt_Property;
use PHPParser_Node_Stmt_PropertyProperty;

class PropertyReflector extends BaseReflector
{
    /** @var PHPParser_Node_Stmt_Property */
    protected $property;

    /** @var PHPParser_Node_Stmt_PropertyProperty */
    protected $node;

    public function __construct(
        PHPParser_Node_Stmt_Property $property,
        Context $context,
        PHPParser_Node_Stmt_PropertyProperty $node
    ) {
        parent::__construct($node, $context);
        $this->property = $property;
    }

    public function getName()
    {
        return '$'.parent::getName();
    }

    /**
     * Returns the default value or null if none found.
     *
     * Please note that if the default value is null that this method returns
     * string 'null'.
     *
     * @return null|string
     */
    public function getDefault()
    {
        $result = null;
        if ($this->node->default) {
            $result = $this->getRepresentationOfValue($this->node->default);
        }

        return $result;
    }

    /**
     * Returns the visibility for this item.
     *
     * The returned value should match either of the following:
     *
     * * public
     * * protected
     * * private
     *
     * If a method has no visibility set in the class definition this method
     * will return 'public'.
     *
     * @return string
     */
    public function getVisibility()
    {
        if ($this->property->type & PHPParser_Node_Stmt_Class::MODIFIER_PROTECTED) {
            return 'protected';
        }
        if ($this->property->type & PHPParser_Node_Stmt_Class::MODIFIER_PRIVATE) {
            return 'private';
        }

        return 'public';
    }

    /**
     * Returns whether this property is static.
     *
     * @return bool
     */
    public function isStatic()
    {
        return (bool) ($this->property->type & PHPParser_Node_Stmt_Class::MODIFIER_STATIC);
    }

    /**
     * Returns the parsed DocBlock.
     *
     * @return DocBlock|null
     */
    public function getDocBlock()
    {
        return $this->extractDocBlock($this->property);
    }
}


text:
package com.powerknights.dashboard.telemetry.datasource.playback;

import com.powerknights.dashboard.lib.SegmentedRange;
import com.powerknights.dashboard.lib.ValueSnapshot;
import com.powerknights.dashboard.telemetry.datasource.ValueSource;
import javafx.beans.property.LongProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleLongProperty;
import javafx.beans.property.SimpleObjectProperty;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Queue;

/**
 * Created by powerknights on 2/14/16.
 */
public class PlaybackManager extends ValueSource {
    private SegmentedRange<ValueSnapshot> range = null;
    private ObjectProperty<PlaybackMode> playbackMode = new SimpleObjectProperty<>(PlaybackMode.PAUSE);
    private ValueSnapshot lastSnapshot = null;
    private volatile LongProperty time = new SimpleLongProperty(0); //In millis
    private Ticker tickerThread = new Ticker(this);

    public PlaybackManager(){
        tickerThread.start();
    }

    @Override
    public void open(String destination) {
        try{
            PlaybackMode lastMode = playbackMode.getValue();
            playbackMode.setValue(PlaybackMode.PAUSE);
            time.setValue(0);

            Queue<ValueSnapshot> snapshots = new ValueLogReader(new File(destination)).read();
            range = new SegmentedRange<ValueSnapshot>(0, 120000);
            snapshots.iterator().forEachRemaining(v -> range.addValue(v));
            range.finalizeRanges();

            playbackMode.setValue(lastMode);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() {
        tickerThread.stop();
    }

    @Override
    public void pause() {

    }

    @Override
    public boolean isConnectedToSource() {
        return true;
    }

    @Override
    public void processCommand(String command) {
        System.out.println(command);
        if(command.startsWith("open")){
            command = command.substring(command.indexOf(" ") + 1);
            open(command);
        }
    }

    public void setPlaybackMode(PlaybackMode mode){
        if(mode == playbackMode.getValue()) return;

        playbackMode.setValue(mode);
    }

    public PlaybackMode getPlaybackMode(){
        return playbackMode.getValue();
    }

    public ObjectProperty<PlaybackMode> playbackModeProperty(){
        return this.playbackMode;
    }

    protected void setTime(long time){
        if(range == null) return;
        if (time > 120000) {
            this.time.setValue(120000);
        } else if (time < 0) {
            this.time.setValue(0);
        }else{
            this.time.setValue(time);
        }

        setCurrentValue();
    }

    public long getTime(){
        return this.time.getValue();
    }

    public LongProperty timeProperty(){
        return this.time;
    }

    private void setCurrentValue(){
        ValueSnapshot snapshot = range.getValueAtTime(this.time.getValue());
        if(snapshot != lastSnapshot){
            this.lastSnapshot = snapshot;
            updateValues();
        }
    }

    private void updateValues(){
        if(lastSnapshot != null)
            this.lastSnapshot.apply();
    }

    private class Ticker extends Thread{
        private long lastMilliTicked = 0;
        private final PlaybackManager instance;

        private Ticker(PlaybackManager instance){
            this.lastMilliTicked = System.currentTimeMillis();
            this.instance = instance;
        }

        @Override
        public void run() {
            while(true){
                long newTime = System.currentTimeMillis();
                long delta = (long) ((newTime - lastMilliTicked) * this.instance.playbackMode.getValue().speedSetting);
                this.instance.setTime(this.instance.getTime() + delta);
                this.lastMilliTicked = newTime;
                try {
                    Thread.sleep(1L);
                } catch (InterruptedException ignore) {
                    //Do nothing
                }
            }
        }
    }
}


text:
/*
 * ToLFileChooser.java
 *
 * Created on October 6, 2003, 4:51 PM
 */

package org.tolweb.treegrow.main;

import java.io.*;
import java.awt.*;
import javax.swing.*;

/**
 * Class that determines whether to show a FileDialog or a JFileChooser.  If
 * the user is on a Mac, the FileDialog is shown since that is more in line
 * with what users expect to see on Mac.  Otherwise, the JFileChooser is used
 * since it is more modern looking and provides more flexible functionality
 */
public class ToLFileChooser {
    private boolean userCancelled = false;
    FileDialog fileDialog;
    FilenameFilter fileNameFilter;

    JFileChooser fileChooser;
    javax.swing.filechooser.FileFilter fileFilter;

    Frame parent;

    public ToLFileChooser(Frame parent, String title) {
        this(parent, title, false);
    }

    /** Creates a new instance of ToLFileChooser */
    public ToLFileChooser(Frame parent, String title, boolean isSave ) {
        this.parent = parent;

        if (Controller.getController().isMac()) {
            fileDialog = new FileDialog(parent, title);
            fileDialog.setDirectory(Controller.getController().getFileManager().getDataPath());
            if (isSave) {
                fileDialog.setMode(FileDialog.SAVE);
            }
        } else {
            fileChooser = new JFileChooser();
            fileChooser.setDialogTitle(title);
        }
    }

    /**
     * Sets the filter for the dialog or chooser
     *
     * @param fileNameFilter A FilenameFilter used for the fileDialog
     * @param fileFilter A FileFilter used for the JFileChooser
     */
    public void setFilter (FilenameFilter fileNameFilter, javax.swing.filechooser.FileFilter fileFilter) {
        if (Controller.getController().isMac()) {
            fileDialog.setFilenameFilter(fileNameFilter);
        } else {
            fileChooser.setFileFilter(fileFilter);
            fileChooser.setAcceptAllFileFilterUsed(false);
        }
    }

    public void setDirectory(File dir) {
        if (Controller.getController().isMac()) {
            fileDialog.setDirectory(dir.getAbsolutePath());
        } else {
            fileChooser.setCurrentDirectory(dir);
        }
    }

    public File getDirectory() {
        if (Controller.getController().isMac()) {
            if (fileDialog.getDirectory() != null) {
                return new File(fileDialog.getDirectory());
            } else {
                return null;
            }
        } else {
            return fileChooser.getCurrentDirectory();
        }
    }

    /**
     * Shows the dialog or asks the chooser to show a dialog
     */
    public void show() {
        if (Controller.getController().isMac()) {
            fileDialog.show();
        } else {
            int response = fileChooser.showDialog(parent,"OK");
            if (response == JFileChooser.CANCEL_OPTION) {
                userCancelled = true;
            }
        }
    }

    /**
     * Returns a string which is the path to the selected file from either the
     * dialog or chooser
     *
     * @return the path to the selected file
     */
    public String getSelectedFileName() {
        if (Controller.getController().isMac()) {
            if (fileDialog.getFile() == null || fileDialog.getFile().equals("")) {
                return null;
            } else {
                return fileDialog.getDirectory() + fileDialog.getFile();
            }
        } else {
            if (userCancelled || fileChooser.getSelectedFile() == null) {
                return null;
            } else {
                return fileChooser.getSelectedFile().getAbsolutePath();
            }
        }
    }

}


text:
/** Add your relevant code here for the issue to reproduce */
export default function Home() {
  return null
}


text:
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { MSGraphClient, AadTokenProvider } from "@microsoft/sp-http";
export interface ISiteTileProps {
  msGraphClient:MSGraphClient;
  site:any;
  themeVariant: IReadonlyTheme | undefined;
}


text:
This package is used to create different interaction states for when a user is
touching, hovering, pressing, or keyboard focusing an element on the page. There
are also some mixins and styles that allow you to apply styles only while the
user is in "touch", "mouse", or "keyboard" mode so you can finally get that
amazing keyboard focus only effect going on.

## Installation

```sh
npm install --save @react-md/states
```

It is also recommended to install the following packages:

```sh
npm install --save @react-md/theme \
  @react-md/typography \
  @react-md/utils
```

<!-- DOCS_REMOVE -->

## Documentation

You should check out the
[full documentation](https://react-md.dev/packages/states/demos) for live
examples and more customization information, but an example usage is shown
below.

<!-- DOCS_REMOVE_END -->

## Usage

This package has two main exports: `StatesConfig` and `useInteractionStates`.

### StatesConfig

This component is used to apply global configuration for how your user
interactions should work as well as determining the user input mode for your
app. There should only be _one_ `StatesConfig` component defined in your app at
a time and it should probably be somewhere near the root of your React render
tree since this component will modify the base `document.body` element with a
different `className` to help determine the current interaction mode.

```tsx
import { render } from "react-dom";
import { StatesConfig } from "@react-md/states";

import App from "./App";

const Root = () => (
  <StatesConfig>
    <App />
  </StatesConfig>
);

render(<Root />, document.getElementById("root"));
```

Since some people do not actually like the ripple effect from material design,
you can also configure the `StatesConfig` to remove the ripples altogether and
fallback to the default "pressed" states which will just change background color
temporarily instead.

```tsx
import { render } from "react-dom";
import { StatesConfig } from "@react-md/states";

import App from "./App";

const Root = () => (
  <StatesConfig disableRipple>
    <App />
  </StatesConfig>
);

render(<Root />, document.getElementById("root"));
```

### useInteractionStates

This is a hook that will allow you to connect to the current `StatesConfig` and
apply the different interaction states for an element. This hook will always
return an object containing:

- `ripples` - `ReactNode` of the ripples when enabled or `null` when ripples are
  disabled
- `className` - A merged `className` if using the pressed fallback state when
  ripples are disabled
- `handlers` - An object containing all the event handlers that must be applied
  to the DOM element so all the interaction states can happen.

```tsx
import type { HTMLAttributes, ReactElement } from "react";
import { render } from "react-dom";
import {
  StatesConfig,
  userInteractionStates,
  InteractionStatesOptions,
} from "@react-md/states";

type ButtonProps = HTMLAttributes<HTMLButtonElement> &
  InteractionStatesOptions<HTMLButtonElement>;
function Button({
  className: propClassName,
  disabled,
  disableRipple,
  disableProgrammaticRipple,
  disableSpacebarClick,
  disablePressedFallback,
  children,
  ...propHandlers
}: ButtonProps): ReactElement {
  const { ripples, handlers, className } = useInteractionStates({
    handlers: propHandlers,
    className: propClassName,
    disabled: disabled,
    disableRipple,
    disableProgrammaticRipple,
    disableSpacebarClick,
    disablePressedFallback,
  });

  return (
    <button type="button" className={className} {...handlers}>
      {children}
      {ripples}
    </button>
  );
}

function App(): ReactElement {
  return (
    <>
      <Button>Button 1</Button>
      <Button disableRipple>Button 2</Button>
      <Button disableRipple disablePressedFallback>
        Button 3
      </Button>
    </>
  );
}

render(<App />, document.getElementById("root"));
```


text:
'use strict';

describe('Auctions E2E Tests:', function () {
  describe('Test Auctions page', function () {
    it('Should report missing credentials', function () {
      browser.get('http://localhost:3001/auctions');
      expect(element.all(by.repeater('auction in auctions')).count()).toEqual(0);
    });
  });
});


text:
Simply refer the user to the R1soft backup server with this DirectAdmin plugin.

## How to install with CLI (Command Line Interface)
SSH to your server and use the following command:
```bash
wget https://raw.githubusercontent.com/MrKoopie/directadmin_r1soft/master/install_script.sh
chmod +x install_script.sh
./install_script.sh

```

# Disclaimer
Use of this plugin is at your own risk and responsibility. No guarantees are provided.


text:
// =================================================================================================
// Copyright 2012 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.args;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Nullable;

import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.reflect.TypeToken;

import com.twitter.common.args.apt.Configuration;

/**
 * Description of a positional command line argument.
 */
public final class PositionalInfo<T> extends ArgumentInfo<List<T>> {
  /**
   * Factory method to create a PositionalInfo from a field.
   *
   * @param field The field must contain a {@link Arg Arg<List<?>>}. The List<?>
   *     represents zero or more positional arguments.
   * @return a PositionalInfo describing the field.
   */
  static PositionalInfo<?> createFromField(Field field) {
    return createFromField(field, null);
  }

  /**
   * Factory method to create a PositionalInfo from a field.
   *
   * @param field The field must contain a {@link Arg Arg<List<?>>}. The List<?>
   *     represents zero or more positional arguments.
   * @param instance The object containing the non-static Arg instance or else null if the Arg
   *     field is static.
   * @return a PositionalInfo describing the field.
   */
  static PositionalInfo<?> createFromField(Field field, @Nullable Object instance) {
    Preconditions.checkNotNull(field);
    Positional positional = field.getAnnotation(Positional.class);
    if (positional == null) {
      throw new Configuration.ConfigurationException(
          "No @Positional Arg annotation for field " + field);
    }

    Preconditions.checkArgument(
        TypeUtil.getRawType(TypeUtil.getTypeParam(field)) == List.class,
        "Field is annotated for positional parsing but is not of Arg<List<?>> type");
    Type nestedType = TypeUtil.extractTypeToken(TypeUtil.getTypeParam(field));

    @SuppressWarnings({"unchecked", "rawtypes"}) // we have no way to know the type here
    PositionalInfo<?> positionalInfo = new PositionalInfo(
        field.getDeclaringClass().getCanonicalName() + "." + field.getName(),
        "[positional args]",
        positional.help(),
        ArgumentInfo.getArgForField(field, Optional.fromNullable(instance)),
        TypeUtil.getTypeParamTypeToken(field),
        TypeToken.of(nestedType),
        Arrays.asList(field.getAnnotations()),
        positional.parser());

    return positionalInfo;
  }

  private final TypeToken<T> elementType;

  private PositionalInfo(
      String canonicalName,
      String name,
      String help,
      Arg<List<T>> arg,
      TypeToken<List<T>> type,
      TypeToken<T> elementType,
      List<Annotation> verifierAnnotations,
      @Nullable Class<? extends Parser<? extends List<T>>> parser) {

    // TODO: https://github.com/twitter/commons/issues/353, consider future support of
    // argFile for Positional arguments.
    super(canonicalName, name, help, false, arg, type, verifierAnnotations, parser);
    this.elementType = elementType;
  }

  /**
   * Parses the positional args and stores the results in the {@link Arg} described by this
   * {@code PositionalInfo}.
   */
  void load(final ParserOracle parserOracle, List<String> positionalArgs) {
    final Parser<? extends T> parser = parserOracle.get(elementType);
    List<T> assignmentValue = Lists.newArrayList(Iterables.transform(positionalArgs,
      new Function<String, T>() {
        @Override public T apply(String argValue) {
          return parser.parse(parserOracle, elementType.getType(), argValue);
        }
      }));
    setValue(assignmentValue);
  }
}


text:
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <ctime>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <unordered_set>
#include <omp.h>
#include <sys/time.h>
using namespace std;

#define DEFAULT_NUM_READS 	1000000
#define BUF_SIZE	4096

// define READ

typedef struct read {
	int id;
	int length;
	char* sequence;
	int numTuples;
	unsigned int* tuples;

	void initialize(int readId, const char* seq, int K);
	void finalize();
	void formTuples(int K);
	void sortTuples();

} READ;

int compareTwoTuples(const void* t1, const void* t2);

void removeNewLine(string &line);

void removeInvalidChar(string &line);

int readFile(string inFileName, READ* &readArray, int &maxLen, int K);

void usage();

void getCommandOptions(int argc, char* argv[], string &inFileName, string &outFileName, int &K, int &groupSize, float &threshold, int &numThreads);

#endif


text:
(function() {
    'use strict';

    angular
        .module('socialprofileApp')
        .factory('Password', Password);

    Password.$inject = ['$resource'];

    function Password($resource) {
        var service = $resource('api/account/change_password', {}, {});

        return service;
    }
})();


text:
package com.example.pdsdt2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends Activity {

	protected EditText portServer;
	protected EditText portClient;
	protected EditText adresa;
	protected EditText city;
	protected Spinner infoType;
	protected TextView weatherForecastTextView;
	private HashMap<String, Informations> informations;
	ServerThread serverThread;

	private boolean serverStateRunning;

	public Informations getInformation(String oras) {
		Informations info = null;
		try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet("http://www.wunderground.com/cgi-bin/findweather/getForecast?query=" + oras);
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String content = httpClient.execute(httpGet, responseHandler);

			Element htmlTag = Jsoup.parse(content).child(0);

			info = new Informations();
			info.umiditate = htmlTag.getElementsByAttributeValue(
					"data-variable", "humidity").text();
			info.presiune = htmlTag.getElementsByAttributeValue(
					"data-variable", "pressure").text();
			info.temperatura = htmlTag.getElementsByAttributeValue(
					"data-variable", "temperature").text();
			info.stareGenerala = htmlTag.getElementsByAttributeValue(
					"data-variable", "feelslike").text();
			info.vitezaVant = htmlTag.getElementsByAttributeValue(
					"data-variable", "wind_gust_speed").text();

		} catch (Exception exception) {
			exception.printStackTrace();
		}

		return info;
	}

	class CommunicationThread extends Thread {
		private Socket socket;

		public CommunicationThread(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			super.run();
			try {
				BufferedReader bufferedReader = Utilities.getReader(socket);
				String oras = bufferedReader.readLine();
				String info = bufferedReader.readLine();

				Informations newInfo;
				if (informations.containsKey(oras)) {
					newInfo = informations.get(oras);
				} else {
					newInfo = getInformation(oras);
					informations.put(oras, newInfo);
				}

				PrintWriter printWriter = Utilities.getWriter(socket);
				if (info.equals("all")) {
					printWriter.println(newInfo.presiune + " "
							+ newInfo.temperatura + " " + newInfo.stareGenerala
							+ " " + newInfo.umiditate + " "
							+ newInfo.vitezaVant);
				} else if (info.equals("temperatura")) {
					printWriter.println(newInfo.temperatura);
				} else if (info.equals("viteza vantului")) {
					printWriter.println(newInfo.vitezaVant);
				}
				printWriter.flush();
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	class ServerThread extends Thread {
		private ServerSocket serverSocket;

		public ServerThread() {
			informations = new HashMap<String, Informations>();
		}

		public void closeSocket() {
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						if (serverSocket != null) {
							serverSocket.close();
						}
					} catch (IOException ioException) {
						ioException.printStackTrace();
					}
				}
			}).start();
		}

		@Override
		public void run() {
			super.run();
			try {
				serverSocket = new ServerSocket(Integer.parseInt(portServer.getText().toString()));

				while (serverStateRunning) {
					Socket socket = serverSocket.accept();
					new CommunicationThread(socket).start();
				}

			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	class ClientThread extends Thread {

		@Override
		public void run() {
			super.run();
			try {
				Socket socket = new Socket(adresa.getText().toString(), Integer.parseInt(portClient.getText().toString()));
				String oras = city.getText().toString();
				String infoTypeRequired = infoType.getSelectedItem().toString();

				PrintWriter printWriter = Utilities.getWriter(socket);
				printWriter.println(oras);
				printWriter.println(infoTypeRequired);
				printWriter.flush();

				BufferedReader bufferedReader = Utilities.getReader(socket);
				final String result  = bufferedReader.readLine();

				weatherForecastTextView.post(new Runnable() {
					@Override
					public void run() {
						weatherForecastTextView.setText(result);
					}
				});
				socket.close();
			} catch (NumberFormatException e) {
				e.printStackTrace();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		portServer = (EditText) findViewById(R.id.server_port_edit_text);

		adresa = (EditText) findViewById(R.id.client_address_edit_text);
		portClient = (EditText) findViewById(R.id.client_port_edit_text);
		city = (EditText) findViewById(R.id.city_edit_text);
		infoType = (Spinner) findViewById(R.id.information_type_spinner);

		weatherForecastTextView = (TextView) findViewById(R.id.weather_forecast_text_view);

		final Button buttonConectServer = (Button) findViewById(R.id.connect_button);
		Button buttonGetWeather = (Button) findViewById(R.id.get_weather_forecast_button);

		serverStateRunning = false;

		buttonConectServer.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!serverStateRunning) {
					serverStateRunning = true;
					buttonConectServer.setText("Disconnect");
					serverThread = new ServerThread();
					serverThread.start();
				} else {
					buttonConectServer.setText("Connect");
					serverStateRunning = false;
					serverThread.closeSocket();
				}
			}
		});

		buttonGetWeather.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				new ClientThread().start();
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}


text:
package io.quarkus.arc.test.inheritance;

import static org.junit.jupiter.api.Assertions.assertEquals;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Model;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.arc.Arc;
import io.quarkus.arc.InjectableBean;
import io.quarkus.arc.test.ArcTestContainer;

public class ScopeInheritanceStereotypeTest {

    @RegisterExtension
    public ArcTestContainer container = new ArcTestContainer(SuperBean.class, SubBean.class);

    @Test
    public void testExplicitScopeTakesPrecedence() {
        // Inheritance of type-level metadata: "A scope type explicitly declared by X and inherited by Y from X takes precedence over default scopes of stereotypes declared or inherited by Y."
        InjectableBean<SubBean> bean = Arc.container().instance(SubBean.class).getBean();
        assertEquals(ApplicationScoped.class, bean.getScope());
    }

    @ApplicationScoped
    static class SuperBean {

        public void ping() {
        }
    }

    @Model
    // should inherit @ApplicationScoped
    static class SubBean extends SuperBean {

    }
}


text:
import { Observable } from "../../Misc/observable";
import type { Nullable, int } from "../../types";
import type { ICanvas, ICanvasRenderingContext } from "../../Engines/ICanvas";
import type { HardwareTextureWrapper } from "./hardwareTextureWrapper";
import { TextureSampler } from "./textureSampler";

declare type ThinEngine = import("../../Engines/thinEngine").ThinEngine;
declare type BaseTexture = import("../../Materials/Textures/baseTexture").BaseTexture;
declare type SphericalPolynomial = import("../../Maths/sphericalPolynomial").SphericalPolynomial;

/**
 * Defines the source of the internal texture
 */
export enum InternalTextureSource {
    /**
     * The source of the texture data is unknown
     */
    Unknown,
    /**
     * Texture data comes from an URL
     */
    Url,
    /**
     * Texture data is only used for temporary storage
     */
    Temp,
    /**
     * Texture data comes from raw data (ArrayBuffer)
     */
    Raw,
    /**
     * Texture content is dynamic (video or dynamic texture)
     */
    Dynamic,
    /**
     * Texture content is generated by rendering to it
     */
    RenderTarget,
    /**
     * Texture content is part of a multi render target process
     */
    MultiRenderTarget,
    /**
     * Texture data comes from a cube data file
     */
    Cube,
    /**
     * Texture data comes from a raw cube data
     */
    CubeRaw,
    /**
     * Texture data come from a prefiltered cube data file
     */
    CubePrefiltered,
    /**
     * Texture content is raw 3D data
     */
    Raw3D,
    /**
     * Texture content is raw 2D array data
     */
    Raw2DArray,
    /**
     * Texture content is a depth/stencil texture
     */
    DepthStencil,
    /**
     * Texture data comes from a raw cube data encoded with RGBD
     */
    CubeRawRGBD,
    /**
     * Texture content is a depth texture
     */
    Depth,
}

/**
 * Class used to store data associated with WebGL texture data for the engine
 * This class should not be used directly
 */
export class InternalTexture extends TextureSampler {
    /**
     * Defines if the texture is ready
     */
    public isReady: boolean = false;
    /**
     * Defines if the texture is a cube texture
     */
    public isCube: boolean = false;
    /**
     * Defines if the texture contains 3D data
     */
    public is3D: boolean = false;
    /**
     * Defines if the texture contains 2D array data
     */
    public is2DArray: boolean = false;
    /**
     * Defines if the texture contains multiview data
     */
    public isMultiview: boolean = false;
    /**
     * Gets the URL used to load this texture
     */
    public url: string = "";
    /** @internal */
    public _originalUrl: string; // not empty only if different from url
    /**
     * Gets a boolean indicating if the texture needs mipmaps generation
     */
    public generateMipMaps: boolean = false;
    /**
     * Gets a boolean indicating if the texture uses mipmaps
     * TODO implements useMipMaps as a separate setting from generateMipMaps
     */
    public get useMipMaps() {
        return this.generateMipMaps;
    }
    public set useMipMaps(value: boolean) {
        this.generateMipMaps = value;
    }
    /**
     * Gets the number of samples used by the texture (WebGL2+ only)
     */
    public samples: number = 0;
    /**
     * Gets the type of the texture (int, float...)
     */
    public type: number = -1;
    /**
     * Gets the format of the texture (RGB, RGBA...)
     */
    public format: number = -1;
    /**
     * Observable called when the texture is loaded
     */
    public onLoadedObservable = new Observable<InternalTexture>();
    /**
     * Observable called when the texture load is raising an error
     */
    public onErrorObservable = new Observable<Partial<{ message: string; exception: any }>>();
    /**
     * If this callback is defined it will be called instead of the default _rebuild function
     */
    public onRebuildCallback: Nullable<
        (internalTexture: InternalTexture) => {
            proxy: Nullable<InternalTexture | Promise<InternalTexture>>;
            isReady: boolean;
            isAsync: boolean;
        }
    > = null;
    /**
     * Gets the width of the texture
     */
    public width: number = 0;
    /**
     * Gets the height of the texture
     */
    public height: number = 0;
    /**
     * Gets the depth of the texture
     */
    public depth: number = 0;
    /**
     * Gets the initial width of the texture (It could be rescaled if the current system does not support non power of two textures)
     */
    public baseWidth: number = 0;
    /**
     * Gets the initial height of the texture (It could be rescaled if the current system does not support non power of two textures)
     */
    public baseHeight: number = 0;
    /**
     * Gets the initial depth of the texture (It could be rescaled if the current system does not support non power of two textures)
     */
    public baseDepth: number = 0;
    /**
     * Gets a boolean indicating if the texture is inverted on Y axis
     */
    public invertY: boolean = false;

    // Private
    /** @internal */
    public _invertVScale = false;
    /** @internal */
    public _associatedChannel = -1;
    /** @internal */
    public _source = InternalTextureSource.Unknown;
    /** @internal */
    public _buffer: Nullable<string | ArrayBuffer | ArrayBufferView | HTMLImageElement | Blob | ImageBitmap> = null;
    /** @internal */
    public _bufferView: Nullable<ArrayBufferView> = null;
    /** @internal */
    public _bufferViewArray: Nullable<ArrayBufferView[]> = null;
    /** @internal */
    public _bufferViewArrayArray: Nullable<ArrayBufferView[][]> = null;
    /** @internal */
    public _size: number = 0;
    /** @internal */
    public _extension: string = "";
    /** @internal */
    public _files: Nullable<string[]> = null;
    /** @internal */
    public _workingCanvas: Nullable<ICanvas> = null;
    /** @internal */
    public _workingContext: Nullable<ICanvasRenderingContext> = null;
    /** @internal */
    public _cachedCoordinatesMode: Nullable<number> = null;
    /** @internal */
    public _isDisabled: boolean = false;
    /** @internal */
    public _compression: Nullable<string> = null;
    /** @internal */
    public _sphericalPolynomial: Nullable<SphericalPolynomial> = null;
    /** @internal */
    public _sphericalPolynomialPromise: Nullable<Promise<SphericalPolynomial>> = null;
    /** @internal */
    public _sphericalPolynomialComputed = false;
    /** @internal */
    public _lodGenerationScale: number = 0;
    /** @internal */
    public _lodGenerationOffset: number = 0;
    /** @internal */
    public _useSRGBBuffer: boolean = false;

    // The following three fields helps sharing generated fixed LODs for texture filtering
    // In environment not supporting the textureLOD extension like EDGE. They are for internal use only.
    // They are at the level of the gl texture to benefit from the cache.
    /** @internal */
    public _lodTextureHigh: Nullable<BaseTexture> = null;
    /** @internal */
    public _lodTextureMid: Nullable<BaseTexture> = null;
    /** @internal */
    public _lodTextureLow: Nullable<BaseTexture> = null;
    /** @internal */
    public _isRGBD: boolean = false;

    /** @internal */
    public _linearSpecularLOD: boolean = false;
    /** @internal */
    public _irradianceTexture: Nullable<BaseTexture> = null;

    /** @internal */
    public _hardwareTexture: Nullable<HardwareTextureWrapper> = null;

    /** @internal */
    public _maxLodLevel: Nullable<number> = null;

    /** @internal */
    public _references: number = 1;

    /** @internal */
    public _gammaSpace: Nullable<boolean> = null;

    private _engine: ThinEngine;
    private _uniqueId: number;

    /** @internal */
    public static _Counter = 0;

    /** Gets the unique id of the internal texture */
    public get uniqueId() {
        return this._uniqueId;
    }

    /**
     * Gets the Engine the texture belongs to.
     * @returns The babylon engine
     */
    public getEngine(): ThinEngine {
        return this._engine;
    }

    /**
     * Gets the data source type of the texture
     */
    public get source(): InternalTextureSource {
        return this._source;
    }

    /**
     * Creates a new InternalTexture
     * @param engine defines the engine to use
     * @param source defines the type of data that will be used
     * @param delayAllocation if the texture allocation should be delayed (default: false)
     */
    constructor(engine: ThinEngine, source: InternalTextureSource, delayAllocation = false) {
        super();

        this._engine = engine;
        this._source = source;
        this._uniqueId = InternalTexture._Counter++;

        if (!delayAllocation) {
            this._hardwareTexture = engine._createHardwareTexture();
        }
    }

    /**
     * Increments the number of references (ie. the number of Texture that point to it)
     */
    public incrementReferences(): void {
        this._references++;
    }

    /**
     * Change the size of the texture (not the size of the content)
     * @param width defines the new width
     * @param height defines the new height
     * @param depth defines the new depth (1 by default)
     */
    public updateSize(width: int, height: int, depth: int = 1): void {
        this._engine.updateTextureDimensions(this, width, height, depth);

        this.width = width;
        this.height = height;
        this.depth = depth;

        this.baseWidth = width;
        this.baseHeight = height;
        this.baseDepth = depth;

        this._size = width * height * depth;
    }

    /** @internal */
    public _rebuild(): void {
        this.isReady = false;
        this._cachedCoordinatesMode = null;
        this._cachedWrapU = null;
        this._cachedWrapV = null;
        this._cachedWrapR = null;
        this._cachedAnisotropicFilteringLevel = null;
        if (this.onRebuildCallback) {
            const data = this.onRebuildCallback(this);
            const swapAndSetIsReady = (proxyInternalTexture: InternalTexture) => {
                proxyInternalTexture._swapAndDie(this, false);
                this.isReady = data.isReady;
            };
            if (data.isAsync) {
                (data.proxy as Promise<InternalTexture>).then(swapAndSetIsReady);
            } else {
                swapAndSetIsReady(data.proxy as InternalTexture);
            }
            return;
        }

        let proxy: InternalTexture;
        switch (this.source) {
            case InternalTextureSource.Temp:
                break;

            case InternalTextureSource.Url:
                proxy = this._engine.createTexture(
                    this._originalUrl ?? this.url,
                    !this.generateMipMaps,
                    this.invertY,
                    null,
                    this.samplingMode,
                    () => {
                        proxy._swapAndDie(this, false);
                        this.isReady = true;
                    },
                    null,
                    this._buffer,
                    undefined,
                    this.format,
                    this._extension,
                    undefined,
                    undefined,
                    undefined,
                    this._useSRGBBuffer
                );
                return;

            case InternalTextureSource.Raw:
                proxy = this._engine.createRawTexture(
                    this._bufferView,
                    this.baseWidth,
                    this.baseHeight,
                    this.format,
                    this.generateMipMaps,
                    this.invertY,
                    this.samplingMode,
                    this._compression,
                    this.type,
                    undefined,
                    this._useSRGBBuffer
                );
                proxy._swapAndDie(this, false);

                this.isReady = true;
                break;

            case InternalTextureSource.Raw3D:
                proxy = this._engine.createRawTexture3D(
                    this._bufferView,
                    this.baseWidth,
                    this.baseHeight,
                    this.baseDepth,
                    this.format,
                    this.generateMipMaps,
                    this.invertY,
                    this.samplingMode,
                    this._compression,
                    this.type
                );
                proxy._swapAndDie(this, false);

                this.isReady = true;
                break;

            case InternalTextureSource.Raw2DArray:
                proxy = this._engine.createRawTexture2DArray(
                    this._bufferView,
                    this.baseWidth,
                    this.baseHeight,
                    this.baseDepth,
                    this.format,
                    this.generateMipMaps,
                    this.invertY,
                    this.samplingMode,
                    this._compression,
                    this.type
                );
                proxy._swapAndDie(this, false);

                this.isReady = true;
                break;

            case InternalTextureSource.Dynamic:
                proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
                proxy._swapAndDie(this, false);
                this._engine.updateDynamicTexture(this, this._engine.getRenderingCanvas()!, this.invertY, undefined, undefined, true);

                // The engine will make sure to update content so no need to flag it as isReady = true
                break;

            case InternalTextureSource.Cube:
                proxy = this._engine.createCubeTexture(
                    this.url,
                    null,
                    this._files,
                    !this.generateMipMaps,
                    () => {
                        proxy._swapAndDie(this, false);
                        this.isReady = true;
                    },
                    null,
                    this.format,
                    this._extension,
                    false,
                    0,
                    0,
                    null,
                    undefined,
                    this._useSRGBBuffer
                );
                return;

            case InternalTextureSource.CubeRaw:
                proxy = this._engine.createRawCubeTexture(
                    this._bufferViewArray!,
                    this.width,
                    this.format,
                    this.type,
                    this.generateMipMaps,
                    this.invertY,
                    this.samplingMode,
                    this._compression
                );
                proxy._swapAndDie(this, false);
                this.isReady = true;
                break;

            case InternalTextureSource.CubeRawRGBD:
                // This case is being handeled by the environment texture tools and is not a part of the rebuild process.
                // To use CubeRawRGBD use updateRGBDAsync on the cube texture.
                return;

            case InternalTextureSource.CubePrefiltered:
                proxy = this._engine.createPrefilteredCubeTexture(
                    this.url,
                    null,
                    this._lodGenerationScale,
                    this._lodGenerationOffset,
                    (proxy) => {
                        if (proxy) {
                            proxy._swapAndDie(this, false);
                        }
                        this.isReady = true;
                    },
                    null,
                    this.format,
                    this._extension
                );
                proxy._sphericalPolynomial = this._sphericalPolynomial;
                return;
        }
    }

    /**
     * @internal
     */
    public _swapAndDie(target: InternalTexture, swapAll = true): void {
        // TODO what about refcount on target?

        this._hardwareTexture?.setUsage(target._source, this.generateMipMaps, this.isCube, this.width, this.height);

        target._hardwareTexture = this._hardwareTexture;
        if (swapAll) {
            target._isRGBD = this._isRGBD;
        }

        if (this._lodTextureHigh) {
            if (target._lodTextureHigh) {
                target._lodTextureHigh.dispose();
            }
            target._lodTextureHigh = this._lodTextureHigh;
        }

        if (this._lodTextureMid) {
            if (target._lodTextureMid) {
                target._lodTextureMid.dispose();
            }
            target._lodTextureMid = this._lodTextureMid;
        }

        if (this._lodTextureLow) {
            if (target._lodTextureLow) {
                target._lodTextureLow.dispose();
            }
            target._lodTextureLow = this._lodTextureLow;
        }

        if (this._irradianceTexture) {
            if (target._irradianceTexture) {
                target._irradianceTexture.dispose();
            }
            target._irradianceTexture = this._irradianceTexture;
        }

        const cache = this._engine.getLoadedTexturesCache();
        let index = cache.indexOf(this);
        if (index !== -1) {
            cache.splice(index, 1);
        }

        index = cache.indexOf(target);
        if (index === -1) {
            cache.push(target);
        }
    }

    /**
     * Dispose the current allocated resources
     */
    public dispose(): void {
        this._references--;
        this.onLoadedObservable.clear();
        this.onErrorObservable.clear();
        if (this._references === 0) {
            this._engine._releaseTexture(this);
            this._hardwareTexture = null;
        }
    }
}


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20130204160231 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        $this->addSql("UPDATE atlas_category SET slug = 'type'  WHERE title = 'Object Type'");
        $this->addSql("UPDATE atlas_category SET slug = 'thematic'  WHERE title = 'Category'");

    }

    public function down(Schema $schema)
    {
        // this down() migration is autogenerated, please modify it to your needs

    }
}


text:
package com.nominanuda.urispec;

import static com.nominanuda.urispec.Assert.isFalse;

import java.net.URI;
import java.util.List;
import java.util.Map;

import org.antlr.runtime.Token;

public class URISpecNode extends AbstractNode implements MatchingNode {
	private PathNode path;
	private QueryNode query;
	private FragmentNode fragment;

	public URISpecNode(Token payload) {
		super(payload);
	}
	@Override
	public String template(Object model) {
		StringBuilder sb = new StringBuilder();
		String p = path.template(model);
		if(p == null) {
			return null;
		}
		sb.append(p);
		if(query != null) {
			String q = query.template(model);
			if(q == null) {
				return null;
			}
			if(q.length() > 0) {
				sb.append("?").append(q);
			}
		}
		if(fragment != null) {
			String f = fragment.template(model);
			if(f == null) {
				return null;
			}
			if(f.length() > 0) {
				sb.append("#").append(f);
			}
		}
		return sb.toString();
	}
	@Override
	public void initNode() {
		isFalse(valid);
		super.initNode();
		path = (PathNode) getChild(0);
		query = (QueryNode) getChild(1);
		fragment = (FragmentNode) getChild(2);
	}

	public int match(String pattern, Object model) {
		URI uri = URI.create(pattern).normalize();
		String q = uri.getRawQuery();
		int qlen = q == null ? 0 : q.length() + /* the '?' */1;
		String f = uri.getRawFragment();
		int flen = f == null ? 0 : f.length() + /* the '#' */1;
		String uriStr = uri.toString();
		int len = uriStr.length();
		String p = uriStr.substring(0, len-qlen-flen);
		StringModelAdapter<? super Object> ma = getNodeAdapter().getStringModelAdapter();
		Object m = ma.createStringModel();

		if(path.match(p, m) < p.length()) {
			return -1;
		}
		if(query != null) {
			if(q == null) {
				q = "";
			}
			Map<String, List<String>> pMap = Utils.parseQueryString(q);
			List<String> l = query.matchParam(pMap, m);
			if(l == null) {
				return -1;
			}
		}
		if(fragment != null) {
			if(path.match(p, m) < 0) {
				return -1;
			}
		}
		ma.setAll(m, model);
		return pattern.length();
	}
}


text:
#import "DDIntranetModule.h"
#import "NSString+DDStringAdditions.h"
#import "MD5.h"
#import "MTUserEntity.h"
#import "MTUserModule.h"
#import "AFNetworking/AFNetworking.h"
@interface DDIntranetModule(PrivateAPI)

- (void)p_sortIntranet;

@end
@implementation DDIntranetModule
- (id)init
{
    self = [super init];
    if (self)
    {
        _intranets = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)loadIntranetsCompletion:(DDIntranetLoadCompletion)completion
{
    AFHTTPRequestOperationManager* httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [httpManager GET:[DDClientState shareInstance].discoverURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray* items = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:nil];
        [items enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSDictionary* info = (NSDictionary*)obj;
            DDIntranetEntity* intranetEntity = [[DDIntranetEntity alloc] initWithInfo:info];
            [_intranets addObject:intranetEntity];
        }];
        [self p_sortIntranet];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        DDLog(@"failed");
    }];
}

#pragma mark private API
- (void)p_sortIntranet
{
    [_intranets sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        DDIntranetEntity* intranet1 = (DDIntranetEntity*)obj1;
        DDIntranetEntity* intranet2 = (DDIntranetEntity*)obj2;
        if (intranet1.priority > intranet2.priority)
        {
            return NSOrderedAscending;
        }
        else if(intranet1.priority < intranet2.priority)
        {
            return NSOrderedDescending;
        }
        else
        {
            return NSOrderedSame;
        }
    }];
}

@end


text:
layout: post
title: Micro Data Center
comments: True
permalink: micro-data-center
published: False
---

In the [previous blog post](http://www.raywritescode.com/raspberry-pi-nas/) you were introduced to my Raspberry Pi (RPi) NAS.

Here's where it's housed.

![dataCenterCloseUp](/images/dataCenterCloseUp.png)

Starting from the lower-left and moving clockwise, the micro data center consists of:

* **Raspberry Pi NAS** To allow for air flow around both hard drives I cut one pair of disposable chopsticks and used the four pieces in two pairs to raise NAS02 off the shelf floor and to raise NAS01 off NAS02.

* **APC Back-UPS ES 550** gives the micro data center about 30 to 40 minutes of backup power in case my home loses electricity. The ES 550 emits a loud and shrill buzzing sound when it kicks into backup power mode.

* **APC 7-outlet surge protection bar** was needed because the ES 550′s backup-powered outlets are near the shelf floor. The three power packs plugged into backup-powered outlets cluttered the floor area. The surge protection bar is plugged into one of the ES 550′s backup-powered outlets and the bar puts the three power packs up and out of the way.

* **Motorola SURFboard SB6141 cable modem** After leasing a cable modem for eight years, I bought the SURFboard SB6141 in early 2013 after my internet provider increased the price of my cable modem lease $3/month.

* **Linksys E1200 Wi-Fi N300 Router** was purchased about three weeks ago to replace a faithful Linksys WRT54G that I used since 2006. The WRT54G went to my parents' house to provide wireless internet access to their home network.

* **The ice cream sandwich looking thing** between the RPi NAS and router is a [TITAN USB-DIY Dual-Way Fan](http://youtu.be/t6Vy9mDh1mE). ![titanFan](/images/titanFan.png) The fan is housed in a foam case with a foam base to absorb the spinning fan's vibration. The fan is plugged into the powered-USB hub and is whisper quiet. It runs 24/7.

## How Micro Is It?

The micro data center occupies the bottom shelf of a small entertainment center next to my bed. This picture gives you a sense of scale of how micro the data center is.

 ![dataCenterBookcase](/images/dataCenterBookcase.png)

The entertainment center has a glass front door. The bottom shelf was previously occupied by books before serving as the micro data center space.

Note the black strip on the face of the cable modem. It's made of a scrap piece of manila envelope cut 1-inch by 3-inches and painted black using a Magic Marker.

The black strip is used to block the modem's power and activity lights, which uncovered light up my room enough making it difficult for me to fall asleep at night.

The strip is taped to modem's top edge so the strip can be lifted like a flap for when I need to observe the lights.

## Conclusion

Up until last week the data on my two-year old computer had never been backed-up. My home network equipment was scattered under my bed, covered with a layer of dust, and with no backup power source.

Now my computer data is backed-up daily with redundancy. My home network equipment is clean and organized, cooled 24/7, and has up to 40 minutes of backup power.

### Short video of the Micro Data Center
<iframe width="640" height="360" src="//www.youtube.com/embed/LI2g8UHlw3c?feature=player_embedded" frameborder="0" allowfullscreen></iframe>


text:
namespace Matrix
{
    using System;

    public class WalkInMatrix
    {
        private const int InitialStartRow = 0;
        private const int InitialStartCol = 0;

        private static int[,] matrix;
        private static int[] directionsRow = { 1, 1, 1, 0, -1, -1, -1, 0 };
        private static int[] directionsCol = { 1, 0, -1, -1, -1, 0, 1, 1 };

        public static int[,] FillMatrix(int matrixSize)
        {
            matrix = new int[matrixSize, matrixSize];
            int numberToAdd = 1;
            var position = PositionInMatrix.Instace;
            position.CurrenRow = InitialStartRow;
            position.CurrentCol = InitialStartCol;

            while (TryGetEmptyCell(position))
            {
                matrix[position.CurrenRow, position.CurrentCol] = numberToAdd++;
                int currentDir = 0;

                while (IsNextToEmptyCell(position))
                {
                    currentDir = GetNewDirection(position, currentDir);

                    while (CanGoInThisDirection(position, currentDir))
                    {
                        position.CurrenRow += directionsRow[currentDir];
                        position.CurrentCol += directionsCol[currentDir];
                        matrix[position.CurrenRow, position.CurrentCol] = numberToAdd++;
                    }
                }
            }

            return matrix;
        }

        private static int GetNewDirection(PositionInMatrix position, int currrentDir)
        {
            while (!CanGoInThisDirection(position, currrentDir))
            {
                currrentDir = (currrentDir == 7) ? 0 : currrentDir + 1;
            }

            return currrentDir;
        }

        private static bool CanGoInThisDirection(PositionInMatrix position, int currentDir)
        {
            int nextRow = position.CurrenRow + directionsRow[currentDir];
            int nextCol = position.CurrentCol + directionsCol[currentDir];
            var result =
                IsInsideMatrix(nextRow, nextCol) &&
                matrix[nextRow, nextCol] == 0;
            return result;
        }

        private static bool IsInsideMatrix(int row, int col)
        {
            var isInside =
                row >= 0 && row < matrix.GetLength(0) && col >= 0 && col < matrix.GetLength(1);
            return isInside;
        }

        private static bool IsNextToEmptyCell(PositionInMatrix position)
        {
            int row;
            int col;

            for (int i = 0; i < directionsRow.Length; i++)
            {
                row = position.CurrenRow + directionsRow[i];
                col = position.CurrentCol + directionsCol[i];
                if (IsInsideMatrix(row, col) && matrix[row, col] == 0)
                {
                    return true;
                }
            }

            return false;
        }

        private static bool TryGetEmptyCell(PositionInMatrix position)
        {
            for (int row = 0; row < matrix.GetLength(0); row++)
            {
                for (int col = 0; col < matrix.GetLength(1); col++)
                {
                    if (matrix[row, col] == 0)
                    {
                        position.CurrenRow = row;
                        position.CurrentCol = col;
                        return true;
                    }
                }
            }

            position.CurrenRow = 0;
            position.CurrentCol = 0;
            return false;
        }
    }
}


text:
;
; Part of OS4, interrupt_test_handler.asm
; Author Mikael Henriksson, miklhh
;

global interrupt_test_handler
interrupt_test_handler:
	pusha

    extern      idt_initialized
    mov         byte[idt_initialized], 0xAB

	popa
	iret


text:
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>com.tlorrain.android.rezenerator</groupId>
		<artifactId>rezenerator</artifactId>
		<version>1.0-SNAPSHOT</version>
	</parent>
	<artifactId>rezenerator-maven-plugin</artifactId>
	<packaging>maven-plugin</packaging>
	<name>rezenerator-maven-plugin Maven Mojo</name>
	<properties>
		<maven.version>3.0.4</maven.version>
		<maven.annotations.version>3.2</maven.annotations.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-plugin-api</artifactId>
			<version>${maven.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.maven.plugin-tools</groupId>
			<artifactId>maven-plugin-annotations</artifactId>
			<version>${maven.annotations.version}</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>com.tlorrain.android.rezenerator</groupId>
			<artifactId>rezenerator-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.maven</groupId>
			<artifactId>maven-core</artifactId>
			<version>${maven.version}</version>
		</dependency>
	</dependencies>
	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-plugin-plugin</artifactId>
				<version>${maven.annotations.version}</version>
				<configuration>
					<!-- see http://jira.codehaus.org/browse/MNG-5346 -->
					<skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
				</configuration>
				<executions>
					<execution>
						<id>mojo-descriptor</id>
						<goals>
							<goal>descriptor</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
		</plugins>
	</build>
</project>