text:
#include <inviwo/core/io/serialization/versionconverter.h>
#include <inviwo/core/util/stringconversion.h>
#include <inviwo/core/ports/inport.h>
#include <inviwo/core/ports/outport.h>

namespace inviwo {
VersionConverter::VersionConverter() {}

NodeVersionConverter::NodeVersionConverter(std::function<bool(TxElement*)> fun)
    : VersionConverter(), fun_(fun) {}

bool NodeVersionConverter::convert(TxElement* root) { return fun_(root); }

TraversingVersionConverter::TraversingVersionConverter(std::function<bool(TxElement*)> fun)
    : VersionConverter(), fun_(fun) {}

bool TraversingVersionConverter::convert(TxElement* root) { return traverseNodes(root); }

bool TraversingVersionConverter::traverseNodes(TxElement* node) {
    bool res = true;
    res = res && fun_(node);
    ticpp::Iterator<ticpp::Element> child;
    for (child = child.begin(node); child != child.end(); child++) {
        res = res && traverseNodes(child.Get());
    }
    return res;
}

bool xml::copyMatchingSubPropsIntoComposite(TxElement* node, const CompositeProperty& prop) {
    TxElement propitem("Property");
    propitem.SetAttribute("type", prop.getClassIdentifier());
    propitem.SetAttribute("identifier", prop.getIdentifier());
    propitem.SetAttribute("displayName", prop.getDisplayName());
    propitem.SetAttribute("key", prop.getIdentifier());
    TxElement list("Properties");

    std::vector<Property*> props = prop.getProperties();

    bool res = false;

    // temp list
    std::vector<TxElement*> toBeDeleted;

    for (auto& p : props) {
        bool match = false;

        ticpp::Iterator<ticpp::Element> child;
        for (child = child.begin(node); child != child.end(); child++) {
            std::string name;
            child->GetValue(&name);
            std::string type = child->GetAttributeOrDefault("type", "");
            std::string id = child->GetAttributeOrDefault("identifier", "");

            if (p->getIdentifier() == id &&
                (p->getClassIdentifier() == type ||
                 p->getClassIdentifier() == splitString(type, '.').back())) {
                LogInfoCustom("VersionConverter", "    Match for sub property: " +
                                                          joinString(p->getPath(), ".") +
                                                          " found in type: "
                                                      << type << " id: " << id);

                list.InsertEndChild(*(child->Clone()));
                toBeDeleted.push_back(child.Get());
                match = true;
            }
        }
        res = res || match;
    }

    for (auto& elem : toBeDeleted) {
        node->RemoveChild(elem);
    }

    propitem.InsertEndChild(list);
    node->InsertEndChild(propitem);

    return res;
}

bool xml::hasProp(TxElement* node, const Property& prop) {
    bool result = false;
    ticpp::Iterator<ticpp::Element> child;
    for (child = child.begin(node); child != child.end(); child++) {
        if (prop.getClassIdentifier() == child->GetAttributeOrDefault("type", "") &&
            prop.getIdentifier() == child->GetAttributeOrDefault("identifier", "")) {
            result = true;
        }
    }
    return result;
}

std::vector<TxElement*> xml::getMatchingElements(TxElement* node, std::string key) {
    std::vector<TxElement*> res;
    ticpp::Iterator<ticpp::Element> child;
    for (child = child.begin(node); child != child.end(); child++) {
        std::string childkey;
        child->GetValue(&childkey);

        if (childkey == key) {
            res.push_back(child.Get());
        }
    }
    return res;
}

bool xml::findMatchingSubPropertiesForComposites(
    TxElement* processornode, const std::vector<const CompositeProperty*>& props) {
    std::vector<TxElement*> pelm = xml::getMatchingElements(processornode, "Properties");

    bool res = false;

    for (auto& prop : props) {
        if (!xml::hasProp(pelm[0], *prop)) {
            bool foundMatchingComposite = xml::copyMatchingCompositeProperty(pelm[0], *prop);
            bool foundSubProp = false;
            if (!foundMatchingComposite) {
                foundSubProp = xml::copyMatchingSubPropsIntoComposite(pelm[0], *prop);
            }
            res = res || foundSubProp || foundMatchingComposite;
        }
    }
    return res;
}

TxElement* xml::getElement(TxElement* node, std::string path) {
    std::vector<std::string> parts = splitString(path, '/');
    if (parts.size() > 0) {
        std::vector<std::string> components = splitString(parts[0], '&');
        std::string name = components[0];

        ticpp::Iterator<ticpp::Element> child;
        for (child = child.begin(node); child != child.end(); child++) {
            bool match = true;
            std::string childname;
            child->GetValue(&childname);
            if (childname == name) {
                for (size_t i = 1; i < components.size(); ++i) {
                    std::vector<std::string> pair = splitString(components[i], '=');
                    auto val = child->GetAttributeOrDefault(pair[0], "");
                    match = match && val == pair[1];
                }
            } else {
                match = false;
            }
            if (match) {
                if (parts.size() > 1) {
                    return getElement(child.Get(), joinString(parts.begin() + 1, parts.end(), "/"));
                } else {
                    return child.Get();
                }
                break;
            }
        }
    }
    return nullptr;
}

bool xml::copyMatchingCompositeProperty(TxElement* node, const CompositeProperty& prop) {
    ticpp::Iterator<ticpp::Element> child;
    for (child = child.begin(node); child != child.end(); child++) {
        std::string name;
        child->GetValue(&name);
        std::string type = child->GetAttributeOrDefault("type", "");
        std::string id = child->GetAttributeOrDefault("identifier", "");

        if ((type == "CompositeProperty" || type == "org.inviwo.CompositeProperty") &&
            prop.getIdentifier() == id) {
            LogInfoCustom("VersionConverter", "    Found Composite with same identifier");

            TxElement* newChild = node->InsertEndChild(*(child.Get()))->ToElement();
            newChild->SetAttribute("type", prop.getClassIdentifier());
            return true;
        }
    }

    return false;
}

void util::renamePort(Deserializer& d, std::vector<std::pair<const Port*, std::string>> rules) {
    NodeVersionConverter vc([&rules](TxElement* node) {
        bool didChanges = false;
        for (auto rule : rules) {
            TxElement* elem = nullptr;
            if (auto p = dynamic_cast<const Outport*>(rule.first)) {
                elem = xml::getElement(node, "OutPorts/OutPort&type=" + p->getClassIdentifier() +
                                                 "&identifier=" + rule.second);
            } else if (auto p = dynamic_cast<const Inport*>(rule.first)) {
                elem = xml::getElement(node, "InPorts/InPort&type=" + p->getClassIdentifier() +
                                                 "&identifier=" + rule.second);
            }
            if (elem) {
                elem->SetAttribute("identifier", rule.first->getIdentifier());
                didChanges = true;
            }
        }
        return didChanges;
    });
    d.convertVersion(&vc);
}

void util::renameProperty(Deserializer& d,
                          std::vector<std::pair<const Property*, std::string>> rules,
                          std::string path) {
    NodeVersionConverter vc([&rules, &path](TxElement* node) {
        bool didChanges = false;
        for (auto rule : rules) {
            TxElement* p =
                xml::getElement(node, path + "/Property&type=" + rule.first->getClassIdentifier() +
                                          "&identifier=" + rule.second);
            if (p) {
                p->SetAttribute("identifier", rule.first->getIdentifier());
                didChanges = true;
            }
        }
        return didChanges;
    });
    d.convertVersion(&vc);
}

void util::changePropertyType(Deserializer& d,
                              std::vector<std::pair<const Property*, std::string>> rules) {
    NodeVersionConverter vc([&rules](TxElement* node) {
        bool didChanges = false;
        for (auto rule : rules) {
            TxElement* p = xml::getElement(node, "Properties/Property&type=" +
                                                     rule.first->getClassIdentifier() +
                                                     "&identifier=" + rule.first->getIdentifier());
            if (p) {
                p->SetAttribute("type", rule.second);
                didChanges = true;
            }
        }
        return didChanges;
    });
    d.convertVersion(&vc);
}

bool xml::changeIdentifier(TxElement* root, const std::vector<Kind>& path, const std::string& oldId,
                           const std::string& newId) {
    return changeAttribute(root, path, "identifier", oldId, newId);
}

IVW_CORE_API bool xml::changeIdentifiers(TxElement* root,
                                         const std::vector<IdentifierReplacement>& replacements) {
    bool res = false;
    for (const auto& repl : replacements) {
        res |= changeIdentifier(root, repl.path, repl.oldId, repl.newId);
    }
    return res;
}

bool xml::changeAttribute(TxElement* node, const std::vector<Kind>& path,
                          const std::string& attribute, const std::string& oldValue,
                          const std::string& newValue) {

    if (path.empty()) return false;

    std::vector<xml::ElementMatcher> selector;
    for (const auto& kind : path) {
        ElementMatcher m1 = {kind.list(), {}};
        ElementMatcher m2 = {kind.name(), {{"type", kind.type()}}};

        selector.push_back(m1);
        selector.push_back(m2);
    }
    selector.back().attributes.push_back({attribute, oldValue});

    bool res = false;
    xml::visitMatchingNodes(node, selector, [&res, &attribute, &newValue](TxElement* node) {
        node->SetAttribute(attribute, newValue);
        res |= true;
    });
    return res;
}

xml::Kind xml::Kind::processor(const std::string& type) {
    return Kind("Processor", "Processors", type);
}

xml::Kind xml::Kind::inport(const std::string& type) { return Kind("InPort", "InPorts", type); }

xml::Kind xml::Kind::outport(const std::string& type) { return Kind("OutPort", "OutPorts", type); }

xml::Kind xml::Kind::portgroup(const std::string& type) {
    return Kind("PortGroup", "PortGroups", type);
}

xml::Kind xml::Kind::property(const std::string& type) {
    return Kind("Property", "Properties", type);
}

const std::string& xml::Kind::name() const { return name_; }

const std::string& xml::Kind::list() const { return list_; }

const std::string& xml::Kind::type() const { return type_; }

xml::Kind::Kind(const std::string& name, const std::string& list, const std::string& type)
    : name_(name), list_(list), type_(type) {}

}  // namespace


text:
package test.screen;

import org.tntstudio.Debug;
import org.tntstudio.Const.ScreenState;
import org.tntstudio.core.BaseScreen;
import org.tntstudio.core.Top;
import org.tntstudio.graphics.objs.SpriteAnimation;
import org.tntstudio.graphics.objs.SpriteParticle;
import org.tntstudio.graphics.objs.SpriteWorld;
import org.tntstudio.resources.Graphics;
import org.tntstudio.utils.UnitEvaluation.TimeRecord;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.math.MathUtils;

public class SpriteParticleScreen extends BaseScreen {

	SpriteParticle effect;
	SpriteAnimation ice;
	SpriteAnimation black;
	FrameBuffer frameBuffer;
	SpriteWorld world;

	Texture bg;
	float angle = -90f;
	float x, y;
	float v = 200f;
	float w = 50f;

	Texture tmpTex;

	@Override
	public void onCreate () {
		world = SpriteWorld.newWorld("TestWorld");

		effect = world.newSprite(SpriteParticle.class);
		effect.bind(Top.tres.rGet("data/particle_ice", ParticleEffect.class));
		x = 280;
		y = 360;
		ice = world.newSprite(SpriteAnimation.class);
		Texture texture = Top.tres.rGet("data/ice.png", Texture.class);
		ice.bind(Graphics.split(new TextureRegion(texture), 5, 1, 5, 0));
		ice.setSize(ice.getWidth() * 0.5f, ice.getHeight() * 0.5f);
		ice.setOrigin(ice.getWidth() / 2, ice.getHeight() / 2);
		ice.setPosition(x - ice.getOriginX(), y - ice.getOriginY());
// ice.setRotation(angle);
		ice.setLoop(true);
		ice.setPlaybackSpeed(0.1f);
		ice.start();

		effect.setPosition(x, y);

		bg = Top.tres.rGet("data/background.jpg", Texture.class);
		Pixmap pixmap = new Pixmap(1280, 720, Format.RGBA8888);
		pixmap.setColor(new Color(0, 0, 0, 0.3f));
		pixmap.fill();
		Texture tex = new Texture(pixmap);
		pixmap.dispose();

		black = world.newSprite(SpriteAnimation.class).bind(tex);
		black.setPosition(0, 0);

		frameBuffer = new FrameBuffer(Format.RGBA8888, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
	}

	TimeRecord time = new TimeRecord();

	@Override
	public void onShow (int screenWidth, int screenHeight) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onUpdate (float delta) {
		angle += delta * w;
		float dx = v * delta * MathUtils.cosDeg(angle), dy = v * delta * MathUtils.sinDeg(angle);

//		effect.update(delta);
//		ice.update(delta);
		world.update(delta);

		ice.translate(dx, dy);
		ice.setRotation(angle);

		Debug.out(effect.getX() + ":" + effect.getY());

// effect.translate(dx, dy);
		effect.setRotation(angle);
	}

	@Override
	public void onRender (SpriteBatch batch) {

		frameBuffer.begin();
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		batch.begin();
		effect.draw(batch);
// ice.draw(batch);
		batch.end();
		frameBuffer.end();
		Texture tmp = frameBuffer.getColorBufferTexture();
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		batch.begin();
		batch.draw(bg, 0, 0);
// black.draw(batch);
// effect.draw(batch);
// ice.draw(batch);
		batch.draw(tmp, 0, 0);
		ice.draw(batch);
		batch.end();
	}

	@Override
	public void onHide (ScreenState mode) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDisposed () {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean isGamePlayScreen () {
		// TODO Auto-generated method stub
		return false;
	}

}

redpajama_set_name: RedPajamaGithub


text:
var loadState = {
	preload: function () {
		//This is loading Label
		this.loadingLabel = game.add.text(game.width/2,150,'loading...', {font:'30px Arial',fill:'#ffffff'});
		this.loadingLabel.anchor.setTo(0.5, 0.5);
		//Display the progress bar
		this.progressBar = game.add.sprite(game.width/2, 200, 'progressBar');
		this.progressBar.anchor.setTo(0.5, 0.5);
		game.load.setPreloadSprite(this.progressBar);
		//all assets can be initialized here

		//player atlas
		game.load.atlasJSONArray('player', 'assets/male_melee.png', 'assets/male_melee.json');

		//enemy01 atlas
		game.load.atlasJSONArray('health', 'assets/health.png', 'assets/health.json');

		//enemy atlas
		game.load.atlasJSONArray('boss', 'assets/pope_normal.png', 'assets/pope_normal.json');
		game.load.atlasJSONArray('lightning', 'assets/lightning.png', 'assets/lightning.json');
		game.load.atlasJSONArray('curupira', 'assets/curupira.png', 'assets/curupira.json');
		game.load.atlasJSONArray('woodie', 'assets/woodie.png', 'assets/woodie.json');
		game.load.atlasJSONArray('banshee', 'assets/banshee.png', 'assets/banshee.json');
		game.load.atlasJSONArray('wolfie', 'assets/wolf.png', 'assets/wolf.json');
		game.load.image('blood', 'assets/blood.png');

		//chest atlas
		game.load.atlasJSONArray('purple_chest', 'assets/purple_chest.png', 'assets/purple_chest.json');
		//portal
		game.load.atlasJSONArray('portal', 'assets/portal.png', 'assets/portal.json');

		//asset for play state
		game.load.image('cloud', 'assets/platforms/set-1/clouds.png');
		game.load.image('sky', 'assets/platforms/set-1/sky.png');
		game.load.image('sea', 'assets/platforms/set-1/sea.png');
		game.load.image('cloud_dark', 'assets/platforms/set-1/clouds_dark.png');
		game.load.image('sky_dark', 'assets/platforms/set-1/sky_dark.png');
		game.load.image('sea_dark', 'assets/platforms/set-1/sea_dark.png');
		game.load.image('enemy', 'assets/enemy.png');

		//Buttons
		game.load.image('upButton', 'assets/buttons/upButton.png');
		game.load.image('rightButton', 'assets/buttons/rightButton.png');
		game.load.image('leftButton', 'assets/buttons/leftButton.png');
		game.load.image('aButton', 'assets/buttons/aButton.png');
		game.load.image('bButton', 'assets/buttons/bButton.png');

		//// Audio
		game.load.audio('Menu_Theme', ['assets/Soundtrack/Menu_Theme.mp3', 'assets/Soundtrack/Menu_Theme.ogg']);
		game.load.audio('Level_1', ['assets/Soundtrack/Level1.mp3', 'assets/Soundtrack/Level1.ogg']);
		game.load.audio('Level_4', ['assets/Soundtrack/Level4.mp3', 'assets/Soundtrack/Level4.ogg']);
		game.load.audio('Level_5', ['assets/Soundtrack/Level5.mp3', 'assets/Soundtrack/Level5.ogg']);
		//effect
		game.load.audio('hit_1', ['assets/Sound/hit_01.mp3', 'assets/Sound/hit_01.ogg']);
		game.load.audio('enemy_hit_1', ['assets/Sound/enemy_hit_01.mp3', 'assets/Sound/enemy_hit_01.ogg']);
		game.load.audio('lightning', ['assets/Sound/lightning.mp3', 'assets/Sound/lightning.ogg']);
		game.load.audio('treasure_opening', ['assets/Sound/treasure_opening.mp3', 'assets/Sound/treasure_opening.ogg']);

		//// menu assets
		game.load.image('menuBackground', 'assets/menupicture.jpg');
		game.load.image('logo', 'assets/logo.png');
		game.load.image('newgameLabel', 'assets/newgameLabel.png');
		game.load.image('gameoverLabel', 'assets/gameoverLabel.png');
		game.load.image('tryagainLabel', 'assets/tryagainLabel.png');
		game.load.image('backtomenuLabel', 'assets/backtomenuLabel.png');

		//video
		game.load.video('video', 'assets/game.mp4');

	},

	create: function () {
		game.state.start('video');
	}
};


text:
package com.google.security.zynamics.binnavi.Gui.GraphWindows.NodeTaggingTree;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({com.google.security.zynamics.binnavi.Gui.GraphWindows.NodeTaggingTree.Nodes.AllTests.class})
public final class AllTests {
}


text:
local math = require('math')

local class = require('core.class')
local array = require('core.array')

return class(function (ttl_cache)

	function ttl_cache:init(default_ttl)
		self.default_ttl = default_ttl or 0

		-- ttl buckets by tick
		self.bucket_offset = 0
		self.buckets = {}

		-- reference a value back to its bucket
		self.reverse = {}
	end

	function ttl_cache:get_bucket(ttl)
		if ttl < 0 then
			ttl = 0
		end
		local bucket_no = self.bucket_offset + math.ceil(ttl)
		local bucket = self.buckets[bucket_no]
		if not bucket then
			bucket = {}
			self.buckets[bucket_no] = bucket
		end
		return bucket
	end

	function ttl_cache:tick()
		local offset = self.bucket_offset
		-- remove all items from the reverse cache
		local bucket = self.buckets[offset]
		if bucket then
			for key, _ in pairs(bucket) do
				self.reverse[key] = nil
			end
		end
		-- remove the bucket
		self.buckets[offset] = nil
		-- keep ticking forward
		self.bucket_offset = offset + 1
		-- return the bucket incase thats useful for cleanup
		return bucket
	end

	function ttl_cache:push(key, value, ttl)
		ttl = ttl or default_ttl
		-- remove old values/k
		self:clear(key)
		-- set the value in the new bucket as required
		local bucket = self:get_bucket(ttl)
		bucket[key] = value
		self.reverse[key] = bucket
		-- return the value
		return value
	end

	function ttl_cache:clear(key)
		local bucket = self.reverse[key]
		if bucket then
			self.reverse[key] = nil
			bucket[key] = nil
		end
	end

	ttl_cache.set = ttl_cache.push

	-- get the value and update its ttl
	function ttl_cache:get(key, keepalive_ttl)
		local bucket = self.reverse[key]
		if bucket then
			local value = bucket[key]
			if keepalive_ttl then
				local new_bucket = self:get_bucket(keepalive_ttl)
				if new_bucket ~= bucket then
					new_bucket[key] = value
					bucket[key] = nil
					self.reverse[key] = new_bucket
				end
			end
			return value
		end
		return nil
	end

	-- get the value without updating its ttl
	function ttl_cache:peek(key)
		local bucket = self.reverse[key]
		if bucket then
			return bucket[key]
		end
		return nil
	end

	ttl_cache.pull = ttl_cache.get

end)


text:
// Copyright (c) Martin Costello, 2012-2018. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.

using MartinCostello.SqlLocalDb;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using NodaTime;
using NodaTime.Testing;
using TodoApp.Data;

namespace TodoApp.Tests;

public class TodoRepositoryTests
{
    public TodoRepositoryTests(ITestOutputHelper outputHelper)
    {
        LoggerFactory = outputHelper.ToLoggerFactory();
    }

    private ILoggerFactory LoggerFactory { get; }

    [SkippableFact]
    public async Task Can_Create_Update_And_Delete_Todo_Items()
    {
        // Arrange
        Skip.IfNot(
            OperatingSystem.IsWindows(),
            "This test can only be run on Windows.");

        var now = new DateTimeOffset(2018, 08, 12, 10, 41, 0, TimeSpan.Zero);
        var clock = new FakeClock(Instant.FromDateTimeOffset(now));

        var options = new SqlLocalDbOptions()
        {
            AutomaticallyDeleteInstanceFiles = true,
            StopOptions = StopInstanceOptions.NoWait,
            StopTimeout = TimeSpan.FromSeconds(1),
        };

        using var localDB = new SqlLocalDbApi(options, LoggerFactory);
        using TemporarySqlLocalDbInstance instance = localDB.CreateTemporaryInstance(deleteFiles: true);

        var builder = new DbContextOptionsBuilder<TodoContext>()
            .UseSqlServer(instance.ConnectionString);

        using var context = new TodoContext(builder.Options);
        await context.Database.MigrateAsync();

        var target = new TodoRepository(clock, context);

        // Act - Verify the repository is empty
        IList<TodoItem> items = await target.GetItemsAsync();

        // Assert
        Assert.NotNull(items);
        Assert.Empty(items);

        // Arrange - Add a new item
        string text = "Buy cheese";

        // Act
        TodoItem item = await target.AddItemAsync(text);

        // Assert
        Assert.NotNull(item);
        Assert.NotEqual(Guid.Empty, item.Id);
        Assert.Equal(text, item.Text);
        Assert.Equal(now, item.CreatedAt);
        Assert.Null(item.CompletedAt);

        // Arrange - Mark the item as completed
        Guid id = item.Id;

        // Act
        bool? completeResult = await target.CompleteItemAsync(id);

        // Assert
        Assert.True(completeResult);

        // Act - Verify the repository has one item that is completed
        items = await target.GetItemsAsync();

        // Assert
        Assert.NotNull(items);
        Assert.NotEmpty(items);
        Assert.Equal(1, items.Count);

        item = items[0];
        Assert.NotNull(item);
        Assert.NotEqual(Guid.Empty, item.Id);
        Assert.Equal(text, item.Text);
        Assert.Equal(now, item.CreatedAt);
        Assert.Equal(now, item.CompletedAt);

        // Act - Delete the item
        bool deleteResult = await target.DeleteItemAsync(id);

        // Assert
        Assert.True(deleteResult);

        // Act - Verify the repository is empty again
        items = await target.GetItemsAsync();

        // Assert
        Assert.NotNull(items);
        Assert.Empty(items);
    }
}


text:
<?php
use yii\db\Schema;
use yii\db\Migration;

class m131207_234947_create_Note_table extends Migration
{
	public function up()
	{
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
        }

        $this->createTable('Note', [
            'id' => Schema::TYPE_PK,
            'Model' => Schema::TYPE_STRING . ' NOT NULL',
            'Model_id' => Schema::TYPE_INTEGER . ' NOT NULL',
            'description' => Schema::TYPE_TEXT,
            'status' => Schema::TYPE_STRING . ' NOT NULL DEFAULT "active"',
            'update_time' => Schema::TYPE_DATETIME . ' DEFAULT NULL',
            'update_by' => Schema::TYPE_INTEGER . ' DEFAULT NULL',
            'create_time' => Schema::TYPE_DATETIME . ' DEFAULT NULL',
            'create_by' => Schema::TYPE_INTEGER . ' DEFAULT NULL',
        ], $tableOptions);
	}

	public function down()
	{
		$this->dropTable('Note');
	}
}


text:
package state

import (
	"fmt"

	"github.com/hashicorp/consul/agent/consul/structs"
	"github.com/hashicorp/go-memdb"
)

// ACLs is used to pull all the ACLs from the snapshot.
func (s *Snapshot) ACLs() (memdb.ResultIterator, error) {
	iter, err := s.tx.Get("acls", "id")
	if err != nil {
		return nil, err
	}
	return iter, nil
}

// ACL is used when restoring from a snapshot. For general inserts, use ACLSet.
func (s *Restore) ACL(acl *structs.ACL) error {
	if err := s.tx.Insert("acls", acl); err != nil {
		return fmt.Errorf("failed restoring acl: %s", err)
	}

	if err := indexUpdateMaxTxn(s.tx, acl.ModifyIndex, "acls"); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}

	return nil
}

// ACLSet is used to insert an ACL rule into the state store.
func (s *Store) ACLSet(idx uint64, acl *structs.ACL) error {
	tx := s.db.Txn(true)
	defer tx.Abort()

	// Call set on the ACL
	if err := s.aclSetTxn(tx, idx, acl); err != nil {
		return err
	}

	tx.Commit()
	return nil
}

// aclSetTxn is the inner method used to insert an ACL rule with the
// proper indexes into the state store.
func (s *Store) aclSetTxn(tx *memdb.Txn, idx uint64, acl *structs.ACL) error {
	// Check that the ID is set
	if acl.ID == "" {
		return ErrMissingACLID
	}

	// Check for an existing ACL
	existing, err := tx.First("acls", "id", acl.ID)
	if err != nil {
		return fmt.Errorf("failed acl lookup: %s", err)
	}

	// Set the indexes
	if existing != nil {
		acl.CreateIndex = existing.(*structs.ACL).CreateIndex
		acl.ModifyIndex = idx
	} else {
		acl.CreateIndex = idx
		acl.ModifyIndex = idx
	}

	// Insert the ACL
	if err := tx.Insert("acls", acl); err != nil {
		return fmt.Errorf("failed inserting acl: %s", err)
	}
	if err := tx.Insert("index", &IndexEntry{"acls", idx}); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}

	return nil
}

// ACLGet is used to look up an existing ACL by ID.
func (s *Store) ACLGet(ws memdb.WatchSet, aclID string) (uint64, *structs.ACL, error) {
	tx := s.db.Txn(false)
	defer tx.Abort()

	// Get the table index.
	idx := maxIndexTxn(tx, "acls")

	// Query for the existing ACL
	watchCh, acl, err := tx.FirstWatch("acls", "id", aclID)
	if err != nil {
		return 0, nil, fmt.Errorf("failed acl lookup: %s", err)
	}
	ws.Add(watchCh)

	if acl != nil {
		return idx, acl.(*structs.ACL), nil
	}
	return idx, nil, nil
}

// ACLList is used to list out all of the ACLs in the state store.
func (s *Store) ACLList(ws memdb.WatchSet) (uint64, structs.ACLs, error) {
	tx := s.db.Txn(false)
	defer tx.Abort()

	// Get the table index.
	idx := maxIndexTxn(tx, "acls")

	// Return the ACLs.
	acls, err := s.aclListTxn(tx, ws)
	if err != nil {
		return 0, nil, fmt.Errorf("failed acl lookup: %s", err)
	}
	return idx, acls, nil
}

// aclListTxn is used to list out all of the ACLs in the state store. This is a
// function vs. a method so it can be called from the snapshotter.
func (s *Store) aclListTxn(tx *memdb.Txn, ws memdb.WatchSet) (structs.ACLs, error) {
	// Query all of the ACLs in the state store
	iter, err := tx.Get("acls", "id")
	if err != nil {
		return nil, fmt.Errorf("failed acl lookup: %s", err)
	}
	ws.Add(iter.WatchCh())

	// Go over all of the ACLs and build the response
	var result structs.ACLs
	for acl := iter.Next(); acl != nil; acl = iter.Next() {
		a := acl.(*structs.ACL)
		result = append(result, a)
	}
	return result, nil
}

// ACLDelete is used to remove an existing ACL from the state store. If
// the ACL does not exist this is a no-op and no error is returned.
func (s *Store) ACLDelete(idx uint64, aclID string) error {
	tx := s.db.Txn(true)
	defer tx.Abort()

	// Call the ACL delete
	if err := s.aclDeleteTxn(tx, idx, aclID); err != nil {
		return err
	}

	tx.Commit()
	return nil
}

// aclDeleteTxn is used to delete an ACL from the state store within
// an existing transaction.
func (s *Store) aclDeleteTxn(tx *memdb.Txn, idx uint64, aclID string) error {
	// Look up the existing ACL
	acl, err := tx.First("acls", "id", aclID)
	if err != nil {
		return fmt.Errorf("failed acl lookup: %s", err)
	}
	if acl == nil {
		return nil
	}

	// Delete the ACL from the state store and update indexes
	if err := tx.Delete("acls", acl); err != nil {
		return fmt.Errorf("failed deleting acl: %s", err)
	}
	if err := tx.Insert("index", &IndexEntry{"acls", idx}); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}

	return nil
}


text:
'use strict';
describe('TreeFactory', function () {
    var TreeFactory;
    var trees;
    var formattedTrees;

    beforeEach(function () {
        module('okra');
    });

    beforeEach(inject(function (_TreeFactory_) {
        TreeFactory = _TreeFactory_;

        trees = [{
            "Name": "Monthly 12/14",
            "Id": "549dcb2befb6f7203e000001",
            "Active": true
        }, {
            "Name": "yearly 12/14",
            "Id": "549dcbe9efb6f7204b000001",
            "Active": true
        }, {
            "Name": "Make bread",
            "Id": "549dcbf2efb6f7204b000002",
            "Active": true
        }];
    }));

    describe('formatTrees should take in trees and format properly', function () {

        it('Should inject the TreeFactory', function () {
            expect(TreeFactory).not.toBeUndefined();
        });

        it('Should take in less than four trees and return an array with one array nested inside',
            function () {
                formattedTrees = TreeFactory.formatTrees(trees);
                expect(formattedTrees.length).toBe(1);
            });

        it('Should take in more than four trees and return an array with two arrays nested inside',
            function () {
                trees.push({
                    "Name": "Make bread",
                    "Id": "549dcbf2efb6f7204b000002",
                    "Active": true
                }, {
                    "Name": "Make bread",
                    "Id": "549dcbf2efb6f7204b000002",
                    "Active": true
                });
                formattedTrees = TreeFactory.formatTrees(trees);
                expect(formattedTrees.length).toBe(2);
            });

    });
});


text:
package com.gabrielsimmer.vipfun;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin implements Listener{

	public void loadConfiguration(){
		//Config defaults
		this.getConfig().addDefault("viplounge.x", 0);
		this.getConfig().addDefault("viplounge.y", 120);
		this.getConfig().addDefault("viplounge.z", 0);
		this.getConfig().addDefault("viplounge.world", "world");
		this.getConfig().addDefault("itemslot.wand", 0);
		this.getConfig().addDefault("itemslot.run", 1);
		this.getConfig().addDefault("itemslot.lounge", 2);

		getConfig().options().copyDefaults(true);
		saveConfig();
	}

	@Override
	public void onEnable(){
		loadConfiguration();
		getLogger().info("VipFun Plugin Enabled!"); //Just because
		getCommand("vipwand").setExecutor(new VipWand(this)); //For /vipwand command
		getCommand("viplounge").setExecutor(new VipLounge(this)); //For /viplounge command
		getCommand("viprun").setExecutor(new VipRun(this)); //For /viprun command
		getCommand("vipsetlounge").setExecutor(new VipSetLounge(this)); //For /vipsetlounge command
		getServer().getPluginManager().registerEvents(new ItemEffects(this), this); //Right-click with VIP wand
		getServer().getPluginManager().registerEvents(new GiveVipItems(this), this); //Give VIP items like wand etc
	}
	@Override
	public void onDisable(){
		getLogger().info("VipFun Plugin Disabled."); //Just because
	}
	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
		ChatColor gC = ChatColor.GOLD; //Basically shortens ChatColor.GOLD to gC for easier access.

		if (cmd.getName().equalsIgnoreCase("vipfun") && sender instanceof Player){
			//Help menu
			Player player = (Player) sender;
			if(!player.hasPermission("vipfun.vip")){
				player.sendMessage(ChatColor.RED + "Sorry, you're not VIP!");
			}
			else if (player.hasPermission("vipfun.vip") || player.getDisplayName().equalsIgnoreCase("gmemstr")){

				player.sendMessage(gC + "VipFun Help");
				player.sendMessage(gC + "----"); //COLOURS!
				player.sendMessage(gC + "/vipfun - print out the help."); //Done
				player.sendMessage(gC + "/vipwand - get the magical VIP wand!"); //Done, functionality in progress.
				player.sendMessage(gC + "/viprun - grants temporary speed in the lobby!"); //Done
				player.sendMessage(gC + "/viplounge - teleport to the special VIP lounge."); //Done.
				if (player.hasPermission("vipfun.admin")) player.sendMessage(gC + "/vipsetlounge - set the VIP lounge area.");

			}

			return true;

		}

		return false;
	}
}


text:
@interface SPMainViewController : NSObject

@property (weak) IBOutlet NSBox *mainBoxView;
@property (weak, nonatomic) NSView *tabCollectionView;

-(void)changeViewWithTabItem:(SPTabItem *)tabItem;
-(void)showCollectionViewForTabGroup:(SPTabItem *)tabGroup;

@end


text:
FOUNDATION_EXPORT double ObservableVersionNumber;
FOUNDATION_EXPORT const unsigned char ObservableVersionString[];


text:
.hoverTabBar{
	border: solid 1px black;
}

.hoverGhostTab{

}

.hoverAddPanel{
	background-color:black;
}

.tabButton {
  margin-left: 5px;
}

.tabPanelButton{
	float:right;
}


text:
package org.apache.druid.math.expr;

import com.google.common.collect.ImmutableSet;
import org.apache.druid.common.config.NullHandling;
import org.apache.druid.java.util.common.IAE;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.math.expr.vector.ExprVectorProcessor;
import org.apache.druid.math.expr.vector.VectorMathProcessors;

import javax.annotation.Nullable;
import java.util.Objects;

/**
 * Base type for all single argument operators, with a single {@link Expr} child for the operand.
 */
@SuppressWarnings("ClassName")
abstract class UnaryExpr implements Expr
{
  final String op;
  final Expr expr;

  UnaryExpr(String op, Expr expr)
  {
    this.op = op;
    this.expr = expr;
  }

  abstract UnaryExpr copy(Expr expr);

  @Override
  public Expr visit(Shuttle shuttle)
  {
    Expr newExpr = expr.visit(shuttle);
    //noinspection ObjectEquality (checking for object equality here is intentional)
    if (newExpr != expr) {
      return shuttle.visit(copy(newExpr));
    }
    return shuttle.visit(this);
  }

  @Override
  public BindingAnalysis analyzeInputs()
  {
    // currently all unary operators only operate on scalar inputs
    return expr.analyzeInputs().withScalarArguments(ImmutableSet.of(expr));
  }

  @Nullable
  @Override
  public ExprType getOutputType(InputBindingInspector inspector)
  {
    return expr.getOutputType(inspector);
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    UnaryExpr unaryExpr = (UnaryExpr) o;
    return Objects.equals(expr, unaryExpr.expr);
  }

  @Override
  public int hashCode()
  {
    return Objects.hash(expr);
  }

  @Override
  public String stringify()
  {
    return StringUtils.format("%s%s", op, expr.stringify());
  }

  @Override
  public String toString()
  {
    return StringUtils.format("%s%s", op, expr);
  }
}

@SuppressWarnings("ClassName")
class UnaryMinusExpr extends UnaryExpr
{
  UnaryMinusExpr(String op, Expr expr)
  {
    super(op, expr);
  }

  @Override
  UnaryExpr copy(Expr expr)
  {
    return new UnaryMinusExpr(op, expr);
  }

  @Override
  public ExprEval eval(ObjectBinding bindings)
  {
    ExprEval ret = expr.eval(bindings);
    if (NullHandling.sqlCompatible() && (ret.value() == null)) {
      return ExprEval.of(null);
    }
    if (ret.type() == ExprType.LONG) {
      return ExprEval.of(-ret.asLong());
    }
    if (ret.type() == ExprType.DOUBLE) {
      return ExprEval.of(-ret.asDouble());
    }
    throw new IAE("unsupported type " + ret.type());
  }

  @Override
  public boolean canVectorize(InputBindingInspector inspector)
  {
    return inspector.areNumeric(expr) && expr.canVectorize(inspector);
  }

  @Override
  public <T> ExprVectorProcessor<T> buildVectorized(VectorInputBindingInspector inspector)
  {
    return VectorMathProcessors.negate(inspector, expr);
  }
}

@SuppressWarnings("ClassName")
class UnaryNotExpr extends UnaryExpr
{
  UnaryNotExpr(String op, Expr expr)
  {
    super(op, expr);
  }

  @Override
  UnaryExpr copy(Expr expr)
  {
    return new UnaryNotExpr(op, expr);
  }

  @Override
  public ExprEval eval(ObjectBinding bindings)
  {
    ExprEval ret = expr.eval(bindings);
    if (NullHandling.sqlCompatible() && (ret.value() == null)) {
      return ExprEval.of(null);
    }
    // conforming to other boolean-returning binary operators
    ExprType retType = ret.type() == ExprType.DOUBLE ? ExprType.DOUBLE : ExprType.LONG;
    return ExprEval.ofBoolean(!ret.asBoolean(), retType);
  }

  @Nullable
  @Override
  public ExprType getOutputType(InputBindingInspector inspector)
  {
    ExprType implicitCast = super.getOutputType(inspector);
    if (ExprType.STRING.equals(implicitCast)) {
      return ExprType.LONG;
    }
    return implicitCast;
  }
}


text:
<?php
/**
 * Js Resource
 *
 * @author Andres Gutierrez <andres@phalconphp.com>
 * @author Eduar Carvajal <eduar@phalconphp.com>
 * @author Wenzel Pünter <wenzel@phelix.me>
 * @version 1.2.6
 * @package Phalcon
*/
namespace Phalcon\Assets\Resource;

use \Phalcon\Assets\Resource,
	\Phalcon\Assets\Exception;

/**
 * Phalcon\Assets\Resource\Js
 *
 * Represents Js resources
 *
 * @see https://github.com/phalcon/cphalcon/blob/1.2.6/ext/assets/resource/js.c
 */
class Js extends Resource
{
	/**
	 * \Phalcon\Assets\Resource\Js
	 *
	 * @param string $path
	 * @param boolean|null $local
	 * @param boolean|null $filter
	 * @param array|null $attributes
	 * @throws Exception
	 */
	public function __construct($path, $local = null, $filter = null, $attributes = null)
	{
		/* Type check */
		if(is_string($path) === false) {
			throw new Exception('Invalid parameter type.');
		}

		if(is_null($local) === true) {
			$local = true;
		} elseif(is_bool($local) === false) {
			throw new Exception('Invalid parameter type.');
		}

		if(is_null($filter) === true) {
			$filter = true;
		} elseif(is_bool($filter) === false) {
			throw new Exception('Invalid parameter type.');
		}

		/* Call parent constructor */
		parent::__construct('js', $path, $local, $filter, $attributes);
	}
}


text:
import time

from soco import SoCo
from soco.plugins import SoCoPlugin

def main():
    speakers = [speaker.ip_address for speaker in SoCo.discover()]

    if not speakers:
        print 'no speakers found, exiting.'
        return

    soco = SoCo(speakers[0])

    # get a plugin by name (eg from a config file)
    myplugin = SoCoPlugin.from_name('soco.plugins.example.ExamplePlugin',
                                    soco, 'some user')

    # do something with your plugin
    print 'Testing', myplugin.name
    myplugin.music_plugin_play()

    time.sleep(5)

    # create a plugin by normal instantiation
    from soco.plugins.example import ExamplePlugin

    # create a new plugin, pass the soco instance to it
    myplugin = ExamplePlugin(soco, 'a user')

    print 'Testing', myplugin.name

    # do something with your plugin
    myplugin.music_plugin_stop()

if __name__ == '__main__':
    main()


text:
layout: docs
title: 'DBCoreTableSchema'
---

```ts
export interface DBCoreTableSchema {
  readonly name: string;
  readonly primaryKey: DBCoreIndex;
  readonly indexes: DBCoreIndex[];
  readonly getIndexByKeyPath: (keyPath: null | string | string[]) => DBCoreIndex | undefined;
}
```
Table schema structure in [DBCoreSchema](DBCoreSchema).

## See Also
* [DBCoreIndex](DBCoreIndex)


text:
using Esprima;
using Esprima.Ast;
using Jint.Native;
using Jint.Runtime;
using Jint.Runtime.Interop;
using Jint.Runtime.Modules;

namespace Jint;

public sealed class ModuleBuilder
{
    private readonly Engine _engine;
    private readonly string _specifier;
    private Module? _module;
    private readonly List<string> _sourceRaw = new();
    private readonly Dictionary<string, JsValue> _exports = new();
    private readonly ParserOptions _options;

    internal ModuleBuilder(Engine engine, string specifier)
    {
        _engine = engine;
        _specifier = specifier;
        _options = new ParserOptions();
    }

    public ModuleBuilder AddSource(string code)
    {
        if (_module != null)
        {
            throw new InvalidOperationException("Cannot have both source text and pre-compiled.");
        }
        _sourceRaw.Add(code);
        return this;
    }

    public ModuleBuilder AddModule(Module module)
    {
        if (_sourceRaw.Count > 0)
        {
            throw new InvalidOperationException("Cannot have both source text and pre-compiled.");
        }

        if (_module != null)
        {
            throw new InvalidOperationException("pre-compiled module already exists.");
        }
        _module = module;
        return this;
    }

    public ModuleBuilder ExportValue(string name, JsValue value)
    {
        _exports.Add(name, value);
        return this;
    }

    public ModuleBuilder ExportObject(string name, object value)
    {
        _exports.Add(name, JsValue.FromObject(_engine, value));
        return this;
    }

    public ModuleBuilder ExportType<T>()
    {
        ExportType<T>(typeof(T).Name);
        return this;
    }

    public ModuleBuilder ExportType<T>(string name)
    {
        _exports.Add(name, TypeReference.CreateTypeReference<T>(_engine));
        return this;
    }

    public ModuleBuilder ExportType(Type type)
    {
        ExportType(type.Name, type);
        return this;
    }

    public ModuleBuilder ExportType(string name, Type type)
    {
        _exports.Add(name, TypeReference.CreateTypeReference(_engine, type));
        return this;
    }

    public ModuleBuilder ExportFunction(string name, Func<JsValue[], JsValue> fn)
    {
        _exports.Add(name, new ClrFunctionInstance(_engine, name, (_, args) => fn(args)));
        return this;
    }

    public ModuleBuilder ExportFunction(string name, Func<JsValue> fn)
    {
        _exports.Add(name, new ClrFunctionInstance(_engine, name, (_, _) => fn()));
        return this;
    }

    public ModuleBuilder ExportFunction(string name, Action<JsValue[]> fn)
    {
        _exports.Add(name, new ClrFunctionInstance(_engine, name, (_, args) =>
        {
            fn(args);
            return JsValue.Undefined;
        }));
        return this;
    }

    public ModuleBuilder ExportFunction(string name, Action fn)
    {
        _exports.Add(name, new ClrFunctionInstance(_engine, name, (_, _) =>
        {
            fn();
            return JsValue.Undefined;
        }));
        return this;
    }

    public ModuleBuilder WithOptions(Action<ParserOptions> configure)
    {
        configure(_options);
        return this;
    }

    internal Module Parse()
    {
        if (_module != null) return _module;
        if (_sourceRaw.Count <= 0)
        {
            return new Module(NodeList.Create(Array.Empty<Statement>()));
        }

        var javaScriptParser = new JavaScriptParser(_options);
        try
        {
            var source = _sourceRaw.Count == 1 ? _sourceRaw[0] : string.Join(Environment.NewLine, _sourceRaw);
            return javaScriptParser.ParseModule(source, _specifier);
        }
        catch (ParserException ex)
        {
            ExceptionHelper.ThrowSyntaxError(_engine.Realm, $"Error while loading module: error in module '{_specifier}': {ex.Error}", Location.From(Position.From(ex.LineNumber, ex.Column), Position.From(ex.LineNumber, ex.Column), _specifier));
            return null!;
        }
    }

    internal void BindExportedValues(BuilderModuleRecord module)
    {
        foreach (var export in _exports)
        {
            module.BindExportedValue(export.Key, export.Value);
        }
    }
}


text:
package services;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.Transaction;
import controllers.LoginController;
import models.UpdateModel;
import play.data.Form;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created by a587853 on 06/04/2016.
 */
public class UpdateService {
        public static Boolean updateUser(Form<UpdateModel> userModelForm) {
        Transaction transaction = Ebean.beginTransaction();
        try {
        Connection connection = transaction.getConnection();
        PreparedStatement ps = connection.prepareStatement("UPDATE REGISTER_MODEL SET FIRSTNAME = ?, LASTNAME = ?, USERNAME = ?, PASSWORD = ? WHERE USERNAME = ? ");
        ps.setString(1, userModelForm.get().getFirstname());
        ps.setString(2, userModelForm.get().getLastname());
        ps.setString(3, userModelForm.get().getUsername());
        ps.setString(4, userModelForm.get().getPassword());
            ps.setString(5, LoginController.session("user"));
        ps.execute();
        transaction.addModification("REGISTER_MODEL",false,true,false);
        Ebean.commitTransaction();
                return true;
        } catch (SQLException e) {
        e.printStackTrace();

        } finally {
        Ebean.endTransaction();
        }
                return false;
        }

}


text:
package Q7_05_Online_Book_Reader;

public class Display {
	private Book activeBook;
	private User activeUser;
	private int pageNumber = 0;

	public void displayUser(User user) {
		activeUser = user;
		refreshUsername();
	}

	public void displayBook(Book book) {
		pageNumber = 0;
		activeBook = book;

		refreshTitle();
		refreshDetails();
		refreshPage();
	}

	public void refreshUsername() {
		/* updates username display */
	}

	public void refreshTitle() {
		/* updates title display */
	}

	public void refreshDetails() {
		/* updates details display */
	}

	public void refreshPage() {
		/* updated page display */
	}

	public void turnPageForward() {
		pageNumber++;
		refreshPage();
	}

	public void turnPageBackward() {
		pageNumber--;
		refreshPage();
	}
}


text:
package org.apache.cassandra.hadoop.cql3;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.TokenRange;
import com.google.common.collect.Maps;

import org.apache.cassandra.schema.SchemaConstants;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.cassandra.db.SystemKeyspace;
import org.apache.cassandra.dht.*;
import org.apache.cassandra.hadoop.*;
import org.apache.cassandra.utils.*;

import static java.util.stream.Collectors.toMap;

/**
 * Hadoop InputFormat allowing map/reduce against Cassandra rows within one ColumnFamily.
 *
 * At minimum, you need to set the KS and CF in your Hadoop job Configuration.
 * The ConfigHelper class is provided to make this
 * simple:
 *   ConfigHelper.setInputColumnFamily
 *
 * You can also configure the number of rows per InputSplit with
 *   1: ConfigHelper.setInputSplitSize. The default split size is 64k rows.
 *   or
 *   2: ConfigHelper.setInputSplitSizeInMb. InputSplit size in MB with new, more precise method
 *   If no value is provided for InputSplitSizeInMb, we default to using InputSplitSize.
 *
 *   CQLConfigHelper.setInputCQLPageRowSize. The default page row size is 1000. You
 *   should set it to "as big as possible, but no bigger." It set the LIMIT for the CQL
 *   query, so you need set it big enough to minimize the network overhead, and also
 *   not too big to avoid out of memory issue.
 *
 *   other native protocol connection parameters in CqlConfigHelper
 */
public class CqlInputFormat extends org.apache.hadoop.mapreduce.InputFormat<Long, Row> implements org.apache.hadoop.mapred.InputFormat<Long, Row>
{
    public static final String MAPRED_TASK_ID = "mapred.task.id";
    private static final Logger logger = LoggerFactory.getLogger(CqlInputFormat.class);
    private String keyspace;
    private String cfName;
    private IPartitioner partitioner;

    public RecordReader<Long, Row> getRecordReader(InputSplit split, JobConf jobConf, final Reporter reporter)
            throws IOException
    {
        TaskAttemptContext tac = HadoopCompat.newMapContext(
                jobConf,
                TaskAttemptID.forName(jobConf.get(MAPRED_TASK_ID)),
                null,
                null,
                null,
                new ReporterWrapper(reporter),
                null);

        CqlRecordReader recordReader = new CqlRecordReader();
        recordReader.initialize((org.apache.hadoop.mapreduce.InputSplit)split, tac);
        return recordReader;
    }

    @Override
    public org.apache.hadoop.mapreduce.RecordReader<Long, Row> createRecordReader(
            org.apache.hadoop.mapreduce.InputSplit arg0, TaskAttemptContext arg1) throws IOException,
            InterruptedException
    {
        return new CqlRecordReader();
    }

    protected void validateConfiguration(Configuration conf)
    {
        if (ConfigHelper.getInputKeyspace(conf) == null || ConfigHelper.getInputColumnFamily(conf) == null)
        {
            throw new UnsupportedOperationException("you must set the keyspace and table with setInputColumnFamily()");
        }
        if (ConfigHelper.getInputInitialAddress(conf) == null)
            throw new UnsupportedOperationException("You must set the initial output address to a Cassandra node with setInputInitialAddress");
        if (ConfigHelper.getInputPartitioner(conf) == null)
            throw new UnsupportedOperationException("You must set the Cassandra partitioner class with setInputPartitioner");
    }

    public List<org.apache.hadoop.mapreduce.InputSplit> getSplits(JobContext context) throws IOException
    {
        Configuration conf = HadoopCompat.getConfiguration(context);

        validateConfiguration(conf);

        keyspace = ConfigHelper.getInputKeyspace(conf);
        cfName = ConfigHelper.getInputColumnFamily(conf);
        partitioner = ConfigHelper.getInputPartitioner(conf);
        logger.trace("partitioner is {}", partitioner);

        // canonical ranges, split into pieces, fetching the splits in parallel
        ExecutorService executor = new ThreadPoolExecutor(0, 128, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
        List<org.apache.hadoop.mapreduce.InputSplit> splits = new ArrayList<>();

        try (Cluster cluster = CqlConfigHelper.getInputCluster(ConfigHelper.getInputInitialAddress(conf).split(","), conf);
             Session session = cluster.connect())
        {
            List<Future<List<org.apache.hadoop.mapreduce.InputSplit>>> splitfutures = new ArrayList<>();
            Pair<String, String> jobKeyRange = ConfigHelper.getInputKeyRange(conf);
            Range<Token> jobRange = null;
            if (jobKeyRange != null)
            {
                jobRange = new Range<>(partitioner.getTokenFactory().fromString(jobKeyRange.left),
                                       partitioner.getTokenFactory().fromString(jobKeyRange.right));
            }

            Metadata metadata = cluster.getMetadata();

            // canonical ranges and nodes holding replicas
            Map<TokenRange, Set<Host>> masterRangeNodes = getRangeMap(keyspace, metadata);

            for (TokenRange range : masterRangeNodes.keySet())
            {
                if (jobRange == null)
                {
                    // for each tokenRange, pick a live owner and ask it to compute bite-sized splits
                    splitfutures.add(executor.submit(new SplitCallable(range, masterRangeNodes.get(range), conf, session)));
                }
                else
                {
                    TokenRange jobTokenRange = rangeToTokenRange(metadata, jobRange);
                    if (range.intersects(jobTokenRange))
                    {
                        for (TokenRange intersection: range.intersectWith(jobTokenRange))
                        {
                            // for each tokenRange, pick a live owner and ask it to compute bite-sized splits
                            splitfutures.add(executor.submit(new SplitCallable(intersection,  masterRangeNodes.get(range), conf, session)));
                        }
                    }
                }
            }

            // wait until we have all the results back
            for (Future<List<org.apache.hadoop.mapreduce.InputSplit>> futureInputSplits : splitfutures)
            {
                try
                {
                    splits.addAll(futureInputSplits.get());
                }
                catch (Exception e)
                {
                    throw new IOException("Could not get input splits", e);
                }
            }
        }
        finally
        {
            executor.shutdownNow();
        }

        assert splits.size() > 0;
        Collections.shuffle(splits, new Random(System.nanoTime()));
        return splits;
    }

    private TokenRange rangeToTokenRange(Metadata metadata, Range<Token> range)
    {
        return metadata.newTokenRange(metadata.newToken(partitioner.getTokenFactory().toString(range.left)),
                metadata.newToken(partitioner.getTokenFactory().toString(range.right)));
    }

    private Map<TokenRange, Long> getSubSplits(String keyspace, String cfName, TokenRange range, Configuration conf, Session session)
    {
        int splitSize = ConfigHelper.getInputSplitSize(conf);
        int splitSizeMb = ConfigHelper.getInputSplitSizeInMb(conf);
        try
        {
            return describeSplits(keyspace, cfName, range, splitSize, splitSizeMb, session);
        }
        catch (Exception e)
        {
            throw new RuntimeException(e);
        }
    }

    private Map<TokenRange, Set<Host>> getRangeMap(String keyspace, Metadata metadata)
    {
        return metadata.getTokenRanges()
                       .stream()
                       .collect(toMap(p -> p, p -> metadata.getReplicas('"' + keyspace + '"', p)));
    }

    private Map<TokenRange, Long> describeSplits(String keyspace, String table, TokenRange tokenRange, int splitSize, int splitSizeMb, Session session)
    {
        String query = String.format("SELECT mean_partition_size, partitions_count " +
                                     "FROM %s.%s " +
                                     "WHERE keyspace_name = ? AND table_name = ? AND range_start = ? AND range_end = ?",
                                     SchemaConstants.SYSTEM_KEYSPACE_NAME,
                                     SystemKeyspace.SIZE_ESTIMATES);

        ResultSet resultSet = session.execute(query, keyspace, table, tokenRange.getStart().toString(), tokenRange.getEnd().toString());

        Row row = resultSet.one();

        long meanPartitionSize = 0;
        long partitionCount = 0;
        int splitCount = 0;

        if (row != null)
        {
            meanPartitionSize = row.getLong("mean_partition_size");
            partitionCount = row.getLong("partitions_count");

            splitCount = splitSizeMb > 0
                ? (int)(meanPartitionSize * partitionCount / splitSizeMb / 1024 / 1024)
                : (int)(partitionCount / splitSize);
        }

        // If we have no data on this split or the size estimate is 0,
        // return the full split i.e., do not sub-split
        // Assume smallest granularity of partition count available from CASSANDRA-7688
        if (splitCount == 0)
        {
            Map<TokenRange, Long> wrappedTokenRange = new HashMap<>();
            wrappedTokenRange.put(tokenRange, (long) 128);
            return wrappedTokenRange;
        }

        List<TokenRange> splitRanges = tokenRange.splitEvenly(splitCount);
        Map<TokenRange, Long> rangesWithLength = Maps.newHashMapWithExpectedSize(splitRanges.size());
        for (TokenRange range : splitRanges)
            rangesWithLength.put(range, partitionCount/splitCount);

        return rangesWithLength;
    }

    // Old Hadoop API
    public InputSplit[] getSplits(JobConf jobConf, int numSplits) throws IOException
    {
        TaskAttemptContext tac = HadoopCompat.newTaskAttemptContext(jobConf, new TaskAttemptID());
        List<org.apache.hadoop.mapreduce.InputSplit> newInputSplits = this.getSplits(tac);
        InputSplit[] oldInputSplits = new InputSplit[newInputSplits.size()];
        for (int i = 0; i < newInputSplits.size(); i++)
            oldInputSplits[i] = (ColumnFamilySplit)newInputSplits.get(i);
        return oldInputSplits;
    }

    /**
     * Gets a token tokenRange and splits it up according to the suggested
     * size into input splits that Hadoop can use.
     */
    class SplitCallable implements Callable<List<org.apache.hadoop.mapreduce.InputSplit>>
    {

        private final TokenRange tokenRange;
        private final Set<Host> hosts;
        private final Configuration conf;
        private final Session session;

        public SplitCallable(TokenRange tr, Set<Host> hosts, Configuration conf, Session session)
        {
            this.tokenRange = tr;
            this.hosts = hosts;
            this.conf = conf;
            this.session = session;
        }

        public List<org.apache.hadoop.mapreduce.InputSplit> call() throws Exception
        {
            ArrayList<org.apache.hadoop.mapreduce.InputSplit> splits = new ArrayList<>();
            Map<TokenRange, Long> subSplits;
            subSplits = getSubSplits(keyspace, cfName, tokenRange, conf, session);
            // turn the sub-ranges into InputSplits
            String[] endpoints = new String[hosts.size()];

            // hadoop needs hostname, not ip
            int endpointIndex = 0;
            for (Host endpoint : hosts)
                endpoints[endpointIndex++] = endpoint.getAddress().getHostName();

            boolean partitionerIsOpp = partitioner instanceof OrderPreservingPartitioner || partitioner instanceof ByteOrderedPartitioner;

            for (Map.Entry<TokenRange, Long> subSplitEntry : subSplits.entrySet())
            {
                List<TokenRange> ranges = subSplitEntry.getKey().unwrap();
                for (TokenRange subrange : ranges)
                {
                    ColumnFamilySplit split =
                            new ColumnFamilySplit(
                                    partitionerIsOpp ?
                                            subrange.getStart().toString().substring(2) : subrange.getStart().toString(),
                                    partitionerIsOpp ?
                                            subrange.getEnd().toString().substring(2) : subrange.getEnd().toString(),
                                    subSplitEntry.getValue(),
                                    endpoints);

                    logger.trace("adding {}", split);
                    splits.add(split);
                }
            }
            return splits;
        }
    }
}


text:
package org.apache.wicket.util.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URI;

import org.apache.wicket.util.io.Streams;
import org.apache.wicket.util.time.Time;
import org.apache.wicket.util.watch.IModifiable;

/**
 * Simple extension of File that adds an implementation of IModifiable for files. This allows the
 * ModificationWatcher class to watch files for modification. The IModifiable.lastModifiedTime()
 * method also returns a Time object with a more convenient API than either Date or a value in
 * milliseconds.
 *
 * @author Jonathan Locke
 */
public class File extends java.io.File implements IModifiable
{
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor.
	 *
	 * @param parent
	 *            parent
	 * @param child
	 *            child
	 */
	public File(final File parent, final String child)
	{
		super(parent, child);
	}

	/**
	 * Construct.
	 *
	 * @param parent
	 *            parent
	 * @param child
	 *            child
	 */
	public File(final java.io.File parent, final String child)
	{
		super(parent, child);
	}

	/**
	 * Construct.
	 *
	 * @param file
	 *            File from java.io package
	 */
	public File(final java.io.File file)
	{
		super(file.getAbsolutePath());
	}

	/**
	 * Constructor.
	 *
	 * @param pathname
	 *            path name
	 */
	public File(final String pathname)
	{
		super(pathname);
	}

	/**
	 * Constructor.
	 *
	 * @param parent
	 *            parent
	 * @param child
	 *            child
	 */
	public File(final String parent, final String child)
	{
		super(parent, child);
	}

	/**
	 * Constructor.
	 *
	 * @param uri
	 *            file uri
	 */
	public File(final URI uri)
	{
		super(uri);
	}

	/**
	 * @param name
	 *            Name of child file
	 * @return Child file object
	 */
	public File file(final String name)
	{
		return new File(this, name);
	}

	/**
	 * @return File extension (whatever is after the last '.' in the file name)
	 */
	public String getExtension()
	{
		final int lastDot = getName().lastIndexOf('.');
		if (lastDot >= 0)
		{
			return getName().substring(lastDot + 1);
		}
		return null;
	}

	/**
	 * @return Parent folder
	 */
	public Folder getParentFolder()
	{
		return new Folder(getParent());
	}

	/**
	 * @return Input stream that reads this file
	 * @throws FileNotFoundException
	 *             Thrown if the file cannot be found
	 */
	public InputStream inputStream() throws FileNotFoundException
	{
		return new BufferedInputStream(new FileInputStream(this));
	}

	/**
	 * Returns a Time object representing the most recent time this file was modified.
	 *
	 * @return This file's lastModified() value as a Time object or null if
	 * that information is not available
	 */
	public Time lastModifiedTime()
	{
		final long time = lastModified();

		if(time == 0)
		{
			return null;
		}
		return Time.millis(time);
	}

	/**
	 * Creates a buffered output stream that writes to this file. If the parent folder does not yet
	 * exist, creates all necessary folders in the path.
	 *
	 * @return Output stream that writes to this file
	 * @throws FileNotFoundException
	 *             Thrown if the file cannot be found
	 */
	public OutputStream outputStream() throws FileNotFoundException
	{
		final Folder parent = getParentFolder();
		if (!parent.exists())
		{
			if (!parent.mkdirs())
			{
				throw new FileNotFoundException("Couldn't create path " + parent);
			}
		}
		return new BufferedOutputStream(new FileOutputStream(this));
	}

	/**
	 * @return String read from this file
	 * @throws IOException
	 */
	public String readString() throws IOException
	{
		final InputStream in = new FileInputStream(this);
		try
		{
			return Streams.readString(in);
		}
		finally
		{
			in.close();
		}
	}

	/**
	 * @return Object read from serialization file
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public Object readObject() throws IOException, ClassNotFoundException
	{
		return new ObjectInputStream(inputStream()).readObject();
	}

	/**
	 * @param object
	 *            Object to write to this file
	 * @throws IOException
	 */
	public void writeObject(final Serializable object) throws IOException
	{
		new ObjectOutputStream(outputStream()).writeObject(object);
	}

	/**
	 * @return True if the file was removed
	 * @see java.io.File#delete()
	 */
	public boolean remove()
	{
		return Files.remove(this);
	}

	/**
	 * Force contents of file to physical storage
	 *
	 * @throws IOException
	 */
	public void sync() throws IOException
	{
		final FileInputStream in = new FileInputStream(this);
		try
		{
			in.getFD().sync();
		}
		finally
		{
			in.close();
		}
	}

	/**
	 * @return This file in double quotes (useful for passing to commands and tools that have issues
	 *         with spaces in filenames)
	 */
	public String toQuotedString()
	{
		return "\"" + toString() + "\"";
	}

	/**
	 * Writes the given file to this one
	 *
	 * @param file
	 *            The file to copy
	 * @return number of bytes written
	 * @throws IOException
	 */
	public int write(final File file) throws IOException
	{
		final InputStream in = new BufferedInputStream(new FileInputStream(file));
		try
		{
			return write(in);
		}
		finally
		{
			in.close();
		}
	}

	/**
	 * Writes the given input stream to this file
	 *
	 * @param input
	 *            The input
	 * @return Number of bytes written
	 * @throws IOException
	 */
	public int write(final InputStream input) throws IOException
	{
		return Files.writeTo(this, input);
	}

	/**
	 * Write the given string to this file
	 *
	 * @param string
	 *            The string to write
	 * @throws IOException
	 */
	public void write(final String string) throws IOException
	{
		final FileWriter out = new FileWriter(this);
		try
		{
			out.write(string);
		}
		finally
		{
			out.close();
		}
	}
}


text:
package com.example.knitknit;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

public class CounterEdit extends Activity {
	private static final String TAG = "bunny-knitknit-CounterEdit";
	private Counter mCounter;
	private Resources mResources;

	// UI Elements
	private EditText mNameText;
	private RadioButton mUpdownUp;
	private RadioButton mUpdownDown;
	private CheckBox mPatternCheckBox;
	private EditText mPatternNumber;
	private TextView mPatternEndText;

	/* Activity Lifecycle ************************************************/
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.counteredit);

		mCounter = CountingLand.mSelectedCounter;

		Log.w(TAG, "in onCreate, mCounter: " + mCounter);

		// If counter ID is still null, there is a problem and we need
		// to get out of here since we can't do anything
		if (mCounter == null) {
			finish();
		}

		mResources = getResources();

		setupUI();
	}

	@Override
	protected void onPause() {
		Log.w(TAG, "in onPause");
		super.onPause();
		saveState();
	}

	private void saveState() {
		mCounter.setPatternLength(
			Integer.parseInt(mPatternNumber.getText().toString()));

		mCounter.setName(mNameText.getText().toString());
	}

	private void setupUI() {
		// Find counter name box
		mNameText = (EditText)
			findViewById(R.id.counteredit_name_text);

		Log.w(TAG, "mNameText: " + mNameText);

		// Fill name box with counter's name
		mNameText.append(mCounter.getName());

		// Create an OnClickListener for the updown radio buttons
		OnClickListener updown_listener = new OnClickListener() {
		    public void onClick(View v) {
			Log.w(TAG, "clicked radiobutton");

			RadioButton rb = (RadioButton) v;
			if (rb.getId() == R.id.counteredit_updown_up) {
				Log.w(TAG, "clicked UP");
				mCounter.setCountUp(true);
			} else {
				Log.w(TAG, "clicked DOWN");
				mCounter.setCountUp(false);
			}
		    }
		};

		// Find updown RadioButtons
		mUpdownUp = (RadioButton)
			findViewById(R.id.counteredit_updown_up);
		mUpdownDown = (RadioButton)
			findViewById(R.id.counteredit_updown_down);

		// Attach OnClickListeners
		mUpdownUp.setOnClickListener(updown_listener);
		mUpdownDown.setOnClickListener(updown_listener);

		// Select the correct radiobutton based on the current setting
		if (mCounter.getCountUp()) {
			mUpdownUp.setChecked(true);
		} else {
			mUpdownDown.setChecked(true);
		}

		// Find pattern checkbox
		mPatternCheckBox = (CheckBox)
			findViewById(R.id.counteredit_pattern_checkbox);

		// Check/uncheck the checkbox based on the current setting
		mPatternCheckBox.setChecked(mCounter.getPatternOn());

		// Callback function for when the checkbox changes
		mPatternCheckBox.setOnCheckedChangeListener(
			new CheckBox.OnCheckedChangeListener() {
				@Override
				public void onCheckedChanged(
					CompoundButton v, boolean checked)
				{
					Log.w(TAG, "checkbox changed");

					// Make text normal/dim
					refreshPattern();

					// Enable/disable pattern mode
					mCounter.setPatternOn(checked);
				}
			});

		// Find pattern length number
		mPatternNumber = (EditText)
			findViewById(R.id.counteredit_pattern_number);

		// Set the number based on the current setting
		mPatternNumber.append(
			Integer.toString(mCounter.getPatternLength()));

		// Find end of pattern text (" rows")
		mPatternEndText = (TextView)
			findViewById(R.id.counteredit_pattern_endtext);

		refreshPattern();
	}

	private void refreshPattern() {
		// Set color to normal or dim depending on the toggle state
		int color = mResources.getColor(
			mPatternCheckBox.isChecked() ?
			R.color.counteredit_text :
			R.color.counteredit_disabled);

		// Set color of checkbox text
		mPatternCheckBox.setTextColor(color);

		// Enable/disable pattern number EditText
		mPatternNumber.setEnabled(mPatternCheckBox.isChecked());

		// Set color of end text
		mPatternEndText.setTextColor(color);
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Sydowia 35: 139 (1982)

#### Original name
Teratosphaeria dispersa E. Müll. & Oehrens

### Remarks
null


text:
package com.yiwen.weshop;

/**
 * Created by zsh06
 * Created on 2016/10/13 17:19.
 */

public class Contants {

    public static final String USER_JSON = "user_json";
    public static final String TOKEN = "token";

    public static final String DES_KEY = "Cniao5_123456";

    public static final int REQUEST_CODE = 0;

    public static class API {
        public static final String CAMPAIGN_ID = "campaign_id";
        public static final String WARE_ITEM = "ware_item";

        public static final String BASE_URL = "http://112.124.22.238:8081/course_api/";
        public static final String CAMPAIGN_HOME = BASE_URL + "campaign/recommend";
        public static final String BANNER_HOME = BASE_URL + "banner/query?type=1";
        //      需要参数curPage和pageSize
        public static final String HOT_WARES = BASE_URL + "wares/hot";
        public static final String CATEGORY_LIST = BASE_URL + "category/list";
        public static final String WARES_LIST = BASE_URL + "wares/list";
        public static final String WARE_CAMPAIN_LIST = BASE_URL + "wares/campaign/list";
        public static final String WARE_DETAIL = BASE_URL + "wares/detail.html";
        public static final String LOGIN = BASE_URL + "auth/login";
        public static final String USER_DETAIL = BASE_URL + "user/get?id=1";
        public static final String REGISTER = BASE_URL + "auth/reg";
        public static final String CREATE_ORDER = BASE_URL + "order/create";
        public static final String CHANGE_ORDER = BASE_URL + "order/complete";
        public static final String ADDRESS_LIST = BASE_URL + "addr/list";
        public static final String ADDRESS_UPDATE = BASE_URL + "addr/update";
        public static final String ADDRESS_DELETE = BASE_URL + "addr/del";
        public static final String ADDRESS_CREATE = BASE_URL + "addr/create";

        public static final String ORDER_CREATE=BASE_URL +"/order/create";
        public static final String ORDER_COMPLEPE=BASE_URL +"/order/complete";
        public static final String ORDER_LIST=BASE_URL +"order/list";

        public static final String FAVORITE_LIST=BASE_URL +"favorite/list";
        public static final String FAVORITE_CREATE=BASE_URL +"favorite/create";
        public static final String FAVORITE_DELETE=BASE_URL +"favorite/del";
    }
}


text:
package jsondb

import (
	"code.google.com/p/vitess/go/vt/sqlparser"
//	"io/ioutil"
//	"os"
	"strconv"
	"strings"
	"github.com/artpar/gabs"
	"github.com/op/go-logging"
//	"flag"
//	"github.com/pquerna/ffjson/ffjson"
)

var log = logging.MustGetLogger("example")

// Example format string. Everything except the message has a custom color
// which is dependent on the log level. Many fields have a custom output
// formatting too, eg. the time returns the hour down to the milli second.
var format = logging.MustStringFormatter(
	"%{time:15:04:05.000} ▶ %{level:.4s} %{id:03x}  %{message}",
)

//func main() {
//	logging.SetLevel(logging.DEBUG, "")
//	var sqlString, sqlFile, dataFile string
//	flag.StringVar(&sqlString, "sql", "", "-sql='select t.txn_id from D.data t'")
//	flag.StringVar(&sqlFile, "sqlfile", "", "-sqlfile=1.sql")
//	flag.StringVar(&dataFile, "data", "", "-data='data.json'")
//	flag.Parse()
//
//	var data []byte
//	var err error
//
//
//	if (len(sqlString) < 1) && len(sqlFile) < 1 {
//		log.Debug("Please specify an sql for a file containing a sql")
//		flag.Usage()
//		os.Exit(1)
//	}
//	if len(sqlString) < 1 {
//		sqlStringByte, err := ioutil.ReadFile(sqlFile)
//		if err != nil {
//			panic(err)
//		}
//		sqlString = string(sqlStringByte)
//	}
//	sql, err := sqlparser.Parse(string(sqlString))
//	if err != nil {
//		panic(err)
//	}
//
//	if len(dataFile) > 0 {
//		data, err = ioutil.ReadFile(dataFile)
//		if err != nil {
//			panic(err)
//		}
//	} else {
//		data, _ = ioutil.ReadAll(os.Stdin)
//	}
//
//	TravelNode(sql)
//	executionModel := TravelNodeRecurse(sql)
//	PrintExecutionModel(executionModel)
//	extractedData := Execute(executionModel, data)
//	log.Debug("Data - %#v", extractedData)
//	result, err := ffjson.Marshal(extractedData)
//	//	jsonOut, err := gabs.Consume(extractedData)
//	if err != nil {
//		log.Debug("Error while making json - %s", err)
//	}
//	//	result := jsonOut.StringIndent("    ", "  ")
//	log.Debug("Final - %#v", string(result))
//	os.Stdout.WriteString(string(result))
//	os.Stdout.Close()
//}

func PrintExecutionModel(executionModel ExecutionModel) {
	for _, t := range executionModel.Columns {
		log.Debug("Column  - %s", t.Node)
	}
	for _, t := range executionModel.FromTable {
		log.Debug("Table - %s", t.Node)
	}
}

func temp(data []byte) {
	_, e := gabs.ParseJSON(data)
	if e != nil {
		panic(e)
	}
}

func TravelNode(n *sqlparser.Node) {
	PrintNodeRecurse(n, 0)
}

const ROOTNAME = "d"
const (
	COLUMN = iota
	TABLE
)

func TravelNodeRecurse(n *sqlparser.Node) (ExecutionModel) {
	execution := ExecutionModel{IsDistinct: false, State: COLUMN, Columns: make([]ColumnExpression, 0), FromTable: make([]FromExpression, 0)}
	for _, node := range n.Sub {
		switch node.Type {
		case sqlparser.COMMENT_LIST:
		case sqlparser.NO_DISTINCT:
		case sqlparser.DISTINCT:
			execution.IsDistinct = true
		case sqlparser.NODE_LIST:
			switch execution.State {
			case COLUMN:
				for _, columnNode := range node.Sub {
					log.Debug("Add Column - %s\n", columnNode.Value)
					execution.Columns = append(execution.Columns, ColumnExpression{*columnNode})
				}
				execution.State = TABLE
			case TABLE:
				for _, fromNode := range node.Sub {
					log.Debug("Add from table - %s\n", fromNode.Value)
					execution.FromTable = append(execution.FromTable, FromExpression{*fromNode})
				}
			}
		}
	}
	return execution
}

func PrintNodeRecurse(n *sqlparser.Node, i int) {
	log.Debug(strings.Repeat("\t", i), strconv.Itoa(n.Type)+" - "+string(n.Value))
	for _, node := range n.Sub {
		PrintNodeRecurse(node, i+1)
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Angular-Validation Example with Interpolation</title>
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
        <link rel="stylesheet" href="../../style.css">

Example of Angular-Validation Date validation error after select from ui datepicker.

        Min Date: {{vm.minDate | date:'dd/MM/yyyy'}} |
        Max Date {{vm.maxDate | date:'dd/MM/yyyy'}}

      <form name="vm.test">
        Date

          <input
            type="text"
            id="dateOfChange"
            name="dateOfChange"
            class="form-control"
            validation="required|date_euro_long_between:{{vm.minDate | date:'dd/MM/yyyy'}},{{vm.maxDate | date:'dd/MM/yyyy'}}"
            validation-error-to="dateOfChangeValidation"
            ng-model="vm.model.dateOfChange"
            datepicker-popup="{{vm.datePickerFormat}}"
            datepicker-options="vm.dateOptions"
            datepicker-mode="'day'"
            is-open="vm.isChangeDatePickerOpen"
            min-date="vm.minDate"
            max-date="vm.maxDate"
            />

              <button type="button" class="btn btn-default"
                      data-ng-click="vm.openDatePicker($event)">

              </button>

      </form>

        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>

ERRORS!

{{ item.field }}: {{item.message}}

      <ng-view></ng-view>


text:
<!doctype html>

		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="description" content="A front-end template that helps you build fast, modern mobile web apps.">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
		<title>Marketing Kit | Painel</title>

		<meta name="mobile-web-app-capable" content="yes">
		<link rel="icon" sizes="192x192" href="images/android-desktop.png">

		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<meta name="apple-mobile-web-app-title" content="Material Design Lite">
		<link rel="apple-touch-icon-precomposed" href="images/ios-desktop.png">

		<meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144-precomposed.png">
		<meta name="msapplication-TileColor" content="#3372DF">

		<link rel="shortcut icon" href="images/favicon.png">

		<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
		<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
		<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.deep_orange-red.min.css">
		<link rel="stylesheet" href="css/styles.css">

							search

							<input class="mdl-textfield__input" type="text" id="search">
							Insira uma palavra...

					<button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon">
						notifications_active
					</button>
					<button class="mdl-button mdl-js-button mdl-js-ripple-effect mdl-button--icon" id="hdrbtn">
						settings
					</button>

Sobre

Contato

Informações Legais

					Fernando

					Hoje é Sexta, 04/04/2017

				dashboardPainel
				createNovo Projeto
				workTrabalhos
				historyHistórico
				photo_libraryPortifolio
				schoolCertificados
				peopleCMS

				help_outlineAjuda

4
Projetos em Progresso

											Nome
											Id
											Valor

											Logo da Gama
											254
											R$290.0

											Banner da Gama
											501
											R$125.0

											Site da Gama
											109
											R$2350.0

								<button class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
									more_vert
								</button>

1
Projetos em Avaliação

											Nome
											Id
											Valor

											App Gama
											237
											R$29000.0

								<button class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
									more_vert
								</button>

1
Projetos a expirar

											Nome
											Id
											Valor

											Assigment 5 Gama
											829
											R$305.0

								<button class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
									more_vert
								</button>

								timelapse Percentagem projetos concluidos

								<svg fill="currentColor" width="200px" height="200px" viewBox="0 0 1 1" class="demo-chart mdl-cell mdl-cell--4-col mdl-cell--3-col-desktop" style="width: auto;padding-left: 20%;">
				              		<use xlink:href="#piechart" mask="url(#piemask)"></use>
				              		<text x="0.5" y="0.5" font-family="Roboto" font-size="0.3" fill="#888" text-anchor="middle" dy="0.1">82<tspan font-size="0.2" dy="-0.07">%</tspan></text>
					            </svg>

								<button class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
									more_vert
								</button>

								attach_money Valor médio dos projetos

									R$440.19

									R$83.31 arrow_drop_up

									desde o último mês

								<button class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
									more_vert
								</button>

								account_balance_wallet Previsto a receber no mês

									R$1.120,19

								<button class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
									more_vert
								</button>

								message Últimas mensagens

									  person
									  Bryan Cranston

										Bryan Cranston played the role of Walter in Breaking Bad. He is also known
										for playing Hal in Malcom in the Middle.

									  star

									  person
									  Aaron Paul

										Aaron Paul played the role of Jesse in Breaking Bad. He also featured in
										the "Need For Speed" Movie.

									  star

									  person
									  Bob Odenkirk

										Bob Odinkrik played the role of Saul in Breaking Bad. Due to public fondness for the
										character, Bob stars in his own show now, called "Better Call Saul".

									  star

								<button class="mdl-button mdl-button--icon mdl-js-button mdl-js-ripple-effect">
									more_vert
								</button>

	<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" style="position: fixed; left: -1000px; height: -1000px;">
        <defs>
          <mask id="piemask" maskContentUnits="objectBoundingBox">
            <circle cx="0.5" cy="0.5" r="0.49" fill="white"></circle>
            <circle cx="0.5" cy="0.5" r="0.40" fill="black"></circle>
          </mask>
          <g id="piechart">
            <circle cx="0.5" cy="0.5" r="0.5"></circle>
            <path d="M 0.5 0.5 0.5 0 A 0.5 0.5 0 0 1 0.95 0.28 z" stroke="none" fill="rgba(255, 255, 255, 0.75)"></path>
          </g>
        </defs>
      </svg>

	  <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 500 250" style="position: fixed; left: -1000px; height: -1000px;">
        <defs>
          <g id="chart">
            <g id="Gridlines">
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="27.3" x2="468.3" y2="27.3"></line>
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="66.7" x2="468.3" y2="66.7"></line>
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="105.3" x2="468.3" y2="105.3"></line>
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="144.7" x2="468.3" y2="144.7"></line>
              <line fill="#888888" stroke="#888888" stroke-miterlimit="10" x1="0" y1="184.3" x2="468.3" y2="184.3"></line>
            </g>
            <g id="Numbers">
              <text transform="matrix(1 0 0 1 485 29.3333)" fill="#888888" font-family="'Roboto'" font-size="9">500</text>
              <text transform="matrix(1 0 0 1 485 69)" fill="#888888" font-family="'Roboto'" font-size="9">400</text>
              <text transform="matrix(1 0 0 1 485 109.3333)" fill="#888888" font-family="'Roboto'" font-size="9">300</text>
              <text transform="matrix(1 0 0 1 485 149)" fill="#888888" font-family="'Roboto'" font-size="9">200</text>
              <text transform="matrix(1 0 0 1 485 188.3333)" fill="#888888" font-family="'Roboto'" font-size="9">100</text>
              <text transform="matrix(1 0 0 1 0 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">1</text>
              <text transform="matrix(1 0 0 1 78 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">2</text>
              <text transform="matrix(1 0 0 1 154.6667 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">3</text>
              <text transform="matrix(1 0 0 1 232.1667 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">4</text>
              <text transform="matrix(1 0 0 1 309 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">5</text>
              <text transform="matrix(1 0 0 1 386.6667 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">6</text>
              <text transform="matrix(1 0 0 1 464.3333 249.0003)" fill="#888888" font-family="'Roboto'" font-size="9">7</text>
            </g>
            <g id="Layer_5">
              <polygon opacity="0.36" stroke-miterlimit="10" points="0,223.3 48,138.5 154.7,169 211,88.5
              294.5,80.5 380,165.2 437,75.5 469.5,223.3 	"></polygon>
            </g>
            <g id="Layer_4">
              <polygon stroke-miterlimit="10" points="469.3,222.7 1,222.7 48.7,166.7 155.7,188.3 212,132.7
              296.7,128 380.7,184.3 436.7,125 	"></polygon>
            </g>
          </g>
        </defs>
      </svg>


text:
<?php

namespace abexto\yepa\core\helpers;

/**
 * Static utility class to maniuplate Yii rules
 *
 * @author Andreas Prucha, Abexto - Helicon Software Development
 */
class Rules
{
    /**
     * Removes specific rules from a rule definition array
     *
     * The filter is specified as associative array of attributes => validators in the $excludeRules
     * parameter. The value can be '*' in order to remove all rules for the attribute or a single or
     * an array of validator names.
     *
     * @param array $rules          Current rule definition array
     * @param array $excludeRules   Filter
     */
    public static function filter(array $rules = [], array $excludeRules = [])
    {
        if (empty($excludeRules)) {
            return $rules; // Nothing to remove ==> RETURN original
        }

        //
        // Filter the rules
        $result = $rules;
        foreach ($result as $rk => &$rd) {
            $rd[0] = (array)$rd[0];
                foreach ($rd[0] as $fk => $fv) {
                    if (array_key_exists($fv, $excludeRules)) {
                        if (in_array('*', (array)$excludeRules[$fv]) ||
                                in_array($rd[1], (array)$excludeRules[$fv])) {
                                unset($rd[0][$fk]);
                        }
                    }
                }
                if (empty($rd[0])) {
                    unset($result[$rk]);
                }
        }
        return $result;
    }

}