text:
def load_current_resource
  # Because these attributes are loaded lazily
  # we have to call each one explicitly
  new_resource.pidfile      new_resource.pidfile || "/var/run/redis/#{new_resource.name}.pid"
  new_resource.logfile      new_resource.logfile || "/var/log/redis/#{new_resource.name}.log"
  new_resource.dbfilename   new_resource.dbfilename || "#{new_resource.name}.rdb"
  new_resource.user         new_resource.user  || node.redis.user
  new_resource.group        new_resource.group || node.redis.group

  new_resource.slaveof_ip   new_resource.slaveof_ip
  new_resource.slaveof_port new_resource.slaveof_port || node.redis.config.port

  if new_resource.slaveof_ip || new_resource.slaveof
    new_resource.slaveof      new_resource.slaveof || "#{new_resource.slaveof_ip} #{new_resource.slaveof_port}"
  end

  new_resource.configure_no_appendfsync_on_rewrite
  new_resource.configure_slowlog
  new_resource.configure_list_max_ziplist
  new_resource.configure_maxmemory_samples
  new_resource.configure_set_max_intset_entries
  new_resource.configure_zset_max_ziplist_entries
  new_resource.configure_zset_max_ziplist_value
  new_resource.configure_hash_max_ziplist_entries
  new_resource.configure_hash_max_ziplist_value
  new_resource.conf_dir

  new_resource.state # Load attributes

  @run_context.include_recipe "runit" if new_resource.init_style == "runit"
end

action :create do
  create_user_and_group
  create_directories
  if node.platform_family == "rhel" && node.redis.install_type == "package"
    # For RHEL package installs, use the RPM's init script and set REDIS_USER
    create_sysconfig_file
  else
    create_service_script
  end
  create_config
  enable_service
  new_resource.updated_by_last_action(true)
end

action :destroy do
  disable_service
  new_resource.updated_by_last_action(true)
end

private

def create_user_and_group
  group new_resource.group

  user new_resource.user do
    gid new_resource.group
  end
end

def create_directories
  directory "#{::File.dirname(new_resource.logfile)} (#{new_resource.name})" do
    path ::File.dirname(new_resource.logfile)
    owner new_resource.user
    group new_resource.group
    mode 00755
    only_if { new_resource.logfile.downcase != "stdout" }
  end

  directory new_resource.conf_dir do
    owner "root"
    group "root"
    mode 00755
  end

  directory new_resource.dir do
    owner new_resource.user
    group new_resource.group
    mode 00755
  end

  directory ::File.dirname(new_resource.pidfile) do
    owner new_resource.user
    group new_resource.group
    mode 00755
  end
end

def create_config
  redis_service_name = redis_service
  template "#{new_resource.conf_dir}/#{new_resource.name}.conf" do
    source "redis.conf.erb"
    owner "root"
    group "root"
    mode 00644
    variables :config => new_resource.state
    case new_resource.init_style
    when "init"
      notifies :restart, "service[#{redis_service_name}]"
    when "runit"
      notifies :restart, "runit_service[#{redis_service_name}]"
    end
  end
end

# For RHEL-based installs, to set $REDIS_USER
def create_sysconfig_file
  file "/etc/sysconfig/redis" do
    owner "root"
    group "root"
    mode "0755"
    content "REDIS_USER=#{new_resource.user}\n"
  end
end

def set_dst_dir
  case node.platform_family
  when "rhel", "fedora"
    node.set[:redis][:dst_dir] = "/usr/sbin/"
  when "debian"
    node.set[:redis][:dst_dir] = "/usr/bin/"
  end
end

def create_service_script
  set_dst_dir if node.redis.install_type == "package"
  case new_resource.init_style
  when "init"
    template "/etc/init.d/redis-#{new_resource.name}" do
      source "redis_init.erb"
      owner "root"
      group "root"
      mode 00755
      variables new_resource.to_hash
    end
  when "runit"
    runit_service "redis" do
      options({
        :name     => new_resource.name,
        :dst_dir  => new_resource.dst_dir,
        :conf_dir => new_resource.conf_dir,
        :user     => new_resource.user
      })
    end
  end
end

def enable_service
  service redis_service do
    action [ :enable, :start ]
  end
end

def disable_service
  service redis_service do
    action [ :disable, :stop ]
  end
end

def redis_service
  if node.platform_family == "rhel" && node.redis.install_type == "package"
    "redis"
  else
    "redis-#{new_resource.name}"
  end
end


text:
var _ = require('libs/underscore-min')._;
/*
 * Shooter game example
 *
 * Touch screen to move our ship. The bullets are fired automatically.
 */
var alloy = require('co.lanica.platino');

function MainScene(window, game) {
    var _ = require('libs/underscore-min')._;

    var showingEndScreen = false;
    var debug = true;
    var button;
    // Create scene
    var self = alloy.createScene();

    var track = null;
    var titleScreen = null;
    var endScreen = null;

    var titleScreenTransform = null;
    var trackTransform = null;

    var zoomOutTransform = null;
    var thrownEggTransform = null;
    var thrownEggScaleTransform = null;

    var bikes = [];
    var pedestrians = [];
    var aboutCloseButton;

    var grandma;
    var grandmaThrow;

    var eggTray;
    var timer;
    var eggs = [];
    var NUM_EGGS = 12;
    var eggsLeft = NUM_EGGS;
    var rottenEgg;
    var thrownEgg = null;

    var OUTER_LANE_SPEED = 5;
    var INNER_LANE_SPEED = 8;
    var PEDESTRIAN_SPEED = 2;

    var MAX_DEATHS = 10;
    var started = false;

    var score = 0;
    var scoreSprite;
    var scoreSpriteEnd;
    var deadCount = 0;
    var deadCountSprite = 0;
    var jostleBike = null;
    var jostleOrigY;
    var jostleDuration = 0;

    var webview;
    var webview_window;

    var bikeSprites = [
        'assets/cycle1.png',
        'assets/cycle2.png',
        'assets/cycle3.png',
        'assets/cycle4.png',
        'assets/cycle5.png',
        'assets/cycle6.png',
        'assets/cycle7.png',
        'assets/cycle8.png',
        'assets/cycle9.png',
        'assets/cycle10.png',
        'assets/bus1.png',
        'assets/bus2.png'
    ];

    var pedestrianSprites = [
        ['assets/npc1_a.png', 'assets/npc1_b.png', 'assets/npc1_c.png', 'assets/npc1_d.png'],
        ['assets/npc2_a.png', 'assets/npc2_b.png', 'assets/npc2_c.png', 'assets/npc2_d.png'],
        ['assets/npc3_a.png', 'assets/npc3_b.png', 'assets/npc3_c.png', 'assets/npc3_d.png'],
        ['assets/npc4_a.png', 'assets/npc4_b.png'],
        ['assets/npc5_a.png', 'assets/npc5_b.png'],
        ['assets/npc6_a.png', 'assets/npc6_b.png', 'assets/npc6_c.png', 'assets/npc6_d.png'],
        ['assets/npc7_a.png', 'assets/npc7_b.png', 'assets/npc7_c.png', 'assets/npc7_d.png'],
        ['assets/npc8_a.png', 'assets/npc8_b.png', 'assets/npc8_c.png', 'assets/npc8_d.png']
    ];

    var isThrowing = false;
    var isReloading = false;

    var bikesToRemove = [];
    var pedestriansToRemove = [];

    var animationDelay = 0;

    var pickBikeToJostle = function() {
        if (bikes.length > 0) {
            jostleBike = bikes[Math.floor(bikes.length * Math.random())];
            jostleOrigY = jostleBike.y;
            jostleDuration = 10;
        } else {
            jostleBike = null;
        }
    };

    var updateTimer = function(e) {
        for (var i in bikes) {
            bikes[i].x += bikes[i].velX;

            if ((bikes[i].x > track.width && bikes[i].velX > 0) || (bikes[i].x < -bikes[i].width && bikes[i].velX < 0)) {
                self.remove(bikes[i]);
                bikesToRemove.push(bikes[i]);
            }
        }

        for (var i in pedestrians) {
            pedestrians[i].y += pedestrians[i].velY;

            if ((pedestrians[i].y > track.height && pedestrians[i].velY > 0) || (pedestrians[i].y < -pedestrians[i].height && pedestrians[i].velY < 0)) {
                score += 10;
                self.remove(pedestrians[i]);
                pedestriansToRemove.push(pedestrians[i]);
            }
        }

        scoreSprite.text = "Score: " + score;
        deadCountSprite.text = "Crashes: " + deadCount;

        handleCollisions();

        if (jostleBike != null) {
            jostleBike.y = jostleOrigY + (Math.sin(jostleDuration) * 3.0);
            jostleDuration--;
            if(jostleDuration <= 0) {
                jostleBike.y = jostleOrigY;
                pickBikeToJostle();
            }
        } else {
            pickBikeToJostle();
        }

        while (bikesToRemove.length > 0) {
            var bikeToRemove = bikesToRemove.pop();
            if (bikeToRemove == jostleBike) {
                jostleBike = null;
            }

            bikeToRemove.dispose();
            bikes = _.without(bikes, bikeToRemove);
        }

        while (pedestriansToRemove.length > 0) {
            var pedestrianToRemove = pedestriansToRemove.pop();
            pedestrianToRemove.dispose();
            pedestrians = _.without(pedestrians, pedestrianToRemove);
        }

        animationDelay++;
        if (animationDelay % 5 == 0) {
            animatePedestrians();

            if (isReloading) {
                blinkEggTray();
            }
        }
    };

    var animatePedestrians = function() {
        for (var i in pedestrians) {
            pedestrians[i].currentFrame++;
            if (pedestrians[i].currentFrame > pedestrianSprites[pedestrians[i].type].length - 1) {
                pedestrians[i].currentFrame = 0;
            }
            pedestrians[i].image = pedestrianSprites[pedestrians[i].type][pedestrians[i].currentFrame];
        }
    };

    var blinkEggTray = function() {
        if (eggTray.alpha == 0) {
            eggTray.show();
        } else {
            eggTray.hide();
        }
    };

    var showEndScreen = function () {
        showingEndScreen = true;
        endScreen.show();
        scoreSpriteEnd.text = "Score: " + score;
        scoreSpriteEnd.show();
    };

    var hideEndScreen = function () {
        showingEndScreen = false;
        endScreen.hide();
        resetGame();
        scoreSpriteEnd.hide();
    };

    var resetGame = function() {
        deadCount = 0;
        for (var i in pedestrians) {
            pedestriansToRemove.push(pedestrians[i]);
            self.remove(pedestrians[i]);
        }

        for (var i in bikes) {
            bikesToRemove.push(bikes[i]);
            self.remove(bikes[i]);
        }

        score = 0;
        reloadEggs();
    };

    var handleCollisions = function () {
        for (var i in bikes) {
            for (var j in pedestrians) {
                if (pedestrians[j].collidesWith(bikes[i])) {
                    deadCount++;
                    if (deadCount >= MAX_DEATHS) {
                        showEndScreen();
                    }

                    bikesToRemove.push(bikes[i]);
                    pedestriansToRemove.push(pedestrians[j]);
                    self.remove(bikes[i]);
                    self.remove(pedestrians[j]);
                }
            }
        }
    };

    var spawnOuterLaneBikes = function (e) {
        var newBike;
        var spriteImage = bikeSprites[Math.floor((Math.random()*bikeSprites.length))];

        if (Math.random() > 0.5) {
            newBike = alloy.createSprite({image:spriteImage});
            newBike.velX = OUTER_LANE_SPEED;
            newBike.velY = 0;
            newBike.x = -newBike.width;
            newBike.y = 510;
            newBike.rotationCenter = {x:newBike.width * 0.5, y:newBike.height * 0.5};
        } else {
            newBike = alloy.createSprite({image:spriteImage});
            newBike.velX = -OUTER_LANE_SPEED;
            newBike.velY = 0;
            newBike.x = track.width + newBike.width;
            newBike.y = 70;
            newBike.rotationCenter = {x:newBike.width * 0.5, y:newBike.height * 0.5};
            newBike.scaleFromCenter(-1, 1, newBike.width * 0.5, newBike.height * 0.5);
        }

        newBike.z = track.z + 1;
        self.add(newBike);
        bikes.push(newBike);
    };

    var spawnInnerLaneBikes = function (e) {
        var newBike;
        var spriteImage = bikeSprites[Math.floor((Math.random()*bikeSprites.length))];

        if (Math.random() > 0.5) {
            newBike = alloy.createSprite({image:spriteImage});
            newBike.velX = INNER_LANE_SPEED;
            newBike.x = -newBike.width;
            newBike.y = 360;
            newBike.rotationCenter = {x:newBike.width * 0.5, y:newBike.height * 0.5};
        } else {
            newBike = alloy.createSprite({image:spriteImage});
            newBike.velX = -INNER_LANE_SPEED;
            newBike.x = track.width + newBike.width;
            newBike.y = 220;
            newBike.rotationCenter = {x:newBike.width * 0.5, y:newBike.height * 0.5};
            newBike.scaleFromCenter(-1, 1, newBike.width * 0.5, newBike.height * 0.5);
        }

        newBike.velY = 0;
        newBike.z = track.z + 1;
        self.add(newBike);
        bikes.push(newBike);
    };

    var spawnPedestrians = function (e) {
        var newPedestrian;
        var type = Math.floor((Math.random()*pedestrianSprites.length));
        var spriteImage = pedestrianSprites[type][0];

        if (Math.random() > 0.5) {
            newPedestrian = alloy.createSprite({image:spriteImage});
            newPedestrian.velY = PEDESTRIAN_SPEED;
            newPedestrian.y = 0 - newPedestrian.height;
            newPedestrian.rotationCenter = {x:newPedestrian.width * 0.5, y:newPedestrian.height * 0.5};
        } else {
            newPedestrian = alloy.createSprite({image:spriteImage});
            newPedestrian.velY = -PEDESTRIAN_SPEED;
            newPedestrian.y = track.height;
            newPedestrian.rotationCenter = {x:newPedestrian.width * 0.5, y:newPedestrian.height * 0.5};
            newPedestrian.scaleFromCenter(-1, 1, newPedestrian.width * 0.5, newPedestrian.height * 0.5);
        }

        newPedestrian.type = type;
        newPedestrian.currentFrame = 0;
        newPedestrian.x = track.width * 0.5;
        newPedestrian.velX = 0;
        newPedestrian.z = track.z + 1;
        self.add(newPedestrian);
        pedestrians.push(newPedestrian);
    };

    var zoomOutCompleted = function(e) {
        setInterval(updateTimer, 33);
        setInterval(spawnOuterLaneBikes, Math.floor((Math.random()*1000)+3000));
        setInterval(spawnInnerLaneBikes, Math.floor((Math.random()*1000)+3000));

        setInterval(spawnPedestrians, Math.floor((Math.random()*2000)+4000));

        grandma = alloy.createSprite({image:'assets/grandma_1.png'});
        grandma.x = (track.width - grandma.width) / 2;
        grandma.y = track.height - grandma.height;
        grandma.z = track.z + 10;
        grandmaThrow = alloy.createSprite({image:'assets/grandma_2.png'});
        grandmaThrow.x = (track.width - grandmaThrow.width) / 2;
        grandmaThrow.y = track.height - grandmaThrow.height;
        grandmaThrow.z = track.z + 10;
        self.add(grandma);

        scoreSprite = alloy.createTextSprite({text:'Score: 0', fontSize:75});
        scoreSprite.fontFamily = 'Chantelli_Antiqua';
        scoreSprite.x = (track.width / 2 - scoreSprite.width) / 4;
        scoreSprite.y = 20;
        self.add(scoreSprite);

        deadCountSprite = alloy.createTextSprite({text:"Crashes: 0", fontSize:24});
        deadCountSprite.fontFamily = 'Chantelli_Antiqua';
        deadCountSprite.x = track.width - deadCountSprite.width - 100;
        deadCountSprite.y = track.height - deadCountSprite.height - 50;
        deadCountSprite.z = grandma.z + 1;
        self.add(deadCountSprite);

        initializeEggs();
    };

    var initializeEggs = function() {
        eggTray = alloy.createSprite({image:'assets/eggtray.png'});
        eggTray.x = 20;
        eggTray.y = track.height - eggTray.height - 20;
        eggTray.z = track.z + 1;
        self.add(eggTray);

        rottenEgg = Math.floor(Math.random() * NUM_EGGS);

        for (var i = 0; i < NUM_EGGS; i++) {
            var spriteImage = 'assets/eggtray-egg.png';
            if (i === rottenEgg) {
                spriteImage = 'assets/eggtray-rotten.png';
            }

            eggs[i] = alloy.createSprite({image:spriteImage});
            eggs[i].x = 36 + (i % 6) * 32;
            eggs[i].y = eggTray.y + 16 + (Math.floor(i / 6) * 32);
            eggs[i].z = track.z + 2;
            self.add(eggs[i]);
        }
    };

    var titleScreenTransformCompleted = function(e) {
        started = true;

        track.show();

        track.duration = 1500;
        track.transform(trackTransform);
    };

    var handleTouch = function(e) {
        if (e.type == "touchstart") {
            if (showingEndScreen) {
                hideEndScreen();
            } else if (!started) {
                if (e.x > 150 && e.x < 500 && e.y > 775 && e.y < 825) {
                    openAbout();
                    return;
                }

                if (titleScreen.alpha == 1) {
                    titleScreenTransform.duration = 1000;
                    titleScreenTransform.alpha = 0;
                    titleScreen.transform(titleScreenTransform);
                }
            } else if (!isThrowing) {
                throwEgg(e);
            }
        }
    };

    var throwEgg = function(e) {
        var x = e.x * game.touchScaleX;
        var y = e.y * game.touchScaleY;
        if (Ti.Platform.osname == "android") {
            x -= 75;
            y -= 15;
        }

        self.remove(grandma);
        self.add(grandmaThrow);
        eggsLeft--;
        if (eggsLeft >= 0) {
            self.remove(eggs[eggsLeft]);
        }

        isThrowing = true;

        var eggSprite = 'assets/eggtray-egg.png';
        if (eggsLeft === rottenEgg) {
            eggSprite = 'assets/eggtray-rotten.png';
        }

        thrownEgg = alloy.createSprite({image:eggSprite});
        thrownEgg.x = grandma.x + grandma.width - 50;
        thrownEgg.y = grandma.y + 50;
        thrownEgg.z = grandma.z - 1;
        thrownEgg.scaleX = 3;
        thrownEgg.scaleY = 3;
        self.add(thrownEgg);

        thrownEggTransform.duration = 500;
        thrownEggTransform.x = x;
        thrownEggTransform.y = y;
        thrownEggTransform.z = track.z + 0.5;
        thrownEggTransform.easing = alloy.ANIMATION_CURVE_QUAD_IN_OUT;
        thrownEggTransform.scaleX = 0.3;
        thrownEggTransform.scaleY = 0.3;
        thrownEgg.transform(thrownEggTransform);
    };

    var reloadEggs = function() {
        isThrowing = false;
        isReloading = false;
        eggTray.show();
        for (var i = 0; i < NUM_EGGS; i++) {
            self.add(eggs[i]);
        }

        eggsLeft = NUM_EGGS;
    }

    var thrownEggCompleted = function() {
        self.remove(grandmaThrow);
        self.add(grandma);

        thrownEgg.image = 'assets/egg_1.png';
        thrownEgg.scaleX = 1;
        thrownEgg.scaleY = 1;
        if (eggsLeft == rottenEgg) {
            thrownEgg.image = 'assets/egg_2.png';
        }

        if (eggsLeft > 0) {
            isThrowing = false;
        } else {
            isReloading = true;
            setTimeout(reloadEggs, 1000);
        }

        for (var i in bikes) {
            if (bikes[i].contains(thrownEgg.x, thrownEgg.y)) {
                self.remove(bikes[i]);
                bikesToRemove.push(bikes[i]);
                score++;
                if (eggsLeft === rottenEgg) {
                    score += 5;
                }
            }
        }

        for (var i in pedestrians) {
            if (pedestrians[i].contains(thrownEgg.x, thrownEgg.y)) {
                self.remove(pedestrians[i]);
                pedestriansToRemove.push(pedestrians[i]);
                score -= 10;
                deadCount++;
                if (deadCount >= MAX_DEATHS) {
                    showEndScreen();
                }
            }
        }
    };

    self.addEventListener('onloadsprite', function(e) {
        Ti.API.info("onloadsprite: " + e.tag);
        if (e.tag == "TRACK") {
            game.unloadTexture(e.tag);
        } else if (e.tag == "TITLE_SCREEN") {
            game.unloadTexture(e.tag);

            var t = alloy.createTransform();
            t.duration = 1500;
            t.alpha = 1;

            titleScreen.transform(t);
        }
    });

    function zoomOut() {
        var defaultCamera = game.defaultCamera;

        zoomOutTransform.duration = 1;
        zoomOutTransform.easing = alloy.ANIMATION_CURVE_EASE_IN;
        zoomOutTransform.lookAt_centerX = track.width  * 0.5;
        zoomOutTransform.lookAt_centerY = track.height * 0.5;
        zoomOutTransform.lookAt_eyeX = track.width  * 0.5;
        zoomOutTransform.lookAt_eyeY = track.height * 0.5;
        zoomOutTransform.lookAt_eyeZ = defaultCamera.eyeZ;

        game.moveCamera(zoomOutTransform);
    }

    var hideWebView = function() {
       webview_window.close();
    };

    var openAbout = function() {
        about_webview = Titanium.UI.createWebView({url:'http://dev.mateoj.com/hacku/present.htm'});
        about_webview_window = Titanium.UI.createWindow();
        about_webview_window.add(about_webview);
        about_webview_window.open({modal:true});
        about_webview_window.add(aboutCloseButton);
    };
    var closeAbout = function() {
        about_webview_window.close();
    };

    self.addEventListener('activated', function(e) {
        Ti.API.info("main scene is activated");

        webview = Titanium.UI.createWebView({url:'http://dev.mateoj.com/hacku/phpservice'});
        webview_window = Titanium.UI.createWindow();
        webview_window.add(webview);
        webview_window.open({modal:true});
        button = Titanium.UI.createButton({
            title: 'Close',
            top: 20,
            right: 20,
            width: 150,
            height: 100
        });
        aboutCloseButton = Titanium.UI.createButton({
            title: 'Close',
            top: 20,
            right: 20,
            width: 150,
            height: 100
        });
        webview_window.add(button);
        button.addEventListener('click', hideWebView);
        aboutCloseButton.addEventListener('click', closeAbout);

        bikes = [];
        pedestrians = [];
        started = false;

        if (track === null) {
            track = alloy.createSprite({image:'assets/background_d.png'});
            track.tag = "TRACK";
        }

        if (titleScreen === null) {
            titleScreen = alloy.createSprite({image:'assets/start1.png'});
            titleScreen.tag = "TITLE_SCREEN";
        }

        if (endScreen === null) {
            endScreen = alloy.createSprite({image:'assets/end1.png'});
            endScreen.z = track.z + 20;
            endScreen.hide();
        }

        scoreSpriteEnd = alloy.createTextSprite({text:'Score: 0', fontSize:75});
        scoreSpriteEnd.fontFamily = 'Chantelli_Antiqua';
        scoreSpriteEnd.x = 190;
        scoreSpriteEnd.y = 3;
        scoreSpriteEnd.z = track.z + 21;
        scoreSpriteEnd.color(1, 1, 1);
        scoreSpriteEnd.hide();

        if (zoomOutTransform === null) {
            zoomOutTransform = alloy.createTransform();
        }

        if (titleScreenTransform === null) {
            titleScreenTransform = alloy.createTransform();
        }

        if (trackTransform === null) {
            trackTransform = alloy.createTransform();
        }

        if (thrownEggTransform === null) {
            thrownEggTransform = alloy.createTransform();
        }

        if (thrownEggScaleTransform === null) {
            thrownEggScaleTransform = alloy.createTransform();
        }

        zoomOutTransform.addEventListener('complete', zoomOutCompleted);
        titleScreenTransform.addEventListener('complete', titleScreenTransformCompleted);
        trackTransform.addEventListener('complete', zoomOut);
        thrownEggTransform.addEventListener('complete', thrownEggCompleted);

        track.hide();

        self.add(titleScreen);
        self.add(endScreen);
        self.add(scoreSpriteEnd);
        self.add(track);

        game.addEventListener('touchstart', handleTouch);
        game.addEventListener('touchmove',  handleTouch);
        game.addEventListener('touchend',   handleTouch);

        game.startCurrentScene();
    });

    self.addEventListener('deactivated', function(e) {
        Ti.API.info("main scene is deactivated");

        if (track !== null) {
            self.remove(track);
            track = null;
        }

        game.removeEventListener('touchstart', handleTouch);
        game.removeEventListener('touchmove',  handleTouch);
        game.removeEventListener('touchend',   handleTouch);
    });

    return self;
}

module.exports = MainScene;

redpajama_set_name: RedPajamaGithub


text:
class Windows10IconPainter {
 public:
  Windows10IconPainter();
  virtual ~Windows10IconPainter();

  Windows10IconPainter(const Windows10IconPainter&) = delete;
  Windows10IconPainter& operator=(const Windows10IconPainter&) = delete;

 public:
  // Paints the minimize icon for the button
  virtual void PaintMinimizeIcon(gfx::Canvas* canvas,
                                 gfx::Rect& symbol_rect,
                                 cc::PaintFlags& flags);

  // Paints the maximize icon for the button
  virtual void PaintMaximizeIcon(gfx::Canvas* canvas,
                                 gfx::Rect& symbol_rect,
                                 cc::PaintFlags& flags);

  // Paints the restore icon for the button
  virtual void PaintRestoreIcon(gfx::Canvas* canvas,
                                gfx::Rect& symbol_rect,
                                cc::PaintFlags& flags);

  // Paints the close icon for the button
  virtual void PaintCloseIcon(gfx::Canvas* canvas,
                              gfx::Rect& symbol_rect,
                              cc::PaintFlags& flags);

  // Paints the tab search icon for the button
  virtual void PaintTabSearchIcon(gfx::Canvas* canvas,
                                  gfx::Rect& symbol_rect,
                                  cc::PaintFlags& flags);
};

class Windows11IconPainter : public Windows10IconPainter {
 public:
  Windows11IconPainter();
  ~Windows11IconPainter() override;

  Windows11IconPainter(const Windows11IconPainter&) = delete;
  Windows11IconPainter& operator=(const Windows11IconPainter&) = delete;

 public:
  // Paints the maximize icon for the button
  void PaintMaximizeIcon(gfx::Canvas* canvas,
                         gfx::Rect& symbol_rect,
                         cc::PaintFlags& flags) override;

  // Paints the restore icon for the button
  void PaintRestoreIcon(gfx::Canvas* canvas,
                        gfx::Rect& symbol_rect,
                        cc::PaintFlags& flags) override;
};

#endif  // CHROME_BROWSER_UI_VIEWS_FRAME_WINDOWS_ICON_PAINTER_H_


text:
import React from 'react';
import { Grid } from 'semantic-ui-react';

import CategoryDetails from 'Components/CategoryDetails';
import HeaderBar from 'Components/HeaderBar';

export default ({ match, location }) => (
  <div className="category">
    <HeaderBar />
    <Grid container>
      <Grid.Column>
        <CategoryDetails match={match}/>
      </Grid.Column>
    </Grid>
  </div>
);


text:
<!DOCTYPE HTML>
<html manifest="" lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>US Energy</title>
    <!-- The line below must be kept intact for Sencha Command to build your application -->
    <script id="microloader" type="text/javascript" src="../../microloader/development.js"></script>
</head>
<body>
</body>
</html>


text:
## API

### Usage
Plugins used inside routes, handlers, and methods must be registered first before acquaint.
```js
server.register({
    register: require('acquaint'),
    options: {
        relativeTo: __dirname,
        routes: [
            {
                includes: [
                    'path/to/user/**/*Routes.js'
                ]
            }
        ],
        handlers: [
            {
                includes: [
                    'path/to/**/*Handlers.js'
                ],
                ignores: [
                    'TestHandler.js'
                ]
            }
        ],
        methods: [
            {
                prefix: 'model',
                includes: [
                    'path/to/user/*Models.js',
                    'path/to/sample/*Models.js'
                ],
            },
            {
                prefix: 'util',
                includes: [
                    'path/to/**/*Utils.js'
                ]
            }
        ],
        binds: [
            {
                includes: [
                    'path/to/server/*Binds.js'
                ]
            }
        ],
        apps: [
            {
                includes: [
                    'path/to/server/*Apps.js'
                ]
            }
        ]
    }
}, (err) => {
    ...
});
```
[Glue](https://github.com/hapijs/glue) manifest
```js
registrations: [
    {
        plugin: {
            register: 'acquaint',
            options: [
                ...
            ]
        }
    }
]
```
You may see this sample usage in a [TodoMVC](https://github.com/genediazjr/hapitodo) app.

### Options
* `relativeTo`
  * String of the current working directory in which to search. Defaults to `process.cwd()`.
* `routes`, `handlers`, `methods`, `binds`, and `apps`
  * Array of [inject objects](#inject-object) to be included.
  * You may specify only routes if you only want to autoload routes. The same for handlers, methods, and binds.
  * Returns an `error` if no files are retrieved on the specified [glob](https://github.com/isaacs/node-glob) pattern.

Caveats of `binds` ([server.bind](http://hapijs.com/api#serverbindcontext)):
  * Will not work if the route was registered outside of the plugin.
  * Will not work if the route has a handler that is autoloaded as well.
  * External `binds` will not be usable on autoloaded handlers.
  * For `bind` keys with duplicates, the last entry will be used.

##### Inject Object
* `includes` - array of glob string pattern/s or the `route`, `handler`, or `method` itself. Required.
* `ignores` - array of glob string pattern/s to be excluded while matching. Optional.
* `prefix` - string prefix for methods. Methods use only. Optional.
* `options` - object configuration as *default options* for loaded methods. Methods use only. Optional.
  * `merge` - boolean to merge the keys that does not exist on the loaded options. Defaults to false. Optional.
  * `override` - boolean to force the use of the *default options*. Defaults to false. Optional.

### Option Examples

##### Route Example

glob string
```js
options: {
    routes: [
        {
            includes: [
                'path/to/user/**/*Routes.js'
            ]
        }
    ]
}
```

or the route itself
```js
options: {
    routes: [
        {
            includes: [
                {
                    path: '/test1',
                    method: 'get',
                    handler: function (request, reply) {
                        ...
                        return reply('hello');
                    }
                },
                'path/to/other/**/*Routes.js'
            ]
        }
    ]
}
```

##### Handler Example

glob string
```js
options: {
    handlers: [
        {
            includes: [
                'path/to/user/**/*Handlers.js'
            ]
        }
    ]
}
```

or the handler itself (Function name is required. Don't use arrow functions.)
```js
options: {
    handlers: [
        {
            includes: [
                function handlerName (route, options) {

                    return function (request, reply) {
                        ...
                        return reply('hello');
                    };
                },
                'path/to/other/**/*Handlers.js'
            ]
        }
    ]
}
```

##### Method Example

glob string
```js
options: {
    methods: [
        {
            prefix: 'model',
            includes: [
                'path/to/model/**/*Methods.js'
            ]
        }
    ]
}
```

or the method itself (Function name is required. Don't use arrow functions.)
```js
options: {
    methods: [
        {
            prefix: 'model',
            includes: [
                function methodName (x, y) {
                    ...
                    return x + y + z;
                },
                'path/to/other/**/*Methods.js'
            ]
        }
    ]
}
```

method with options (Function name is required. Don't use arrow functions.)
```js
options: {
    methods: [
        {
            prefix: 'model',
            includes: [
                {
                    options: {
                        cache: {
                            expiresIn: 60000,
                            generateTimeout: 60000
                        }
                    },
                    method: function methodName(x, y) {
                        ...
                        return x + y + z;
                    }
                },
                'path/to/other/**/*Methods.js'
            ]
        }
    ]
}
```

glob string with default method options
```js
options: {
    methods: [
        {
            prefix: 'model',
            includes: [
                'path/to/model/**/*Methods.js'
            ],
            options: {
                cache: {
                    expiresIn: 60000,
                    generateTimeout: 60000
                },
                bind: someObject
            }
        }
    ]
}
```

default options with `merge` and `override`
```js
options: {
    methods: [
        {
            prefix: 'model',
            includes: [
                'path/to/model/**/*Methods.js'
            ],
            options: {
                cache: {
                    expiresIn: 60000,
                    generateTimeout: 60000
                    override: true
                },
                bind: {
                    operation: (x, next) => {
                        ...
                        return next(a);
                    }
                },
                merge: true,
                override: true
            }
        }
    ]
}
```

##### Bind Example

glob string
```js
options: {
    binds: [
        {
            includes: [
                'path/to/server/*Binds.js'
            ]
        }
    ]
}
```

or the bind itself (Name is required for sole functions. Don't use arrow functions.)
```js
options: {
    binds: [{ includes: [{ foo: 'bar'}] }]
}
```

##### App Example

glob string
```js
options: {
    apps: [
        {
            includes: [
                'path/to/server/*Apps.js'
            ]
        }
    ]
}
```

or the app object itself.
```js
options: {
    apps: [{ includes: [{ foo: 'bar'}] }]
}
```

See the [tests](test) for other examples.

### File Signatures

##### Route Signature
```js
module.exports = [
    {
        path: '/',
        method: 'get',
        handler: function (request, reply) {
            ...
            return reply('hello');
        }
    }
];
```

##### Handler Signature
```js
module.exports = (route, options) => {

    return function (request, reply) {
        ...
        return reply('hello');
    };
};
```

Handler use on route
```js
module.exports = [
    {
        path: '/',
        method: 'get',
        handler: {
            handlerFilename: {
                someOption: 'options parameter on handler'
            }
        }
    }
];
```

##### Method Signature
```js
exports.createOrUpdate = (user, next) => {
    ...
    return next(err, userFromDb);
};

exports.obtainOrDelete = {
    method: (user, next) => {
        ...
    },
    options: {
        ...
    }
};
```

Method use on server
```js
    server.methods.methodPrefix.FileName.exportedFunction(user, (err, data) => {
        ...
    });
```

Method use on handler
```js
module.exports = (route, options) => {

    return function (request, reply) {

        request.server.methods.methodPrefix.FileName.exportedFunction(user, (err, data) => {
            ...
            return reply('hello');
        });
    };
};
```

Method use on other method
```js
const context = require('acquaint');

module.exports.createOrUpdate = (user, next) => {
    const sample = context.methods.prefix.filename.exportedFunction;
    ...
    return next(err, userFromDb);
};
```

You may also inject a method that exports a function
```js
module.exports = (user, next) => {
    ...
    return next(err, userFromDb);
};
```

Or a method with `method` and `options` keys
```js
module.exports = {
    method: (user, next) => {
        ...
    },
    options: {
        ...
    }
};
```

### Known Issues

Node v4 and below is not able to set the key name as the default function name so avoid using anonymous functions for your methods.


text:
/**
 * Italian translation for bootstrap-markdown
 * Michele Virgilio <michele.virgilio@gmail.com>
 */
;(function($){
  $.fn.markdown.messages['it'] = {
    'Bold': "Grassetto",
    'Italic': "Corsivo",
    'Heading': "Titolo",
    'URL/Link': "URL/Collegamento",
    'Image': "Inserisci un'immagine",
    'List': "Lista",
    'Preview': "Anteprima",
    'strong text': "Testo grassetto",
    'emphasized text': "Testo corsivo",
    'heading text': "Titolo",
    'enter link description here': "Inserisci la descrizione del link",
    'Insert Hyperlink': "Inserisci Hyperlink",
    'enter image description here': "Inserisci la descrizione dell'immagine",
    'Insert Image Hyperlink': "Inserisci link per l'immagine",
    'enter image title here': "Inserisci il titolo dell'immagine",
    'list text here': "Testo della lista"
  };
}(jQuery))


text:
         <div class="browser-compatibility-alert"> <p class="browser-error">Your browser's Javascript functionality is turned off. Please turn it on so that you can experience the full capabilities of this site.</p> </div>

 <a href="<?=base_url();?>" class="breadcrumb-home" title="Home">Home /
      Your search Results for
      "<?=$search_string;?>"

<?=$search_string;?> /

 <?=count($product_arr);?> Search Results

                    <? if(!empty($product_arr)): ?>

                                Showing <?=count($product_arr);?> /
                                <?=count($product_arr);?> Products

                    <?endif;?>

            <? if(!empty($product_arr)): ?>

                    <?  foreach($product_arr as $curr_product):

                           $url = base_url().'product/details/'.strtolower($curr_product['category']).'/'.clean_string($curr_product['disp_name']).'/'.$curr_product['style'].'/';
                           //echo "
";print_r($curr_product);exit;
                        ?>

                                                    <?foreach($curr_product['prod_images'] as $key=>$curr_color_code):
													//echo "
";print_r($curr_product['prod_images']);exit;

													    /*$image_path = get_image_path($curr_color_code['image_path'],$curr_product['style']);
														if(is_url_exist($image_path)){
                                                            // split the image_path
                                                            $image_path = get_image_path($curr_color_code['image_path'],$curr_product['style']);

                                                        }else{
                                                            $image_path = base_url().'images/sublisting/prod_no_image.jpg';
                                                        }*/
														$img_name_old = $curr_color_code['image_path'];
														$img_name= substr($img_name_old, 0, -5);
														$image_path1 = get_prod_img($img_name,'detail');
														if(is_url_exist($image_path1.'F.jpg')){
															$image_path = get_prod_img($img_name.'F.jpg','detail');
														}else if(is_url_exist($image_path1.'D.jpg')){
															$image_path = get_prod_img($img_name.'D.jpg','detail');
														}else if(is_url_exist($image_path1.'D.jpg')){
															$image_path = get_prod_img($img_name.'D.jpg','detail');
														}else if(is_url_exist($image_path1.'O.jpg')){
															$image_path = get_prod_img($img_name.'O.jpg','detail');
														}else if(is_url_exist($image_path1.'A.jpg')){
															$image_path = get_prod_img($img_name.'A.jpg','detail');
														}else if(is_url_exist($image_path1.'E.jpg')){
															$image_path = get_prod_img($img_name.'E.jpg','detail');
														}else if(is_url_exist($image_path1.'R.jpg')){
															$image_path = get_prod_img($img_name.'R.jpg','detail');
														}else if(is_url_exist($image_path1.'B.jpg')){
															$image_path = get_prod_img($img_name.'B.jpg','detail');
														}else{
														    $image_path = base_url().'images/sublisting/prod_no_image.jpg';
														}
														foreach($curr_product['color_code'] as $k=>$curr_color){
															if($curr_color_code['variation_code'] == $curr_color['attr_code'])
															{
																$color = $curr_color['attr_value'];
															}
														}
                                                    ?>

                                                        <a href="<?=$url.$curr_product['color_code'][0]['attr_code'];?>" title="<?php if(isset($color)){ echo $color; }?>">
                                                        <img itemprop="image" class="primary-image lazy" data-src="" data-original="" data-altimg="" src="<?=$image_path;?>" alt="">

                                                    <? endforeach;?>

                                                <?=count($curr_product['color_code']);?> Colour

                                            <a class="name-link" href="<?=$url.$curr_product['color_code'][0]['attr_code'];?>" title="<?=$curr_product['disp_name'];?>"><?=$curr_product['disp_name'];?>
                                            <a class="name-link-sub" href="<?=$url.$curr_product['color_code'][0]['attr_code'];?>" title="<?=$curr_product['disp_name'];?>"><?=$curr_product['category']?>

												 <?php if($curr_product['price_sale'] != 0 && $curr_product['price_sale'] != '' && $curr_product['price_sale'] < $curr_product['price']):
												echo "$".$curr_product['price']."".$curr_product['price_sale'];
											else:
												echo "$".$curr_product['price'];
											endif;?>

                        <?php endforeach;?>

                <? if(!empty($product_arr)): ?>

                        <?if($this->uri->segment(1) !== 'show_search'){
                            $category = $this->uri->segment(2);
                            $sub_category = $this->uri->segment(3);
                            //$cgid_status = false;
                            //$ajax_data = "{'cgid_status':'true', 'category': '$category', 'sub_category': '$sub_category'}";
                            $ajax_data = array(
                                "cgid_status" => false,
                                'category' => $category,
                                'sub_category'  => $sub_category
                                );
                            $json = json_encode($ajax_data);
                        }else{
                            // first segment is show search
                            //$cgid_status = true;
                            $cgid_data = $_GET['cgid'];
                            //$ajax_data = "{'cgid_status':'false', 'cgid_data': '$cgid_data'}";
                            $ajax_data = array(
                                "cgid_status" => true,
                                'cgid_data' => $cgid_data
                                );
                            $json = json_encode($ajax_data);
                        }

                        ?>

                <?endif;?>

            <?else:?>

WE'RE SORRY, NO PRODUCTS WERE FOUND FOR YOUR SEARCH

            <?endif; //  if(!empty($product_arr)):  ?>

                        <form action="/search-show" method="post" name="Product-Sorting-Options" novalidate="novalidate">
                            <fieldset style="position: relative;">
                                Sort By:
                                <select id="grid-sort-footer" style="-webkit-appearance: none;">
                                    <option selected="" disabled="" value="SortBy">SORT BY</option>
                                    <option value="http://shop.diesel.com/search-show?q=safado&srule=recommended&sz=55&start=0" selected="selected">Featured</option>
                                    <option value="http://shop.diesel.com/search-show?q=safado&srule=recommended-nonSale&sz=55&start=0">New Arrival</option>
                                    <option value="http://shop.diesel.com/search-show?q=safado&srule=most_popular&sz=55&start=0">Most Popular</option>
                                    <option value="http://shop.diesel.com/search-show?q=safado&srule=price-low-to-high&sz=55&start=0">Price Low To High</option>
                                    <option value="http://shop.diesel.com/search-show?q=safado&srule=price-high-to-low&sz=55&start=0">Price High To Low</option>
                                </select>
                                <button class="sort-Go-Button simple-submit" type="submit" value="Go">Go</button> </fieldset>
                        </form>

 Showing 13 / 13 Products

                    <form action="/search-show" method="post" name="Product-Paging-Options" novalidate="novalidate">
                        <fieldset style="position: relative;">
                            Items / Page
                            <select id="grid-paging-footer" style="-webkit-appearance: none;">
                                <option value="http://shop.diesel.com/search-show?q=safado&sz=12">12</option>
                                <option value="http://shop.diesel.com/search-show?q=safado&sz=13">View All (13)</option>
                            </select>
                            <button class="sort-Go-Button simple-submit" type="submit" value="Go">Go</button> </fieldset>
                    </form>


text:
package ikube.application;

import java.io.Serializable;

/**
 * @author Michael Couck
 * @version 01.00
 * @since 23-10-2014
 */
class GCSnapshot implements Serializable {

    /**
     * When the garbage collector started the mark sweep collection.
     */
    long start;
    /**
     * When the garbage collector ended the mark sweep collection.
     */
    long end;
    /**
     * How long the garbage collector took for the iteration.
     */
    long duration;

    /**
     * The interval between the garbage collections.
     */
    long interval;
    /**
     * The change in the memory for the particular memory segment, could be up or down.
     */
    double delta;
    /**
     * The amount of memory available after the collection, the maximum memory for the Jvm less the used portion.
     */
    long available;
    /**
     * The ratio of used memory to maximum.
     */
    double usedToMaxRatio;

    /**
     * The cpu load at the end of the collection. This is in units per core. For 8 cores it could be 5.32 for example
     * which will indicate quite a high load. As a rule of thumb the load should not exceed 1 point for each core, bearing in
     * mind that a large portion of the load could be system and or file system load and will not show in htop for example.
     */
    double cpuLoad;
    /**
     * The number of cores available to the Jvm. Also os specific, and in some cases not correct.
     */
    int processors;
    /**
     * The load per core, 1.6 for example means that the core is very heavily loaded, try to keep this
     * below one, or the instructions are piling up on the way in, reducing the efficiency of the core as the
     * os has to schedule packets into the core.
     */
    double perCoreLoad;
    /**
     * And the number of threads that are used in the Jvm at the end of the garbage collection.
     */
    int threads;

    /**
     * How many garbage collections are being performed per unit, could be a second or a minute.
     */
    int runsPerTimeUnit = 1;

}


text:
package org.springframework.boot.context.properties.source;

import java.util.stream.Stream;

/**
 * An iterable {@link PrefixedConfigurationPropertySource}.
 *
 * @author Madhura Bhave
 */
class PrefixedIterableConfigurationPropertySource extends PrefixedConfigurationPropertySource
		implements IterableConfigurationPropertySource {

	PrefixedIterableConfigurationPropertySource(IterableConfigurationPropertySource source, String prefix) {
		super(source, prefix);
	}

	@Override
	public Stream<ConfigurationPropertyName> stream() {
		return getSource().stream().map(this::stripPrefix);
	}

	private ConfigurationPropertyName stripPrefix(ConfigurationPropertyName name) {
		return (getPrefix().isAncestorOf(name)) ? name.subName(getPrefix().getNumberOfElements()) : name;
	}

	@Override
	protected IterableConfigurationPropertySource getSource() {
		return (IterableConfigurationPropertySource) super.getSource();
	}

}


text:
Bloom Backup Script
===============

This simple PHP script backs up MySQL databases and data directories using Rsync over SSH.


text:
package android.marshon.likequanmintv.mvp.live;

import android.marshon.likequanmintv.bean.PlayBean;
import android.marshon.likequanmintv.librarys.http.delagate.IGetDataDelegate;
import android.marshon.likequanmintv.librarys.mvpbase.BasePresenterImpl;
import android.marshon.likequanmintv.mvp.live.interactor.LiveInteractor;

import java.util.List;

import javax.inject.Inject;

import rx.Subscription;

/**
 * Created by Administrator on 2016/11/22.
 */

public class LiveFragmentPresenterImpl extends BasePresenterImpl<LiveFragmentView>
        implements LiveFragmentPresenter {

    @Inject
    public LiveFragmentPresenterImpl(){

    }

    @Inject
    LiveInteractor mLiveInteractor;

    @Override
    public void onCreate() {
    }

    @Override
    public void loadPlayList() {
        Subscription subscription = mLiveInteractor.loadPlayList(new IGetDataDelegate<List<PlayBean>>() {

            @Override
            public void getDataSuccess(List<PlayBean> playBeanListHolderList) {
                mPresenterView.onPlayBeanList(playBeanListHolderList);

            }

            @Override
            public void getDataError(String errmsg) {

            }
        }, "json/play/list.json");
        mSubscriptions.add(subscription);
    }

    @Override
    public void loadPlayListByUrl(String url) {
        Subscription subscription = mLiveInteractor.loadPlayList(new IGetDataDelegate<List<PlayBean>>() {

            @Override
            public void getDataSuccess(List<PlayBean> playBeanListHolderList) {
                mPresenterView.onPlayBeanList(playBeanListHolderList);

            }

            @Override
            public void getDataError(String errmsg) {

            }
        }, "" + url);
        mSubscriptions.add(subscription);

    }

    @Override
    public void addMorePlayList() {

    }
}


text:
<?php

namespace Flarum\Pusher\Listener;

use Flarum\Post\Event\Posted;
use Flarum\User\Guest;
use Pusher;

class PushNewPost
{
    /**
     * @var Pusher
     */
    protected $pusher;

    public function __construct(Pusher $pusher)
    {
        $this->pusher = $pusher;
    }

    public function handle(Posted $event)
    {
        if ($event->post->isVisibleTo(new Guest)) {
            $tags = $event->post->discussion->tags;

            $this->pusher->trigger('public', 'newPost', [
                'postId' => $event->post->id,
                'discussionId' => $event->post->discussion->id,
                'tagIds' => $tags ? $tags->pluck('id') : null
            ]);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Windows.Input;

namespace MedicineBoxRecorder
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {

    }
}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef COMPONENTS_SERVICES_STORAGE_INDEXED_DB_LEVELDB_LEVELDB_FACTORY_H_
#define COMPONENTS_SERVICES_STORAGE_INDEXED_DB_LEVELDB_LEVELDB_FACTORY_H_

#include <string>
#include <tuple>

#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "third_party/leveldatabase/env_chromium.h"
#include "third_party/leveldatabase/src/include/leveldb/status.h"

namespace leveldb {
class DB;
}

namespace content {
class LevelDBState;

// Factory class used to open leveldb databases, and stores all necessary
// objects in a LevelDBState. This interface exists so that it can be mocked out
// for tests.
class LevelDBFactory {
 public:
  virtual ~LevelDBFactory() = default;

  // Creates an in-memory database.
  virtual std::tuple<std::unique_ptr<leveldb::DB>, leveldb::Status>
  OpenInMemoryDB(leveldb::Env* in_memory_env) = 0;

  // Opens a leveldb database with the given name. If |create_if_missing| is
  // true, then the database will be created if it does not exist.
  virtual std::tuple<std::unique_ptr<leveldb::DB>, leveldb::Status> OpenDB(
      const std::string& name,
      bool create_if_missing,
      size_t write_buffer_size) = 0;

  // Opens a leveldb database and returns it inside of a LevelDBState. If the
  // |file_name| is empty, then the database will be in-memory. If
  // |create_if_missing| is false and the database doesn't exist, then the
  // return tuple will be {nullptr, leveldb::Status::NotFound("", ""), false}.
  virtual std::tuple<scoped_refptr<LevelDBState>,
                     leveldb::Status,
                     /* is_disk_full= */ bool>
  OpenLevelDBState(const base::FilePath& file_name,
                   bool create_if_missing,
                   size_t write_buffer_size) = 0;

  // Assumes that there is no leveldb database currently running for this path.
  virtual leveldb::Status DestroyLevelDB(const base::FilePath& path) = 0;
};

class DefaultLevelDBFactory : public LevelDBFactory {
 public:
  // The |database_options| are used to open any database. The
  // |create_if_missing| is supplied by Open*() calls, and |write_buffer_size|
  // is calculated during the Open* calls as well. |in_memory_db_name| is used
  // for memory profiling reporting in the in-memory database environment.
  DefaultLevelDBFactory(leveldb_env::Options database_options,
                        const std::string& in_memory_db_name);
  ~DefaultLevelDBFactory() override;

  std::tuple<std::unique_ptr<leveldb::DB>, leveldb::Status> OpenInMemoryDB(
      leveldb::Env* in_memory_env) override;

  std::tuple<std::unique_ptr<leveldb::DB>, leveldb::Status> OpenDB(
      const std::string& name,
      bool create_if_missing,
      size_t write_buffer_size) override;

  std::tuple<scoped_refptr<LevelDBState>,
             leveldb::Status,
             /* is_disk_full= */ bool>
  OpenLevelDBState(const base::FilePath& file_name,
                   bool create_if_missing,
                   size_t write_buffer_size) override;

  leveldb::Status DestroyLevelDB(const base::FilePath& path) override;

 protected:
  leveldb_env::Options options_;
  std::string in_memory_db_name_;

  DISALLOW_COPY_AND_ASSIGN(DefaultLevelDBFactory);
};

}  // namespace content

#endif  // COMPONENTS_SERVICES_STORAGE_INDEXED_DB_LEVELDB_LEVELDB_FACTORY_H_


text:
System.register(["../char/skills/skill", "./classesFormulas", "../char/abilities/abitly"], function (exports_1, context_1) {
  "use strict";
  var __moduleName = context_1 && context_1.id;
  var skill_1, classesFormulas_1, abitly_1;
  var Classes;
  return {
    setters: [
      function (skill_1_1) {
        skill_1 = skill_1_1;
      },
      function (classesFormulas_1_1) {
        classesFormulas_1 = classesFormulas_1_1;
      },
      function (abitly_1_1) {
        abitly_1 = abitly_1_1;
      }],
    execute: function () {
      /**
       * Created by sargon on 7/16/16.
       */
      Classes = (function () {
        function Classes(name, baseAttackBonusFunction, fortitudeSaveFunction, reflexSaveFunction, willSaveFunction, skills) {
          this._name = name;
          this._baseAttackBonusFunction = baseAttackBonusFunction;
          this._fortitudeSaveFunction = fortitudeSaveFunction;
          this._reflexSaveFunction = reflexSaveFunction;
          this._willSaveFunction = willSaveFunction;
          this._skills = skills;
          Classes.ALL.push(this);
        }

        Classes.getClass = function (name) {
          return Classes.ALL.find(function (charClass) {
            return charClass.getName() === name;
          });
        };
        Classes.prototype.getName = function () {
          return this._name;
        };
        Classes.prototype.getSkills = function () {
          return this._skills;
        };
        Classes.prototype.getBAB = function (level) {
          return this._baseAttackBonusFunction.call(this, level);
        };
        Classes.prototype.getFortitudeSave = function (level) {
          return this._fortitudeSaveFunction.call(this, level);
        };
        Classes.prototype.getReflexSave = function (level) {
          return this._reflexSaveFunction.call(this, level);
        };
        Classes.prototype.getWillSave = function (level) {
          return this._willSaveFunction.call(this, level);
        };
        Classes.prototype.getSave = function (ability, level) {
          switch (ability) {
            case abitly_1.Ability.CON:
              return this.getFortitudeSave(level);
            case abitly_1.Ability.DEX:
              return this.getReflexSave(level);
            case abitly_1.Ability.WIS:
              return this.getWillSave(level);
          }
        };
        Classes.ALL = [];
        Classes.CLERIC = new Classes("cleric", classesFormulas_1.ClassesFormulas.getMediumBAB, classesFormulas_1.ClassesFormulas.getHighSave, classesFormulas_1.ClassesFormulas.getLowSave, classesFormulas_1.ClassesFormulas.getHighSave, [skill_1.Skill.CONCENTRATION, skill_1.Skill.CRAFT_1, skill_1.Skill.DIPLOMACY, skill_1.Skill.HEAL, skill_1.Skill.KNOWLEDGE_ARC, skill_1.Skill.KNOWLEDGE_HISTORY,
          skill_1.Skill.KNOWLEDGE_RELIGION, skill_1.Skill.KNOWLEDGE_PLANAR, skill_1.Skill.PROFESSION_1, skill_1.Skill.SPELLCRAFT]);
        Classes.MONK = new Classes("monk", classesFormulas_1.ClassesFormulas.getHighBAB, classesFormulas_1.ClassesFormulas.getHighSave, classesFormulas_1.ClassesFormulas.getLowSave, classesFormulas_1.ClassesFormulas.getHighSave, [skill_1.Skill.BALANCE]);
        return Classes;
      }());
      exports_1("Classes", Classes);
    }
  }
});
//# sourceMappingURL=classes.js.map


text:
using Figlotech.Core.Data;
using Figlotech.Core.FileAcessAbstractions;
using Figlotech.DataFlow.Interfaces;
using Figlotech.DataFlow.Models;
using Figlotech.DataFlow.Transformers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Figlotech.DataFlow.Readers
{
    public sealed class SimpleSelect : DataTransform {

        Selector[] Selectors;

        public SimpleSelect(IEnumerable<Selector> Selectors) {
            this.Selectors = Selectors.ToArray();
        }

        ~SimpleSelect() {
            this.Dispose();
        }

        public override async Task<string[]> GetHeaders() {
            var headers = await Input.GetHeaders();
            var retv = new string[this.Selectors.Length];
            for(int i = 0; i < Selectors.Length; i++) {
                Selectors[i].SetupHeaders(headers);
                retv[i] = Selectors[i].OutputColumnName;
            }
            return retv;
        }

        public override object[] ProcessInput(object[] input) {
            var retv = new object[Selectors.Length];
            for (int i = 0; i < Selectors.Length; i++) {
                retv[i] = Selectors[i].GetData(input);
            }
            return retv;
        }
    }
}


text:
using NUnit.Framework;

namespace metrics.Tests
{
    [TestFixture]
    public class MachineMetricsTests
    {
        [Test]
        public void Can_load_all_metrics()
        {
            var metrics = new Metrics();

            metrics.Clear();
            var machineMetrics = new MachineMetrics(metrics);

            machineMetrics.Install();
#if !COREFX
            Assert.IsTrue(metrics.All.Count > 0);
#endif
        }
    }
}


text:
package com.iskyinfor.duoduo.ui.book;

import java.io.File;
import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.iskinfor.servicedata.CommArgs;
import com.iskinfor.servicedata.pojo.BookShelf;
import com.iskinfor.servicedata.pojo.RecommentInfor;
import com.iskyinfor.duoduo.R;
import com.iskyinfor.duoduo.StaticData;
import com.iskyinfor.duoduo.downloadManage.DownloadServiceStub;
import com.iskyinfor.duoduo.downloadManage.utils.SdcardUtil;
import com.iskyinfor.duoduo.ui.book.BookShelfAdapter.ItemViewOclickEvent;
import com.iskyinfor.duoduo.ui.custom.page.PageListAdapter;

public class BookShelfRecommendListByAdapter extends PageListAdapter<RecommentInfor> {
	private LayoutInflater inflater;
	public  Context context;
	private TextView gift;
	public TextView userId;//用户ID
	public TextView username;//用户名
	public TextView proId;//书ID
	public TextView proName;//书名
	public ImageView proSmallPic;//书大图
	public ImageView proBigPic;//书小图
	public TextView recommendDate;//时间
	public TextView reason;//原因
	public boolean boolAll=true;

	public BookShelfRecommendListByAdapter(Context context,
			ArrayList<RecommentInfor> arrayList) {
		super(context, arrayList);
		this.context = context;
		inflater = LayoutInflater.from(context);
	}

	@Override
	public View initItemView(View convertView, Object item, int position) {
        final RecommentInfor recomment = (RecommentInfor) item;
		// ViewHolder holder = null;
		// if (convertView == null) {

		final ViewHolder holder = new ViewHolder();
		convertView = inflater.inflate(R.layout.bookshelf_recommendby_child, null);

		holder.proBigPic = (ImageView) convertView.findViewById(R.id.bookshelfgift_img);
		holder.proName = (TextView) convertView.findViewById(R.id.bookshelfgift_bookname);
		//holder.ather = (TextView) convertView.findViewById(R.id.bookshelfgift_gifttype);
		holder.username = (TextView) convertView.findViewById(R.id.bookshelfgift_username);
		holder.reason = (TextView) convertView.findViewById(R.id.bookshelfrecommend_contentby);
		holder.recommendDate = (TextView) convertView.findViewById(R.id.bookshelfgift_gifttime);
		holder.bookshelfrecommend_contentbyall=(TextView)convertView.findViewById(R.id.bookshelfrecommend_contentbyall);
		holder.bookshelfrecommend_contentby=(TextView)convertView.findViewById(R.id.bookshelfrecommend_contentby);

		if (recomment != null) {
			File file = new File(StaticData.IMAGE_DOWNLOAD_ADDR);
			Bitmap bitmap = SdcardUtil.nativeLoad(recomment.getProSmallPic());
			//true  本地加载图片
			if (bitmap!=null)
			{
				holder.proBigPic.setImageBitmap(bitmap);
			}
			else
			{
				holder.proBigPic.setBackgroundResource(R.drawable.bookshelfgift_img);
			}

			holder.proName.setText(recomment.getProName());
			holder.username.setText(recomment.getUserName());
			holder.reason.setText(recomment.getReason());
			holder.recommendDate.setText(recomment.getRecommendDate());
//			holder.gift.setOnClickListener(itemViewOclickEvent);

			if(recomment.getReason().length()>20){
				((TextView)convertView.findViewById(R.id.bookshelfrecommend_contentby)).setHeight(35);
				((TextView)convertView.findViewById(R.id.bookshelfrecommend_contentbyall)).setVisibility(View.VISIBLE);
			}
			else{
				((TextView)convertView.findViewById(R.id.bookshelfrecommend_contentbyall)).setVisibility(View.GONE);
			}
//
			holder.bookshelfrecommend_contentbyall.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(boolAll==true)
					{
					holder.bookshelfrecommend_contentby.setHeight(100);
					holder.bookshelfrecommend_contentbyall.setText("收起");
					boolAll=false;}
					else{
						holder.bookshelfrecommend_contentby.setHeight(35);
						holder.bookshelfrecommend_contentbyall.setText("查看全部");
						boolAll=true;
					}
				}
			});
//			holder.gift.setOnClickListener(itemViewOclickEvent);
 	     }
		return convertView;
	}

	private class ViewHolder {
		public TextView userId;//用户ID
		public TextView username;//用户名
		public TextView proId;//书ID
		public TextView proName;//书名
		public ImageView proSmallPic;//书大图
		public ImageView proBigPic;//书小图
		public TextView recommendDate;//时间
		public TextView reason;//原因
		public TextView bookshelfrecommend_contentbyall,bookshelfrecommend_contentby;

	}

	class ItemViewOclickEvent implements OnClickListener {
		BookShelf bookShelf;
		Context context;

		public ItemViewOclickEvent(BookShelf bookShelf, Context context) {
			this.bookShelf = bookShelf;
			this.context = context;
		}

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.book_logo:

				break;
//			case R.id.gift:
//				break;
			default:
				break;
			}

		}

	}

}


text:
'use strict';

exports.__esModule = true;

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _uncontrollable = require('uncontrollable');

var _uncontrollable2 = _interopRequireDefault(_uncontrollable);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var TAB = 'tab';
var PANE = 'pane';

var idPropType = _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.number]);

var propTypes = {
  /**
   * HTML id attribute, required if no `generateChildId` prop
   * is specified.
   */
  id: function id(props) {
    var error = null;

    if (!props.generateChildId) {
      for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      error = idPropType.apply(undefined, [props].concat(args));

      if (!error && !props.id) {
        error = new Error('In order to properly initialize Tabs in a way that is accessible ' + 'to assistive technologies (such as screen readers) an `id` or a ' + '`generateChildId` prop to TabContainer is required');
      }
    }

    return error;
  },

  /**
   * A function that takes an `eventKey` and `type` and returns a unique id for
   * child tab `<NavItem>`s and `<TabPane>`s. The function _must_ be a pure
   * function, meaning it should always return the _same_ id for the same set
   * of inputs. The default value requires that an `id` to be set for the
   * `<TabContainer>`.
   *
   * The `type` argument will either be `"tab"` or `"pane"`.
   *
   * @defaultValue (eventKey, type) => `${this.props.id}-${type}-${key}`
   */
  generateChildId: _react.PropTypes.func,

  /**
   * A callback fired when a tab is selected.
   *
   * @controllable activeKey
   */
  onSelect: _react.PropTypes.func,

  /**
   * The `eventKey` of the currently active tab.
   *
   * @controllable onSelect
   */
  activeKey: _react.PropTypes.any
};

var childContextTypes = {
  $bs_tabContainer: _react2['default'].PropTypes.shape({
    activeKey: _react.PropTypes.any,
    onSelect: _react.PropTypes.func.isRequired,
    getTabId: _react.PropTypes.func.isRequired,
    getPaneId: _react.PropTypes.func.isRequired
  })
};

var TabContainer = function (_React$Component) {
  (0, _inherits3['default'])(TabContainer, _React$Component);

  function TabContainer() {
    (0, _classCallCheck3['default'])(this, TabContainer);
    return (0, _possibleConstructorReturn3['default'])(this, _React$Component.apply(this, arguments));
  }

  TabContainer.prototype.getChildContext = function getChildContext() {
    var _props = this.props,
        activeKey = _props.activeKey,
        onSelect = _props.onSelect,
        generateChildId = _props.generateChildId,
        id = _props.id;

    var getId = generateChildId || function (key, type) {
      return id ? id + '-' + type + '-' + key : null;
    };

    return {
      $bs_tabContainer: {
        activeKey: activeKey,
        onSelect: onSelect,
        getTabId: function getTabId(key) {
          return getId(key, TAB);
        },
        getPaneId: function getPaneId(key) {
          return getId(key, PANE);
        }
      }
    };
  };

  TabContainer.prototype.render = function render() {
    var _props2 = this.props,
        children = _props2.children,
        props = (0, _objectWithoutProperties3['default'])(_props2, ['children']);

    delete props.generateChildId;
    delete props.onSelect;
    delete props.activeKey;

    return _react2['default'].cloneElement(_react2['default'].Children.only(children), props);
  };

  return TabContainer;
}(_react2['default'].Component);

TabContainer.propTypes = propTypes;
TabContainer.childContextTypes = childContextTypes;

exports['default'] = (0, _uncontrollable2['default'])(TabContainer, { activeKey: 'onSelect' });
module.exports = exports['default'];


text:
class ProductsController < Spree::BaseController
  HTTP_REFERER_REGEXP = /^https?:\/\/[^\/]+\/t\/([a-z0-9\-\/]+\/)$/

  #prepend_before_filter :reject_unknown_object, :only => [:show]
  before_filter :load_data, :only => :show

  resource_controller
  helper :taxons
  actions :show, :index

  private

  def load_data
    redirect_to login_url unless current_user
    load_object

    @variants = Variant.active.find_all_by_product_id(@product.id,
                :include => [:option_values, :images])
    @product_properties = ProductProperty.find_all_by_product_id(@product.id,
                          :include => [:property])
    @selected_variant = @variants.detect { |v| v.available? }

    referer = request.env['HTTP_REFERER']

    if referer  && referer.match(HTTP_REFERER_REGEXP)
      @taxon = Taxon.find_by_permalink($1)
    end
  end

  def collection
    @searcher = CoolpurSearch.new(params) #Spree::Config.searcher_class.new(params)
    @products = @searcher.retrieve_products
  end

  def accurate_title
    @product ? @product.name : nil
  end
end


text:
package org.conqat.engine.architecture.scope;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.conqat.engine.architecture.assessment.shared.ICodeMapping;
import org.conqat.engine.architecture.assessment.shared.IComponent;
import org.conqat.engine.architecture.format.ECodeMappingType;
import org.conqat.engine.architecture.format.EStereotype;
import org.conqat.engine.architecture.overlap.PatternToCodeMappingAdaptor;
import org.conqat.engine.commons.CommonUtils;
import org.conqat.engine.commons.node.ConQATGeneralNodeBase;
import org.conqat.engine.commons.pattern.PatternList;
import org.conqat.engine.core.core.ConQATException;
import org.conqat.lib.commons.assertion.CCSMPre;
import org.conqat.lib.commons.clone.DeepCloneException;
import org.conqat.lib.commons.collections.CollectionUtils;
import org.conqat.lib.commons.collections.IdentityHashSet;
import org.conqat.lib.commons.collections.UnmodifiableList;
import org.conqat.lib.commons.string.StringUtils;

/**
 * This is a node representing a component (which can in turn have sub
 * components). The elements of a system (usually these are classes) are mapped
 * onto these components.
 *
 * @author $Author: hummelb $
 * @version $Rev: 43813 $
 * @ConQAT.Rating GREEN Hash: 24ECC0409BC8B8D69B73C3AA8149EDF7
 */
public class ComponentNode extends ConQATGeneralNodeBase<ComponentNode>
		implements IComponent {

	/** Full unique name of this component. */
	private final String name;

	/** A human-readable description for this component. */
	private String description = StringUtils.EMPTY_STRING;

	/**
	 * Position of this Component. The Position is relative to the parent
	 * Component!
	 */
	private final Point pos;

	/** Dimension of this Component. */
	private final Dimension dim;

	/** Patterns matching names of elements contained in this component. */
	private final PatternList containedElementPatterns = new PatternList();

	/**
	 * Patterns matching names of elements explicitly excluded from this
	 * component. (Overrules containedElementPatterns)
	 */
	private final PatternList excludedElementPatterns = new PatternList();

	/**
	 * All policies for which this component is the source. This is a map from
	 * the target to policy.
	 */
	private final Map<IComponent, DependencyPolicy> sourcePolicies = new IdentityHashMap<IComponent, DependencyPolicy>();

	/** All policies for which this component is the target. */
	private final Collection<DependencyPolicy> targetPolicies = new HashSet<DependencyPolicy>();

	/** The stereotype of this component */
	private final EStereotype stereotype;

	/**
	 * Creates a new {@link ComponentNode}.
	 *
	 * @param pos
	 *            Position of this component.
	 * @param stereotype
	 *            the stereotype of this component.
	 *
	 * @throws IllegalArgumentException
	 *             if pos is null.
	 *
	 */
	public ComponentNode(String name, Point pos, Dimension dim,
			EStereotype stereotype) {
		CCSMPre.isNotNull(pos, "The position must not be null");
		CCSMPre.isNotNull(dim, "The dimension must not be null");
		CCSMPre.isNotNull(stereotype, "The stereotype must not be null");

		this.name = name;
		this.pos = pos;
		this.dim = dim;
		this.stereotype = stereotype;
	}

	/** Copy constructor. */
	protected ComponentNode(ComponentNode other) throws DeepCloneException {
		super(other);
		name = other.name;
		description = other.description;
		containedElementPatterns.addAll(other.containedElementPatterns);
		excludedElementPatterns.addAll(other.excludedElementPatterns);

		pos = other.pos;
		dim = other.dim;
		stereotype = other.stereotype;

		// policies are not copied, as they are processed in the
		// ArchitectureDefinition
	}

	/**
	 * Creates a lookup table from names to components by traversing the nodes
	 * in DFS order and putting results into the provided map.
	 */
	protected void fillNameLookup(Map<String, ComponentNode> nameLookup) {
		nameLookup.put(getName(), this);
		if (hasChildren()) {
			for (ComponentNode child : getChildren()) {
				child.fillNameLookup(nameLookup);
			}
		}
	}

	/**
	 * Collect all policies by traversing the tree in DFS order and using only
	 * fromPolicies, to avoid duplicate entries. Results are put into the
	 * provided collection.
	 */
	public void collectPolicies(Collection<DependencyPolicy> policies) {
		policies.addAll(sourcePolicies.values());
		if (hasChildren()) {
			for (ComponentNode child : getChildren()) {
				child.collectPolicies(policies);
			}
		}
	}

	/** {@inheritDoc} */
	@Override
	protected ComponentNode[] allocateArray(int size) {
		return new ComponentNode[size];
	}

	/** {@inheritDoc} */
	@Override
	public String getId() {
		// names are unique for architectures
		return getName();
	}

	/** {@inheritDoc} */
	@Override
	public String getName() {
		return name;
	}

	/** Returns the name. */
	@Override
	public String toString() {
		return getName();
	}

	/** {@inheritDoc} */
	@Override
	public ComponentNode deepClone() throws DeepCloneException {
		return new ComponentNode(this);
	}

	/** Adds an additional pattern to identify elements of this component. */
	public void addIncludeRegex(String regex) throws ConQATException {
		containedElementPatterns.add(CommonUtils.compilePattern(regex));
	}

	/**
	 * Adds an additional exclude pattern to explicitly exclude elements of this
	 * component. (Overrules patterns added by {@link #addIncludeRegex(String)}
	 * ).
	 */
	/* package */void addExcludeRegex(String regex) throws ConQATException {
		excludedElementPatterns.add(CommonUtils.compilePattern(regex));
	}

	/** Add a dependency policy to this component. */
	/* package */void addPolicy(DependencyPolicy policy) throws ConQATException {
		if (policy.getSource() == this) {
			if (sourcePolicies.containsKey(policy.getTarget())) {
				throw new ConQATException("Duplicate policy from " + getName()
						+ " to " + policy.getTarget());
			}
			sourcePolicies.put(policy.getTarget(), policy);
		}
		if (policy.getTarget() == this) {
			targetPolicies.add(policy);
		}
	}

	/**
	 * Find all components (this plus child components) into which the given
	 * element name fits. They are put into the provided collection. The list of
	 * component nodes is filled by 'preorder' traversal.
	 */
	/* package */void findMatchingComponents(String elementName,
			List<ComponentNode> result) {
		if (containedElementPatterns.matchesAny(elementName)) {

			// explicitly check if elementName is excluded
			if (!excludedElementPatterns.matchesAny(elementName)) {
				result.add(this);
			}
		}

		if (hasChildren()) {
			for (ComponentNode child : getChildren()) {
				child.findMatchingComponents(elementName, result);
			}
		}
	}

	/** Returns whether there is a policy to the other node. */
	@Override
	public boolean hasPolicyTo(IComponent other) {
		return sourcePolicies.containsKey(other);
	}

	/** Returns the dependency to the given component (or null if non exists). */
	@Override
	public DependencyPolicy getPolicyTo(IComponent other) {
		return sourcePolicies.get(other);
	}

	/**
	 * Returns true, if this node (or one of its ancestors) carries the
	 * {@link EStereotype#PUBLIC} stereotype
	 */
	public boolean isPublic() {
		return hasTypeAncestor(EStereotype.PUBLIC);
	}

	/**
	 * Returns true, if this node (or one of its ancestors) carries the
	 * {@link EStereotype#COMPONENT_PUBLIC} stereotype
	 */
	public boolean isComponentPublic() {
		return hasTypeAncestor(EStereotype.COMPONENT_PUBLIC);
	}

	/** Returns true, if node has an ancestor (including this) of given type. */
	private boolean hasTypeAncestor(EStereotype type) {
		ComponentNode ancestor = this;
		while (ancestor != null) {
			if (ancestor.stereotype == type) {
				return true;
			}
			ancestor = ancestor.getParent();
		}

		return false;
	}

	/**
	 * Returns a set containing this node and all predecessors of this node in
	 * the hierarchy! The order of nodes is preserved and starts from the
	 * current node down to the root.
	 */
	@Override
	public LinkedHashSet<ComponentNode> getAncestors() {
		LinkedHashSet<ComponentNode> result = new LinkedHashSet<ComponentNode>();
		ComponentNode node = this;
		while (node != null) {
			result.add(node);
			node = node.getParent();
		}
		return result;
	}

	/** Returns the relative Position of this Component. */
	public Point getPosition() {
		return pos;
	}

	/** Returns the stereotype. */
	@Override
	public EStereotype getStereotype() {
		return stereotype;
	}

	/** Returns the absolute Position of this Component. */
	public Point getAbsolutePosition() {
		Point result = new Point(pos);
		if (getParent() != null) {
			Point parentPos = getParent().getAbsolutePosition();
			result.translate(parentPos.x, parentPos.y);
		}
		return result;
	}

	/** Returns the Dimension of this Component. */
	public Dimension getDimension() {
		return dim;
	}

	/** Returns the absolute bounds of this component. */
	public Rectangle getAbsoluteBounds() {
		return new Rectangle(getAbsolutePosition(), getDimension());
	}

	/** Retrieves all outgoing policies of this component. */
	public Collection<DependencyPolicy> getOutgoingPolicies() {
		return CollectionUtils.asUnmodifiable(sourcePolicies.values());
	}

	/** Retrieves all incoming policies of this component. */
	public Collection<DependencyPolicy> getIncomingPolicies() {
		return CollectionUtils.asUnmodifiable(targetPolicies);
	}

	/**
	 * Creates and returns a list of {@link ICodeMapping}s out of a
	 * {@link PatternList} with the specified {@link ECodeMappingType}.
	 */
	private static List<ICodeMapping> createCodeMappingList(
			PatternList patternList, ECodeMappingType type) {
		List<ICodeMapping> codeMappings = new ArrayList<ICodeMapping>();

		for (Pattern pattern : patternList) {
			codeMappings.add(new PatternToCodeMappingAdaptor(pattern, type));
		}

		return codeMappings;
	}

	/** {@inheritDoc} */
	@Override
	public UnmodifiableList<ICodeMapping> getCodeMappings() {
		List<ICodeMapping> codeMappings = new ArrayList<ICodeMapping>();
		codeMappings.addAll(createCodeMappingList(containedElementPatterns,
				ECodeMappingType.INCLUDE));
		codeMappings.addAll(createCodeMappingList(excludedElementPatterns,
				ECodeMappingType.EXCLUDE));
		return CollectionUtils.asUnmodifiable(codeMappings);
	}

	/** {@inheritDoc} */
	@Override
	public boolean isDescendant(IComponent component) {
		if (component instanceof ComponentNode) {
			LinkedHashSet<ComponentNode> ancestors = getAncestors();
			if (ancestors.contains(component)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Collects all transitive children of this ComponentNode. The result is
	 * returned in the provided collection.
	 */
	private void collectTransitiveChildren(Collection<ComponentNode> children) {
		children.add(this);

		if (hasChildren()) {
			for (ComponentNode component : getChildren()) {
				component.collectTransitiveChildren(children);
			}
		}
	}

	/** Returns true, if a node is a top level component in the architecture */
	@Override
	public boolean isToplevel() {
		return getParent() != null && getParent().getParent() == null;
	}

	/** {@inheritDoc} */
	@Override
	public Set<ComponentNode> getDescendants() {
		Set<ComponentNode> result = new IdentityHashSet<ComponentNode>();
		collectTransitiveChildren(result);
		return result;
	}

	/** {@inheritDoc} */
	@Override
	public Set<? extends IComponent> getSubComponents() {
		if (hasChildren()) {
			IdentityHashSet<IComponent> result = new IdentityHashSet<IComponent>();
			Collections.addAll(result, getChildren());
			return result;
		}
		return CollectionUtils.emptySet();
	}

	/**
	 * Retrieves the human-readable description of this node. This may be an
	 * empty string in case there is no description, but this method will never
	 * return null.
	 */
	public String getDescription() {
		return description;
	}

	/** Sets a human-readable description for this component. */
	public void setDescription(String description) {
		this.description = description;
	}
}