text:
package org.onepf.opfpush.configuration;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import org.onepf.opfpush.listener.CheckManifestHandler;
import org.onepf.opfpush.listener.EventListener;
import org.onepf.opfpush.pushprovider.PushProvider;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * The instance of this class is used as an argument of the {@link org.onepf.opfpush.OPFPush#init(android.content.Context, Configuration)}
 * method for configuring the {@link org.onepf.opfpush.OPFPushHelper} instance.
 *
 * @author Kirill Rozov
 * @author Roman Savin
 * @since 04.09.2014
 */
@SuppressWarnings("PMD.MissingStaticMethodInNonInstantiatableClass")
public final class Configuration {

    @NonNull
    private final List<PushProvider> providers;

    @Nullable
    private final EventListener eventListener;

    @Nullable
    private final CheckManifestHandler checkManifestHandler;

    private final boolean isSelectSystemPreferred;

    private Configuration(@NonNull final Collection<? extends PushProvider> providers,
                          @Nullable final EventListener eventListener,
                          final boolean selectSystemPreferred,
                          @Nullable CheckManifestHandler checkManifestHandler) {
        this.providers = Collections.unmodifiableList(new ArrayList<>(providers));
        this.eventListener = eventListener;
        this.isSelectSystemPreferred = selectSystemPreferred;
        this.checkManifestHandler = checkManifestHandler;
    }

    /**
     * Returns all available push providers.
     *
     * @return All available push providers.
     */
    @NonNull
    public List<PushProvider> getProviders() {
        return providers;
    }

    /**
     * Returns the instance of the {@link org.onepf.opfpush.listener.EventListener}.
     *
     * @return The instance of the {@link org.onepf.opfpush.listener.EventListener}.
     */
    @Nullable
    public EventListener getEventListener() {
        return eventListener;
    }

    /**
     * Returns {@code true} if the system push provider is preferred, false otherwise.
     *
     * @return {@code true} if the system push provider is preferred, false otherwise.
     */
    public boolean isSelectSystemPreferred() {
        return isSelectSystemPreferred;
    }

    /**
     * Returns the instance of the {@link CheckManifestHandler}.
     *
     * @return The instance of the {@link CheckManifestHandler}.
     */
    @Nullable
    public CheckManifestHandler getCheckManifestHandler() {
        return checkManifestHandler;
    }

    @Override
    public String toString() {
        return "Configuration {"
                + "providers = " + providers
                + ", isSelectSystemPreferred = " + isSelectSystemPreferred
                + '}';
    }

    /**
     * The builder class that creates an instance of the {@code Configuration} class.
     */
    public static final class Builder {

        @Nullable
        private Map<String, PushProvider> providersMap;

        @Nullable
        private EventListener eventListener;

        private boolean isSelectSystemPreferred;

        @Nullable
        private CheckManifestHandler checkManifestHandler;

        /**
         * See {@link #addProviders(java.util.List)}
         *
         * @return The current {@code Builder} instance.
         * @throws java.lang.IllegalArgumentException If a provider was already added
         */
        @NonNull
        public Builder addProviders(@NonNull final PushProvider... providers) {
            if (providers.length == 0) {
                return this;
            } else {
                return addProviders(Arrays.asList(providers));
            }
        }

        /**
         * Add push providers to the configuration. The priority of the providers corresponds to the order
         * in which they were added.
         *
         * @return The current {@code Builder} instance.
         * @throws java.lang.IllegalArgumentException If a provider was already added.
         */
        @NonNull
        public Builder addProviders(@NonNull final List<? extends PushProvider> providers) {
            if (providers.isEmpty()) {
                return this;
            }

            if (this.providersMap == null) {
                this.providersMap = new LinkedHashMap<>();
            }

            for (PushProvider provider : providers) {
                final String providerName = provider.getName();
                if (this.providersMap.containsKey(providerName)) {
                    throw new IllegalArgumentException(
                            String.format("Provider '%s' already added.", provider)
                    );
                } else {
                    this.providersMap.put(providerName, provider);
                }
            }
            return this;
        }

        @NonNull
        public Builder setEventListener(@NonNull final EventListener eventListener) {
            this.eventListener = eventListener;
            return this;
        }

        /**
         * If you set {@code true}, the system push provider will get the highest priority.
         * For Google devices this is Google Cloud Messaging, for Kindle devices - ADM.
         * False by default.
         *
         * @param isSelectSystemPreferred {@code true} if the system provider is preferred, {@code false} otherwise.
         * @return The current {@code Builder}.
         */
        public Builder setSelectSystemPreferred(final boolean isSelectSystemPreferred) {
            this.isSelectSystemPreferred = isSelectSystemPreferred;
            return this;
        }

        @NonNull
        public Builder setCheckManifestHandler(@NonNull final CheckManifestHandler checkManifestHandler) {
            this.checkManifestHandler = checkManifestHandler;
            return this;
        }

        /**
         * Create the instance of the {@link Configuration} class.
         *
         * @return The new {@link Configuration} object.
         * @throws java.lang.IllegalArgumentException If there are no any added providers.
         */
        @NonNull
        @SuppressWarnings("PMD.AccessorClassGeneration")
        public Configuration build() {
            if (providersMap == null) {
                throw new IllegalArgumentException("Need to add at least one push provider.");
            }

            return new Configuration(
                    providersMap.values(),
                    eventListener,
                    isSelectSystemPreferred,
                    checkManifestHandler
            );
        }

        @Override
        public String toString() {
            return "Builder{"
                    + "providersMap="
                    + providersMap
                    + ", systemPushPreferred="
                    + isSelectSystemPreferred
                    + '}';
        }
    }
}


text:
namespace ash {

class AppListFolderItem;
class AppListItem;
class AppListItemList;
class AppListModelObserver;
class AppListModelDelegate;

// Main model for the app list. Holds AppListItemList, which owns a list of
// AppListItems and is displayed in the grid view.
// NOTE: Currently this class observes |top_level_item_list_|. The View code may
// move entries in the item list directly (but can not add or remove them) and
// the model needs to notify its observers when this occurs.
class APP_LIST_MODEL_EXPORT AppListModel : public AppListItemListObserver {
 public:
  explicit AppListModel(AppListModelDelegate* app_list_model_delegate);

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

  ~AppListModel() override;

  void AddObserver(AppListModelObserver* observer);
  void RemoveObserver(AppListModelObserver* observer);

  void SetStatus(AppListModelStatus status);

  // Finds the item matching |id|.
  AppListItem* FindItem(const std::string& id);

  // Find a folder item matching |id|.
  AppListFolderItem* FindFolderItem(const std::string& id);

  // Creates and adds an empty folder item with the provided ID.
  AppListFolderItem* CreateFolderItem(const std::string& folder_id);

  // Adds |item| to the model. The model takes ownership of |item|. Returns a
  // pointer to the item that is safe to use (e.g. after passing ownership).
  AppListItem* AddItem(std::unique_ptr<AppListItem> item);

  // Adds |item| to an existing folder or creates a new folder. If |folder_id|
  // is empty, adds the item to the top level model instead. The model takes
  // ownership of |item|. Returns a pointer to the item that is safe to use.
  AppListItem* AddItemToFolder(std::unique_ptr<AppListItem> item,
                               const std::string& folder_id);

  // Add a "page break" item right after the specified item in item list.
  void AddPageBreakItemAfter(const AppListItem* previous_item);

  // Updates an item's metadata (e.g. name, position, etc).
  void SetItemMetadata(const std::string& id,
                       std::unique_ptr<AppListItemMetadata> data);

  // Merges two items. If the target item is a folder, the source item is
  // added to the end of the target folder. Otherwise a new folder is created
  // in the same position as the target item with the target item as the first
  // item in the new folder and the source item as the second item. Returns
  // the id of the target folder, or an empty string if the merge failed. The
  // source item may already be in a folder. See also the comment for
  // RemoveItemFromFolder. NOTE: This should only be called by the View code
  // (not the sync code); it enforces folder restrictions (e.g. the target can
  // not be an OEM folder).
  const std::string MergeItems(const std::string& target_item_id,
                               const std::string& source_item_id);

  // Move |item| to the folder matching |folder_id| or to the top level if
  // |folder_id| is empty. |item|->position will determine where the item
  // is positioned. See also the comment for RemoveItemFromFolder.
  // This method should only be called by `AppListControllerImpl`. It does the
  // real job of reparenting an item. Note that `app_list_model_delegate_`
  // should be used to request for reparenting an item. We should not call
  // `MoveItemToFolder()` in ash directly.
  // TODO(https://crbug.com/1257605): it is confusing that when reparenting an
  // item, `MoveItemToFolder()` is called through an indirect way. The reason
  // leading to confusion is that `AppListModel` plays two roles: (1) the class
  // that sends the request for app list item change (2) the class that manages
  // app list items. To fix this issue, `AppListModel` code should be splitted
  // based on these two roles.
  void MoveItemToFolder(AppListItem* item, const std::string& folder_id);

  // Moves `item` to the top level. The item will be inserted before `position`
  // or at the end of the list if `position` is invalid. Note: `position` is
  // copied in case it refers to the containing folder which may get deleted.
  // See also the comment for RemoveItemFromFolder. Returns true if the item was
  // moved. NOTE: This should only be called by the View code (not the sync
  // code); it enforces folder restrictions (e.g. the source folder can not be
  // type OEM).
  bool MoveItemToRootAt(AppListItem* item, syncer::StringOrdinal position);

  // Sets the position of |item| either in |top_level_item_list_| or the
  // folder specified by |item|->folder_id(). If |new_position| is invalid,
  // move the item to the end of the list.
  void SetItemPosition(AppListItem* item,
                       const syncer::StringOrdinal& new_position);

  // Sets the name of |item| and notifies observers.
  void SetItemName(AppListItem* item, const std::string& name);

  // Deletes the item matching |id| from |top_level_item_list_| or from the
  // appropriate folder.
  void DeleteItem(const std::string& id);

  AppListModelDelegate* delegate() { return delegate_; }

  AppListItemList* top_level_item_list() const {
    return top_level_item_list_.get();
  }

  AppListModelStatus status() const { return status_; }

 private:
  enum class ReparentItemReason {
    // Reparent an item when adding the item to the model.
    kAdd,

    // Reparent an item when updating the item in the model.
    kUpdate
  };

  // AppListItemListObserver
  void OnListItemMoved(size_t from_index,
                       size_t to_index,
                       AppListItem* item) override;

  // Adds |item_ptr| to |top_level_item_list_| and notifies observers.
  AppListItem* AddItemToRootListAndNotify(std::unique_ptr<AppListItem> item_ptr,
                                          ReparentItemReason reason);

  // Adds |item_ptr| to |folder| and notifies observers.
  AppListItem* AddItemToFolderListAndNotify(
      AppListFolderItem* folder,
      std::unique_ptr<AppListItem> item_ptr,
      ReparentItemReason reason);

  // Notifies observers of `item` being reparented.
  void NotifyItemParentChange(AppListItem* item, ReparentItemReason reason);

  // Removes `item` from the top item list.
  std::unique_ptr<AppListItem> RemoveFromTopList(AppListItem* item);

  // Removes `item` from its parent folder. If `destination_folder_id` is not
  // set, the removed item will be deleted; otherwise, move `item` to the top
  // list or a specified folder depending on `destination_folder_id`. If
  // the parent folder becomes empty after removal, deletes the folder from
  // `top_level_item_list_`. It is guaranteed that folder deletion is always
  // after moving or deleting `item`.
  void ReparentOrDeleteItemInFolder(
      AppListItem* item,
      absl::optional<std::string> destination_folder_id);

  // Removes `item` from `folder` then returns a unique pointer to the removed
  // item.
  std::unique_ptr<AppListItem> RemoveItemFromFolder(AppListFolderItem* folder,
                                                    AppListItem* item);

  // Deletes folder with ID `folder_id` if it's empty.
  void DeleteFolderIfEmpty(const std::string& folder_id);

  // Sets the position of a root item.
  void SetRootItemPosition(AppListItem* item,
                           const syncer::StringOrdinal& new_position);

  // Used to initiate updates on app list items from the ash side.
  AppListModelDelegate* const delegate_;

  std::unique_ptr<AppListItemList> top_level_item_list_;

  AppListModelStatus status_ = AppListModelStatus::kStatusNormal;

  base::ObserverList<AppListModelObserver, true> observers_;
  base::ScopedMultiSourceObservation<AppListItemList, AppListItemListObserver>
      item_list_scoped_observations_{this};
};

}  // namespace ash

#endif  // ASH_APP_LIST_MODEL_APP_LIST_MODEL_H_

redpajama_set_name: RedPajamaGithub


text:
'use strict';

angular.module('writtenOffApp.view2', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/view2', {
    templateUrl: 'partials/view2.html',
    controller: 'View2Ctrl'
  });
}])

.controller('ModalDemoCtrl', function($scope, $modal) {

})

.controller('View2Ctrl', [function() {

}]);


text:
package us.crast.mondochest.persist;

import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;

public class PlayerState {
	private String lastClickedWorld = null;
	private Vector lastClickedVector = null;

	private State state = State.NORMAL;

	public PlayerState(Player player) {}

	/* Getters/Setters */
	public Location getLastClickedMaster() {
	    if (lastClickedWorld == null) return null;
	    World world = Bukkit.getWorld(lastClickedWorld);
	    if (world == null) return null;
		return new Location(
		    world,
		    lastClickedVector.getX(),
		    lastClickedVector.getY(),
		    lastClickedVector.getZ()
		);
	}

	public void setLastClickedMaster(Location lastClickedMaster) {
	    if (lastClickedMaster == null) {
	        this.lastClickedWorld = null;
	    } else {
    		this.lastClickedWorld = lastClickedMaster.getWorld().getName();
    		this.lastClickedVector = lastClickedMaster.toVector();
	    }
	}

	public boolean isManagingChest() {
	    return this.state == State.MANAGING_CHEST;
	}

	public void setManagingChest() {
	    this.state = State.MANAGING_CHEST;
	}

	public void setNormalMode() {
	    this.state = State.NORMAL;
	}

	enum State {
	    NORMAL,
	    MANAGING_CHEST;
	}
}


text:
var types = require("../main");
var n = types.namedTypes;
var b = types.builders;
var path = require("path");
var fs = require("fs");
var esprima = require("esprima");
var esprimaSyntax = esprima.Syntax;
var parse = esprima.parse;

exports.testBasic = function(t, assert) {
    var fooId = b.identifier("foo");
    var ifFoo = b.ifStatement(fooId, b.blockStatement([
        b.expressionStatement(b.callExpression(fooId, []))
    ]));

    assert.ok(n.IfStatement.check(ifFoo));
    assert.ok(n.Statement.check(ifFoo));
    assert.ok(n.Node.check(ifFoo));

    assert.ok(n.BlockStatement.check(ifFoo.consequent));
    assert.strictEqual(
        ifFoo.consequent.body[0].expression.arguments.length,
        0);

    assert.strictEqual(ifFoo.test, fooId);
    assert.ok(n.Expression.check(ifFoo.test));
    assert.ok(n.Identifier.check(ifFoo.test));
    assert.ok(!n.Statement.check(ifFoo.test));

    t.finish();
};

exports.testIsSupertypeOf = function(t, assert) {
    var def = types.Type.def;

    assert.ok(def("Node").isSupertypeOf(def("Node")));
    assert.ok(def("Node").isSupertypeOf(def("Expression")));
    assert.ok(!def("Expression").isSupertypeOf(def("Node")));
    assert.ok(!def("Expression").isSupertypeOf(
        def("DebuggerStatement")));

    // TODO Make this test case more exhaustive.

    t.finish();
};

exports.testShallowAndDeepChecks = function(t, assert) {
    var index = b.identifier("foo");
    var decl = b.variableDeclaration(
        "var", [b.variableDeclarator(
            index, b.literal(42))]);

    assert.ok(n.Node.check(decl));
    assert.ok(n.Statement.check(decl));
    assert.ok(n.Declaration.check(decl));
    assert.ok(n.VariableDeclaration.check(decl));

    assert.ok(n.Node.check(decl, true));
    assert.ok(n.Statement.check(decl, true));
    assert.ok(n.Declaration.check(decl, true));
    assert.ok(n.VariableDeclaration.check(decl, true));

    // Not an Expression.
    assert.ok(!n.Expression.check(decl));

    // This makes decl cease to conform to n.VariableDeclaration.
    decl.declarations.push(b.literal("bar"));

    assert.ok(n.Node.check(decl));
    assert.ok(n.Statement.check(decl));
    assert.ok(n.Declaration.check(decl));
    assert.ok(n.VariableDeclaration.check(decl));

    assert.ok(!n.Node.check(decl, true));
    assert.ok(!n.Statement.check(decl, true));
    assert.ok(!n.Declaration.check(decl, true));

    // As foretold above.
    assert.ok(!n.VariableDeclaration.check(decl, true));

    // Still not an Expression.
    assert.ok(!n.Expression.check(decl));

    var fs = b.forStatement(
        decl,
        b.binaryExpression("<", index, b.literal(48)),
        b.updateExpression("++", index, true),
        b.blockStatement([
            b.expressionStatement(
                b.callExpression(index, []))
        ]));

    assert.ok(n.Node.check(fs));
    assert.ok(n.Statement.check(fs));
    assert.ok(n.ForStatement.check(fs));

    // Not a true ForStatement because fs.init is not a true
    // VariableDeclaration.
    assert.ok(!n.Node.check(fs, true));
    assert.ok(!n.Statement.check(fs, true));
    assert.ok(!n.ForStatement.check(fs, true));

    t.finish();
};

function validateProgram(file) {
    var fullPath = path.join(__dirname, "..", file);

    exports["test " + file] = function(t, assert) {
        fs.readFile(fullPath, "utf8", function(err, code) {
            if (err) throw err;

            assert.ok(n.Program.check(parse(code), true));
            assert.ok(n.Program.check(parse(code, { loc: true }), true));

            t.finish();
        });
    };
}

validateProgram("main.js");
validateProgram("lib/shared.js");
validateProgram("def/core.js");
validateProgram("lib/types.js");
validateProgram("test/run.js");
validateProgram("test/data/backbone.js");
validateProgram("test/data/jquery-1.9.1.js");

exports.testEsprimaSyntaxBuildability = function(t, assert) {
    var def = types.Type.def;
    var todo = {
        ClassHeritage: true,
        ComprehensionBlock: true,
        ComprehensionExpression: true,
        ExportSpecifierSet: true,
        Glob: true,
        TaggedTemplateExpression: true,
        TemplateElement: true,
        TemplateLiteral: true
    };

    Object.keys(esprimaSyntax).forEach(function(name) {
        if (todo[name] === true) return;
        assert.ok(n.hasOwnProperty(name), name);
    });

    Object.keys(n).forEach(function(name) {
        if (name in esprimaSyntax)
            assert.ok(def(name).buildable, name);
    });

    t.finish();
};

exports.testGetFieldValue = function(t, assert) {
    assert.strictEqual(
        types.getFieldValue({
            type: "CatchClause"
        }, "guard"),
        null
    );

    assert.strictEqual(
        types.getFieldValue({
            type: "CatchClause"
        }, "asdf"),
        void 0
    );

    assert.strictEqual(
        types.getFieldValue({
            type: "CatchClause"
        }, "type"),
        "CatchClause"
    );

    assert.strictEqual(
        types.getFieldValue({
            type: "CatchClause",
            guard: b.identifier("test")
        }, "guard").name,
        "test"
    );

    assert.deepEqual(
        types.getFieldValue({
            type: "TryStatement",
        }, "handler"),
        null
    );

    assert.deepEqual(
        types.getFieldValue({
            type: "TryStatement",
        }, "handlers"),
        []
    );

    assert.deepEqual(
        types.getFieldValue({
            type: "TryStatement",
        }, "guardedHandlers"),
        []
    );

    assert.deepEqual(
        types.getFieldValue({
            type: "TryStatement",
            guardedHandlers: void 0
        }, "guardedHandlers"),
        []
    );

    t.finish();
};

exports.testEachField = function(t, assert) {
    var context = {};

    function check(node, names) {
        var seen = [];

        types.eachField(node, function(name, value) {
            assert.strictEqual(this, context);
            if (name === "type")
                assert.strictEqual(node.type, value);
            seen.push(name);
        }, context);

        assert.deepEqual(seen.sort(), names.sort());
    }

    check({ type: "Expression" }, [
        "type", "loc"
    ]);

    check({ type: "SourceLocation" }, [
        "type", "start", "end", "source"
    ]);

    check({ type: "TryStatement" }, [
        // Note that the "handlers" field is now hidden from eachField.
        "type", "block", "handler", "guardedHandlers", "finalizer", "loc"
    ]);

    check({ type: "CatchClause" }, [
        "type", "param", "guard", "body", "loc"
    ]);

    check({ type: "asdf" }, []);

    t.finish();
};

exports.testTraverse = function(t, assert) {
    var traverse = types.traverse;

    var call = b.expressionStatement(
        b.callExpression(
            b.memberExpression(
                b.identifier("foo"),
                b.identifier("bar"),
                false
            ),
            [b.literal("baz")]
        )
    );

    var ts = b.tryStatement(
        b.blockStatement([call, call]),
        b.catchClause(
            b.identifier("err"),
            null,
            b.blockStatement([])
        )
    );

    var literalCount = 0;

    traverse(ts, function(node) {
        if (n.Literal.check(node)) {
            literalCount += 1;
            assert.strictEqual(node.value, "baz");
            assert.strictEqual(this.parent.node, call.expression);
            assert.strictEqual(this.parent.parent.node, call);
            assert.strictEqual(this.parent.parent.parent.node, ts.block);
            assert.strictEqual(this.parent.parent.parent.parent.node, ts);
            assert.strictEqual(this.parent.parent.parent.parent.parent, null);
        }
    });

    assert.strictEqual(literalCount, 2);

    var ids = {};

    traverse(ts, function(node) {
        if (n.MemberExpression.check(node)) {
            return false;
        }

        if (n.Identifier.check(node)) {
            ids[node.name] = true;
        }
    });

    // Make sure all identifers beneath member expressions were skipped.
    assert.deepEqual(ids, { err: true });

    traverse(ts, function(node) {
        if (n.Identifier.check(node)) {
            ids[node.name] = true;
        }
    });

    // Now make sure those identifiers (foo and bar) were visited.
    assert.deepEqual(ids, {
        err: true,
        foo: true,
        bar: true
    });

    t.finish();
};

var scope = [
    "var foo = 42;",
    "function bar(baz) {",
    "  return baz + foo;",
    "}"
];

exports.testGlobalScope = function(t, assert) {
    var traverse = types.traverse;
    var ast = parse(scope.join("\n"));
    var globalScope;

    traverse(ast, function(node) {
        if (n.Program.check(node)) {
            assert.strictEqual(this.scope.isGlobal, true);
            globalScope = this.scope;

        } else if (n.FunctionDeclaration.check(node)) {
            assert.strictEqual(this.scope.isGlobal, false);

            assert.strictEqual(node.id.name, "bar");
            assert.notStrictEqual(this.scope, globalScope);
            assert.strictEqual(this.scope.isGlobal, false);
            assert.strictEqual(this.scope.parent, globalScope);

            assert.strictEqual(this.scope.getGlobalScope(), globalScope);
            assert.ok(globalScope.declares("foo"));
            assert.ok(globalScope.declares("bar"));
            assert.strictEqual(this.scope.lookup("foo"), globalScope);
            assert.strictEqual(this.scope.lookup("bar"), globalScope);

            assert.ok(this.scope.declares("baz"));
            assert.strictEqual(this.scope.lookup("baz"), this.scope);

            assert.strictEqual(this.scope.lookup("qux"), null);
            assert.strictEqual(globalScope.lookup("baz"), null);
        }
    });

    t.finish();
};


text:
package org.jboss.weld.environment.se.test.extension.build.compatible;

import jakarta.enterprise.event.Observes;
import jakarta.enterprise.inject.spi.AfterBeanDiscovery;
import jakarta.enterprise.inject.spi.BeforeBeanDiscovery;
import jakarta.enterprise.inject.spi.Extension;
import jakarta.enterprise.inject.spi.ProcessAnnotatedType;

/**
 * This PE overrides {@link OverridenBuildCompatibleExtension} and should be executed instead
 */
public class OverridingPortableExtension implements Extension {

    public static int TIMES_INVOKED = 0;

    public void pat(@Observes ProcessAnnotatedType<DummyBean> pat) {
        TIMES_INVOKED++;
    }

    public void bbd(@Observes BeforeBeanDiscovery bbd) {
        TIMES_INVOKED++;
    }

    public void abd(@Observes AfterBeanDiscovery abd) {
        TIMES_INVOKED++;
    }
}


text:
package com.thinkbiganalytics.nifi.v2.hdfs;

import org.apache.nifi.components.PropertyDescriptor;

/**
 * Additional properties for Hadoop processors (NiFi version 1.0)
 */
public class AdditionalProperties {

    public static PropertyDescriptor getHdfsAdditionalClasspathResources() {
        return null;
    }

    public static String getNiFiVersion() {
        return "v1.0";
    }
}


text:
# Common middleware

As well as per-route middleware you can also define more _common_ middleware, which apply per-HTTP-method and/or to all incoming requests.

Both of these are defined in your app's [configuration](../AppConfiguration/), as such:

```javascript
// file: <project folder>/src/config/base.js

module.exports = function(config) {
  ...
  /* middleware for every request */
  config.middleware.ALL = {
    /* order in which middleware gets run */
    _order: [
      'errorHandler',
      'staticResources',
    ],
    /* options for each middleware's initializer */
    errorHandler: {},
    staticResources: {
      // relative to app folder
      folder: '/static',
    },
  };
  ...

  /* middleware for only POST and PUT requests */
  config.middleware.POST = config.middleware.PUT = {
  	/* order in which middleware gets run */
    _order: [
      'bodyParser',
      'csrf',
    ],
    /* options to pass to each middleware's initialier */
    bodyParser: {
      limit: '16mb',
    },
  };
}
```

Once a request has been passed through the common middleware handler chain it then gets handed off to the middleware specific to the route associated with the request.

Let's say you have route defined as such:

```javascript
// file: <project folder>/src/routes/user.js

module.exports = {
  '/user': {
  	'/info': {
      GET: 'users.updateInfo'
	  },
  	'/pic': {
      POST: [ { id: 'bodyParser', limit: '3mb' }, 'users.updatePic' ]
	  }
  }
};
```

Combined with the common middleware defined above, this is what the actual route middleware chain would look like if we were to define it entirely within the route configuration:

```javascript
module.exports = {
  '/user': {
  	'/info': {
     GET: [
       'errorHandler',
       { id: 'staticResources', folder: '/static' },
       'users.getInfo'
     ]
	},
  	'/pic': {
     POST: [
       'errorHandler',
       { id: 'staticResources', folder: '/static' },
       { id: 'bodyParser', limit: '16mb' },
       'csrf',
       'users.updatePic'
     ]
	}
  }
};
```


text:
<PackageItem xmlns:tcm="http://www.tridion.com/ContentManager/5.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.sdltridion.com/ContentManager/ImportExport/Package/2013">
  <Data>
    <tcm:Data>
      <tcm:Title>TridionDocsMashup</tcm:Title>
      <tcm:Type>Normal</tcm:Type>
      <tcm:Schema xlink:type="simple" xlink:title="Module Configuration" xlink:href="/webdav/100%20Master/Building%20Blocks/Framework/Developer/Schemas/Module%20Configuration.xsd" IsMandatory="false" />
      <tcm:Content>
        <ModuleConfiguration xmlns="http://www.sdl.com/web/schemas/core">
          <name>TridionDocsMashup</name>
          <softwareVersion>2.2</softwareVersion>
          <isActive>Yes</isActive>
          <furtherConfiguration xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/webdav/100%20Master/Building%20Blocks/Modules/TridionDocsMashup/Admin/TridionDocsMashup%20URL%20Configuration.xml" xlink:title="TridionDocsMashup URL Configuration" />
          <designConfiguration xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/webdav/100%20Master/Building%20Blocks/Settings/TridionDocsMashup/Site%20Manager/TridionDocsMashup%20HTML%20Design%20Configuration.xml" xlink:title="TridionDocsMashup HTML Design Configuration" />
        </ModuleConfiguration>
      </tcm:Content>
      <tcm:Metadata />
      <tcm:IsBasedOnTridionWebSchema>true</tcm:IsBasedOnTridionWebSchema>
      <tcm:MultimediaType xlink:type="simple" xlink:title="" xlink:href="tcm:0-0-0" />
    </tcm:Data>
  </Data>
  <Dependencies>
    <Dependency dependencyType="Publication" itemUrl="/webdav/100%20Master" linkName="LocationInfo/ContextRepository" />
    <Dependency dependencyType="OrganizationalItemFolder" itemUrl="/webdav/100%20Master/Building%20Blocks/Modules/TridionDocsMashup/Admin" linkName="LocationInfo/OrganizationalItem" />
    <Dependency dependencyType="LinkedComponent" itemUrl="/webdav/100%20Master/Building%20Blocks/Modules/TridionDocsMashup/Admin/TridionDocsMashup%20URL%20Configuration.xml" linkName="Content" xpath="*[local-name() = 'ModuleConfiguration'][1]/*[local-name() = 'furtherConfiguration'][1]/@xlink:href" />
    <Dependency dependencyType="LinkedComponent" itemUrl="/webdav/100%20Master/Building%20Blocks/Settings/TridionDocsMashup/Site%20Manager/TridionDocsMashup%20HTML%20Design%20Configuration.xml" linkName="Content" xpath="*[local-name() = 'ModuleConfiguration'][1]/*[local-name() = 'designConfiguration'][1]/@xlink:href" />
    <Dependency dependencyType="Schema" itemUrl="/webdav/100%20Master/Building%20Blocks/Framework/Developer/Schemas/Module%20Configuration.xsd" linkName="Schema" />
  </Dependencies>
</PackageItem>


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:fillAfter="true" >

    <alpha
        android:duration="2000"
        android:fromAlpha="0.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:toAlpha="1.0"
        android:repeatCount="infinite"/>

</set>


text:
package runner;

import java.util.regex.Pattern;

public class Replace {
	public Replace(String pattern, String corpus_text, String replace){
		// Nice and short :)
		String json = "{\"replace\":\"" + Pattern.compile(pattern).matcher(corpus_text).replaceAll(replace) + "\"}";
		System.out.println(json);
	}
}


text:
package org.araymond.joal.core.client.emulated.generator.key;

import com.turn.ttorrent.common.protocol.TrackerMessage.AnnounceRequestMessage.RequestEvent;
import org.araymond.joal.core.client.emulated.TorrentClientConfigIntegrityException;
import org.araymond.joal.core.client.emulated.generator.key.algorithm.KeyAlgorithm;
import org.araymond.joal.core.client.emulated.utils.Casing;
import org.araymond.joal.core.torrent.torrent.InfoHash;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

/**
 * Created by raymo on 16/07/2017.
 */
public class TimedRefreshKeyGeneratorTest {

    @Test
    public void shouldNotBuildWithoutRefreshEvery() {
        final KeyAlgorithm algo = Mockito.mock(KeyAlgorithm.class);
        Mockito.when(algo.generate()).thenReturn("do-not-care");
        assertThatThrownBy(() -> new TimedRefreshKeyGenerator(null, algo, Casing.NONE))
                .isInstanceOf(TorrentClientConfigIntegrityException.class)
                .hasMessage("refreshEvery must be greater than 0.");
    }

    @Test
    public void shouldNotBuildWithRefreshEveryLessThanOne() {
        final KeyAlgorithm algo = Mockito.mock(KeyAlgorithm.class);
        Mockito.when(algo.generate()).thenReturn("do-not-care");
        assertThatThrownBy(() -> new TimedRefreshKeyGenerator(0, algo, Casing.NONE))
                .isInstanceOf(TorrentClientConfigIntegrityException.class)
                .hasMessage("refreshEvery must be greater than 0.");
    }

    @Test
    public void shouldBuild() {
        final KeyAlgorithm algo = Mockito.mock(KeyAlgorithm.class);
        Mockito.when(algo.generate()).thenReturn("do-not-care");
        final TimedRefreshKeyGenerator generator = new TimedRefreshKeyGenerator(10, algo, Casing.NONE);

        assertThat(generator.getRefreshEvery()).isEqualTo(10);
    }

    @Test
    public void keyShouldNotBeRefreshedIfDelayIsNotElapsedAndRefreshWhenElapsed() throws InterruptedException {
        final KeyAlgorithm algo = Mockito.mock(KeyAlgorithm.class);
        Mockito.when(algo.generate()).thenReturn("do-not-care");
        final TimedRefreshKeyGenerator generator = new TimedRefreshKeyGenerator(1, algo, Casing.NONE);

        final InfoHash infoHash = new InfoHash(new byte[] { 22 });
        assertThat(generator.getKey(infoHash, RequestEvent.STARTED))
                .isEqualTo(generator.getKey(infoHash, RequestEvent.STARTED))
                .isEqualTo(generator.getKey(infoHash, RequestEvent.STARTED))
                .isEqualTo(generator.getKey(infoHash, RequestEvent.STARTED))
                .isEqualTo(generator.getKey(infoHash, RequestEvent.STARTED));

        Mockito.verify(algo, Mockito.times(1)).generate();

        generator.lastGeneration = LocalDateTime.now().minus(10, ChronoUnit.SECONDS);

        generator.getKey(infoHash, RequestEvent.STARTED);
        Mockito.verify(algo, Mockito.times(2)).generate();
    }

}


text:
@import Foundation;
@import CoreGraphics;

NS_ASSUME_NONNULL_BEGIN
@interface NSNumber (Mathematica)

- (NSArray<NSNumber *> *)squareFactorization;

@end

@interface NSNumber (CGFloatAddition)

@property (readonly) CGFloat CGFloatValue;

+ (instancetype)numberWithCGFloat:(CGFloat)floatValue;
- (instancetype)initWithCGFloat:(CGFloat)value;

@end
NS_ASSUME_NONNULL_END


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yirui.admin.sys.group.dao.GroupDao">
    <!-- 缓存算法:LRU,FIFO,SOFT,WEAK
             flushInterval 单位毫秒 清空缓存间隔-->
    <cache type="org.mybatis.caches.ehcache.EhcacheCache" eviction="LRU"
           flushInterval="60000" size="1024" readOnly="true" />

    <sql id="groupColumns">
      SELECT id,name,type,is_show show,default_group defaultGroup FROM sys_group
    </sql>

    <select id="findDefaultGroupIds" resultType="int">
        SELECT id FROM sys_group WHERE default_group=1 and is_show=1
    </select>

    <select id="findAll" resultType="Group">
        <include refid="groupColumns"/>
    </select>
</mapper>


text:
#ifndef TENSORFLOW_LITE_SUPPORT_CC_COMMON_H_
#define TENSORFLOW_LITE_SUPPORT_CC_COMMON_H_

#include "absl/status/status.h"  // from @com_google_absl
#include "absl/strings/string_view.h"  // from @com_google_absl

namespace tflite {
namespace support {

// Name (aka type URL key) of the `absl::Status` payload which contains a
// stringified `TfLiteSupportStatus` code (see below).
constexpr absl::string_view kTfLiteSupportPayload =
    "tflite::support::TfLiteSupportStatus";

// Error codes for TensorFlow Lite Support (TFLS) C++ APIs.
//
// Such codes capture errors encountered in the TFLS layer. They complement all
// the other type of errors that occur in the lower-level TF Lite codebase (see
// `TfLiteStatus` codes).
//
// At runtime, such codes are meant to be attached (where applicable) to a
// `absl::Status` in a key-value manner with `kTfLiteSupportPayload` as key and
// stringifed error code as value (aka payload). This logic is encapsulated in
// the `CreateStatusWithPayload` helper below for convenience.
//
// The returned status includes:
// 1. The canonical error code (INVALID_ARGUMENT)
// 2. The fine-grained error message ("Invalid metadata ...")
// 3. The specific TFLS code as a payload (kMetadataInvalidSchemaVersionError)
enum class TfLiteSupportStatus {
  // Generic error codes.

  // Success.
  kOk = 0,
  // Unspecified error.
  kError = 1,
  // Invalid argument specified.
  kInvalidArgumentError = 2,
  // Invalid FlatBuffer file or buffer specified.
  kInvalidFlatBufferError = 3,
  // Model contains a builtin op that isn't supported by the OpResolver or
  // delegates.
  kUnsupportedBuiltinOp = 4,
  // Model contains a custom op that isn't supported by the OpResolver or
  // delegates.
  kUnsupportedCustomOp = 5,

  // File I/O error codes.

  // No such file.
  kFileNotFoundError = 100,
  // Permission issue.
  kFilePermissionDeniedError,
  // I/O error when reading file.
  kFileReadError,
  // I/O error when mmap-ing file.
  kFileMmapError,

  // TensorFlow Lite metadata error codes.

  // Unexpected schema version (aka file_identifier) in the Metadata FlatBuffer.
  kMetadataInvalidSchemaVersionError = 200,
  // No such associated file within metadata, or file has not been packed.
  kMetadataAssociatedFileNotFoundError,
  // ZIP I/O error when unpacking an associated file.
  kMetadataAssociatedFileZipError,
  // Inconsistency error between the metadata and actual TF Lite model.
  // E.g.: number of labels and output tensor values differ.
  kMetadataInconsistencyError,
  // Invalid process units specified.
  // E.g.: multiple ProcessUnits with the same type for a given tensor.
  kMetadataInvalidProcessUnitsError,
  // Inconsistency error with the number of labels.
  // E.g.: label files for different locales have a different number of labels.
  kMetadataNumLabelsMismatchError,
  // Score calibration parameters parsing error.
  // E.g.: too many parameters provided in the corresponding associated file.
  kMetadataMalformedScoreCalibrationError,
  // Unexpected number of subgraphs for the current task.
  // E.g.: image classification expects a single subgraph.
  kMetadataInvalidNumSubgraphsError,
  // A given tensor requires NormalizationOptions but none were found.
  // E.g.: float input tensor requires normalization to preprocess input images.
  kMetadataMissingNormalizationOptionsError,
  // Invalid ContentProperties specified.
  // E.g. expected ImageProperties, got BoundingBoxProperties.
  kMetadataInvalidContentPropertiesError,
  // Metadata is mandatory but was not found.
  // E.g. current task requires TFLite Model Metadata but none was found.
  kMetadataNotFoundError,
  // Associated TENSOR_AXIS_LABELS or TENSOR_VALUE_LABELS file is mandatory but
  // none was found or it was empty.
  // E.g. current task requires labels but none were found.
  kMetadataMissingLabelsError,
  // The ProcessingUnit for tokenizer is not correctly configured.
  // E.g BertTokenizer doesn't have a valid vocab file associated.
  kMetadataInvalidTokenizerError,

  // Input tensor(s) error codes.

  // Unexpected number of input tensors for the current task.
  // E.g. current task expects a single input tensor.
  kInvalidNumInputTensorsError = 300,
  // Unexpected input tensor dimensions for the current task.
  // E.g.: only 4D input tensors supported.
  kInvalidInputTensorDimensionsError,
  // Unexpected input tensor type for the current task.
  // E.g.: current task expects a uint8 pixel image as input.
  kInvalidInputTensorTypeError,
  // Unexpected input tensor bytes size.
  // E.g.: size in bytes does not correspond to the expected number of pixels.
  kInvalidInputTensorSizeError,
  // No correct input tensor found for the model.
  // E.g.: input tensor name is not part of the text model's input tensors.
  kInputTensorNotFoundError,

  // Output tensor(s) error codes.

  // Unexpected output tensor dimensions for the current task.
  // E.g.: only a batch size of 1 is supported.
  kInvalidOutputTensorDimensionsError = 400,
  // Unexpected input tensor type for the current task.
  // E.g.: multi-head model with different output tensor types.
  kInvalidOutputTensorTypeError,
  // No correct output tensor found for the model.
  // E.g.: output tensor name is not part of the text model's output tensors.
  kOutputTensorNotFoundError,
  // Unexpected number of output tensors for the current task.
  // E.g.: current task expects a single output tensor.
  kInvalidNumOutputTensorsError,

  // Image processing error codes.

  // Unspecified image processing failures.
  kImageProcessingError = 500,
  // Unexpected input or output buffer metadata.
  // E.g.: rotate RGBA buffer to Grayscale buffer by 90 degrees.
  kImageProcessingInvalidArgumentError,
  // Image processing operation failures.
  // E.g. libyuv rotation failed for an unknown reason.
  kImageProcessingBackendError,
};

// Convenience helper to create an `absl::Status` augmented with the
// fine-grained `tfls_code` attached as payload under the
// `kTfLiteSupportPayload` type URL key.
//
// This should only be used for non-ok codes since otherwise it does nothing
// more than returning an object identical to an OK status. See `absl::Status`
// for more details.
absl::Status CreateStatusWithPayload(
    absl::StatusCode canonical_code, absl::string_view message,
    tflite::support::TfLiteSupportStatus tfls_code =
        tflite::support::TfLiteSupportStatus::kError);

}  // namespace support
}  // namespace tflite
#endif  // TENSORFLOW_LITE_SUPPORT_CC_COMMON_H_


text:
import config from '../webpack.dev.js'
import webpack from 'webpack'
import webpackDevMiddleware from 'webpack-dev-middleware'
import webpackHotMiddleware from 'webpack-hot-middleware'

export function bindDevAssets(app) {
  const compiler = webpack(config)
  app.use(webpackDevMiddleware(compiler))
  app.use(webpackHotMiddleware(compiler))
}


text:
.class final Landroid/media/session/MediaSession$QueueItem$1;
.super Ljava/lang/Object;
.source "MediaSession.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/media/session/MediaSession$QueueItem;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Landroid/os/Parcelable$Creator",
        "<",
        "Landroid/media/session/MediaSession$QueueItem;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Landroid/media/session/MediaSession$QueueItem;
    .locals 2

    new-instance v0, Landroid/media/session/MediaSession$QueueItem;

    const/4 v1, 0x0

    invoke-direct {v0, p1, v1}, Landroid/media/session/MediaSession$QueueItem;-><init>(Landroid/os/Parcel;Landroid/media/session/MediaSession$QueueItem;)V

    return-object v0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1

    invoke-virtual {p0, p1}, Landroid/media/session/MediaSession$QueueItem$1;->createFromParcel(Landroid/os/Parcel;)Landroid/media/session/MediaSession$QueueItem;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Landroid/media/session/MediaSession$QueueItem;
    .locals 1

    new-array v0, p1, [Landroid/media/session/MediaSession$QueueItem;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .locals 1

    invoke-virtual {p0, p1}, Landroid/media/session/MediaSession$QueueItem$1;->newArray(I)[Landroid/media/session/MediaSession$QueueItem;

    move-result-object v0

    return-object v0
.end method


text:
Ext.ns('Rwiki.Tree');

Rwiki.Tree.Menu = Ext.extend(Ext.menu.Menu, {
  constructor: function() {
    Ext.apply(this, {
      id: 'feeds-ctx',
      items: [{
        text: 'Add page',
        id: 'add-page',
        iconCls: 'icon-add-page',
        scope: this,
        handler: this.onCreatePage
      }, '-',  {
        text: 'Rename page',
        id: 'rename-page',
        iconCls: 'icon-rename-page',
        scope: this,
        handler: this.onRenameNode
      }, {
        text: 'Delete page',
        id: 'delete-page',
        iconCls: 'icon-delete-page',
        scope: this,
        handler: this.onDeleteNode
      }]
    });

    Rwiki.Tree.Menu.superclass.constructor.apply(this, arguments);
  },

  show: function(node, xy) {
    this.node = node;
    node.select();

    this.setItemDisabled('delete-page', node.isRoot);
    this.setItemDisabled('rename-page', node.isRoot);

    this.showAt(xy);
  },

  onCreatePage: function() {
    var parentNode = this.node;
    Rwiki.keyMap.disable();

    var callback = function(button, name) {
      Rwiki.keyMap.enable();

      if (button !== 'ok') {
        return;
      }

      var parentPath = parentNode.getPath();
      Rwiki.nodeManager.createPage(parentPath, name);
    }

    Ext.MessageBox.prompt('Add page', 'New page name:', callback);
  },

  onRenameNode: function() {
    Rwiki.keyMap.disable();
    var node = this.node;
    if (node.isRoot) {
      return;
    }

    var oldPath = node.getPath();
    var oldBaseName = node.text;

    var callback = function(button, newName) {
      Rwiki.keyMap.enable();
      if (button !== 'ok') {
        return;
      }

      Rwiki.nodeManager.renameNode(oldPath, newName);
    };

    Ext.MessageBox.prompt('Rename page', 'Enter a new name:', callback, this, false, oldBaseName);
  },

  onDeleteNode: function() {
    var node = this.node;
    if (node.isRoot) {
      return;
    }

    var path = node.getPath();

    var callback = function(button) {
      if (button !== 'yes') {
        return;
      }

      Rwiki.nodeManager.deleteNode(path);
    };

    var message = 'Delete "' + path + '"?';
    Ext.MessageBox.confirm('Confirm', message, callback);
  },

  setItemDisabled: function(id, disabled) {
    var item = this.findById(id);
    item.setDisabled(disabled);
  }
});


text:
<?php

namespace danapplegate\LeakyBucket\Storage;

use danapplegate\LeakyBucket\TokenBucket;

/**
 * StorageInterface.php
 *
 * @package     PHP Leaky Bucket
 * @author 		Dan Applegate <dan.applegate@rokkan.com>
 * @copyright   Copyright 2012 Rokkan Media LLC
 * @since 		Mar 27, 2012
 * @license     MIT license
 */
interface StorageInterface {

    public function readBucket(TokenBucket $bucket);

    public function writeBucket(TokenBucket $bucket);
}


text:
<?php

namespace Box\Spout\Reader\CSV;

use Box\Spout\Reader\AbstractReader;
use Box\Spout\Common\Exception\IOException;

/**
 * Class Reader
 * This class provides support to read data from a CSV file.
 *
 * @package Box\Spout\Reader\CSV
 */
class Reader extends AbstractReader
{
    /** @var resource Pointer to the file to be written */
    protected $filePointer;

    /** @var SheetIterator To iterator over the CSV unique "sheet" */
    protected $sheetIterator;

    /** @var string Original value for the "auto_detect_line_endings" INI value */
    protected $originalAutoDetectLineEndings;

    /**
     * Returns the reader's current options
     *
     * @return ReaderOptions
     */
    protected function getOptions()
    {
        if (!isset($this->options)) {
            $this->options = new ReaderOptions();
        }
        return $this->options;
    }

    /**
     * Sets the field delimiter for the CSV.
     * Needs to be called before opening the reader.
     *
     * @param string $fieldDelimiter Character that delimits fields
     * @return Reader
     */
    public function setFieldDelimiter($fieldDelimiter)
    {
        $this->getOptions()->setFieldDelimiter($fieldDelimiter);
        return $this;
    }

    /**
     * Sets the field enclosure for the CSV.
     * Needs to be called before opening the reader.
     *
     * @param string $fieldEnclosure Character that enclose fields
     * @return Reader
     */
    public function setFieldEnclosure($fieldEnclosure)
    {
        $this->getOptions()->setFieldEnclosure($fieldEnclosure);
        return $this;
    }

    /**
     * Sets the encoding of the CSV file to be read.
     * Needs to be called before opening the reader.
     *
     * @param string $encoding Encoding of the CSV file to be read
     * @return Reader
     */
    public function setEncoding($encoding)
    {
        $this->getOptions()->setEncoding($encoding);
        return $this;
    }

    /**
     * Sets the EOL for the CSV.
     * Needs to be called before opening the reader.
     *
     * @param string $endOfLineCharacter used to properly get lines from the CSV file.
     * @return Reader
     */
    public function setEndOfLineCharacter($endOfLineCharacter)
    {
        $this->getOptions()->setEndOfLineCharacter($endOfLineCharacter);
        return $this;
    }

    /**
     * Returns whether stream wrappers are supported
     *
     * @return bool
     */
    protected function doesSupportStreamWrapper()
    {
        return true;
    }

    /**
     * Opens the file at the given path to make it ready to be read.
     * If setEncoding() was not called, it assumes that the file is encoded in UTF-8.
     *
     * @param  string $filePath Path of the CSV file to be read
     * @return void
     * @throws \Box\Spout\Common\Exception\IOException
     */
    protected function openReader($filePath)
    {
        $this->originalAutoDetectLineEndings = ini_get('auto_detect_line_endings');
        ini_set('auto_detect_line_endings', '1');

        $this->filePointer = $this->globalFunctionsHelper->fopen($filePath, 'r');
        if (!$this->filePointer) {
            throw new IOException("Could not open file $filePath for reading.");
        }

        $this->sheetIterator = new SheetIterator(
            $this->filePointer,
            $this->getOptions(),
            $this->globalFunctionsHelper
        );
    }

    /**
     * Returns an iterator to iterate over sheets.
     *
     * @return SheetIterator To iterate over sheets
     */
    protected function getConcreteSheetIterator()
    {
        return $this->sheetIterator;
    }

    /**
     * Closes the reader. To be used after reading the file.
     *
     * @return void
     */
    protected function closeReader()
    {
        if ($this->filePointer) {
            $this->globalFunctionsHelper->fclose($this->filePointer);
        }

        ini_set('auto_detect_line_endings', $this->originalAutoDetectLineEndings);
    }
}


text:
layout: post
title:  "内存优化之图片加载"
date:   2017-05-02
---
###问题
为什么 ImageView 是155x155,而用 Fresco 加载的 Bitmap 却是 512x512 呢

先看下 ViewHolder 的布局信息

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:orientation="horizontal">

        <include
            android:id="@+id/layout_1"
            layout="@layout/unit_app_download"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <include
            android:id="@+id/layout_2"
            layout="@layout/unit_app_download"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <include
            android:id="@+id/layout_3"
            layout="@layout/unit_app_download"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <include
            android:id="@+id/layout_4"
            layout="@layout/unit_app_download"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

    </LinearLayout>

unit\_app\_download.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <org.qiyi.basecore.widget.QiyiDraweeView
            android:id="@+id/poster"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:scaleType="centerCrop" />

        <RelativeLayout
            android:id="@+id/meta_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/poster">
            ...
        </RelativeLayout>
    </RelativeLayout>

基本就是 4个 QiyiDraweeView 4等分屏幕宽度(我的手机是1280x720,720/4=180,为了精简展示,布局里一些 margin 等信息被我去掉)

布局这样的写法,在 setResizeOptions() 的时候,在控件未渲染的时候,获取的宽高都是0( layout\_width, layout\_height 不是固定数值的都获取不到,这个问题不是 Fresco 特有的,使用 UniversalImageLoader 也要面对这个问题)

    public class QiyiDraweeView extends SimpleDraweeView {
        ....
        private ResizeOptions getResizeOption() {
            ViewGroup.LayoutParams layoutParams = getLayoutParams();
            int width = (layoutParams != null && layoutParams.width > 0) ? layoutParams.width : getScreenWidth();
            int height = (layoutParams != null && layoutParams.height > 0) ? layoutParams.height : 1;
            return new ResizeOptions(width, height);
        }

        public void setImageURI(final Uri uri) {
            ...
            ImageRequest request = ImageRequestBuilder
                    .newBuilderWithSource(uri)
                    .setResizeOptions(getResizeOption())
                    .setImageDecodeOptions(ImageDecodeOptions.newBuilder().setDecodePreviewFrame(true).build())
                    .build();
            ...
        }
    }

###解决

对我们来说,最容(甩)易(锅)的解决方法就是让服务端把这12张512x512的图都缩小一些,但这是治标不治本,而且这些 url 还可能在其他地方使用

未渲染的时候,得不到 width 和 height,也得不到 measuredWidth 和 measuredHeight,那能不能在 measure 之后再去获取宽高,获取图片呢? View 的确有提供这样一个方法

    public void setImageURI(final Uri uri) {
        getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                setImageURI(uri);
                return true;
            }
        });
    }

在 onPreDraw() 里就能获取到宽高了。但是,这个从开始监听到回调 onPreDraw() 经过了1秒多,这样就相当于延迟1秒多才去获取图片,这就得不偿失了,只能另寻方法了

那我们能不能在 getResizeOption() 的时候,如果获取不到宽高,就自己去调用 measure() 呢?这样就能得到 measuredWidth 和 measuredHeight

	public final void measure(int widthMeasureSpec, int heightMeasureSpec)

但应该传入多大的宽高呢?不用担心,我们只要在当前位置 getRootView(),就能得到最上层的 View 了,调用 getRootView().measure() 传入屏幕宽度和高度(我们估算的话,当然是让最外层的 View 充满屏幕,这样才能保证估算出来的宽高不会小于实际宽高),之后当前 View 就能得到一个估算的宽高

    private ResizeOptions getResizeOption() {
        ViewGroup.LayoutParams layoutParams = getLayoutParams();
        int width = (layoutParams != null && layoutParams.width > 0) ? layoutParams.width : getWidthOrMaxWidth();
        int height = (layoutParams != null && layoutParams.height > 0) ? layoutParams.height : getHeightOrMaxHeight();
        if (width <= 0 || height <= 0) {
            getRootView().measure(MeasureSpec.makeMeasureSpec(getScreenWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(getScreenHeight(), MeasureSpec.EXACTLY));
            if (width <= 0) {
                width = getMeasuredWidth();
                if (width <= 1) {//ImageView onMeasure() 中会判断 width height,如果 <=0,就=1
                    width = getScreenWidth();
                }
            }
            if (height <= 0) {
                height = getMeasuredHeight();
            }
        }
        return new ResizeOptions(width, height);
    }

这样改写后,得到的 measuredWidth 和 measuredHeight 就是155

那 getRootView().measure() 的性能如何?
如果 ViewGroup 节点下有 N 个 ImageView,当第一个 ImageView 要获取宽高的时候,因为获取不到而执行 getRootView().measure(),那么后续的 N-1 个 ImageView 就可以直接获取到宽高了,不会重复 measure

getWidthOrMaxWidth() 是参考 UniversalImageLoader 的代码,其加入了 maxWidth 和 maxHeight 属性的支持,就是当 layoutParams.width <= 0 时(不是固定值),去获取 maxWidth,如果有配置则使用 maxWidth

    ImageLoader.java
    public void displayImage(String uri, ImageAware imageAware, DisplayImageOptions options,
            ImageSize targetSize, ImageLoadingListener listener, ImageLoadingProgressListener progressListener) {
        ...
        if (targetSize == null) {
            targetSize = ImageSizeUtils.defineTargetSizeForView(imageAware, configuration.getMaxImageSize());
        }
        ...
    }

    ImageSizeUtils.java
    public static ImageSize defineTargetSizeForView(ImageAware imageAware, ImageSize maxImageSize) {
        int width = imageAware.getWidth();
        if (width <= 0) width = maxImageSize.getWidth();

        int height = imageAware.getHeight();
        if (height <= 0) height = maxImageSize.getHeight();

        return new ImageSize(width, height);
    }

    ImageViewAware.java
    @Override
    public int getWidth() {
        int width = super.getWidth();
        if (width <= 0) {
            ImageView imageView = (ImageView) viewRef.get();
            if (imageView != null) {
                width = getImageViewFieldValue(imageView, "mMaxWidth"); // 反射获取,因为 getMaxWidth() 是API16开始才支持的
            }
        }
        return width;
    }

    @Override
    public int getHeight() {
        int height = super.getHeight();
        if (height <= 0) {
            ImageView imageView = (ImageView) viewRef.get();
            if (imageView != null) {
                height = getImageViewFieldValue(imageView, "mMaxHeight");
            }
        }
        return height;
    }

那么我们的 QiyiDraweeView 也可以依葫芦画瓢

    public int getWidthOrMaxWidth() {
        int width = super.getWidth();
        if (width <= 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                width = getMaxWidth();
            } else {
                width = getImageViewFieldValue("mMaxWidth"); // 反射获取,因为 getMaxWidth() 是API16开始才支持的
            }
            if (width <= 0) {
                width = getMeasuredWidth();
            }
        }
        return width;
    }

    public int getHeightOrMaxHeight() {
        int height = super.getHeight();
        if (height <= 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                height = getMaxHeight();
            } else {
                height = getImageViewFieldValue("mMaxHeight");
            }
            if (height <= 0) {
                height = getMeasuredHeight();
            }
        }
        return height;
    }

    private int getImageViewFieldValue(String fieldName) {
        int value = 0;
        try {
            Field field = ImageView.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            int fieldValue = (Integer) field.get(this);
            if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) {
                value = fieldValue;
            }
        } catch (Exception e) {
        }
        return value;
    }


text:
package mimir.sql;

import java.sql._
import java.util

import sparsity.statement.{Statement => SparsityStatement}
import sparsity.expression.{
  Expression  => SparsityExpression,
  LongPrimitive    => SparsityLong,
  DoublePrimitive  => SparsityDouble,
  StringPrimitive  => SparsityString,
  NullPrimitive    => SparsityNull,
  BooleanPrimitive => SparsityBool,
  PrimitiveValue   => SparsityPrimitive,
  Not              => SparsityNot,
  Function         => SparsityFunction,
  Comparison       => SparsityComparison,
  Arithmetic       => SparsityArithmetic,
  Cast             => SparsityCast,
  IsNull           => SparsityIsNull,
  Column,
  InExpression,
  CaseWhenElse
}
import sparsity.select.{
  SelectBody,
  SelectExpression,
  SelectAll,
  SelectTable,
  FromElement,
  FromSelect,
  FromTable,
  FromJoin,
  Join => SparsityJoin
}
import sparsity.Name

import mimir.Database
import mimir.algebra._
import mimir.ctables.OperatorDeterminism
import mimir.util._
import org.joda.time.LocalDate
import com.typesafe.scalalogging.LazyLogging

import scala.collection.JavaConversions._
import scala.collection.{immutable, mutable}
import scala.collection.mutable.ListBuffer
import mimir.provenance.Provenance

class SqlToRA(db: Database)
  extends LazyLogging
{
  import SqlToRA._

  def apply(v: sparsity.statement.Statement): Operator =
    v match {
      case sel: sparsity.statement.Select => convertSelect(sel)._1
      case _ => throw new SQLException(s"Not a Query: $v")
    }
  def apply(v: sparsity.statement.Select): Operator = convertSelect(v)._1
  def apply(v: sparsity.select.SelectBody): Operator = convertSelectBody(v)._1
  def apply(v: sparsity.expression.PrimitiveValue): PrimitiveValue = SqlToRA(v)
  def apply(v: sparsity.expression.Expression): Expression = SqlToRA(v)
  def apply(v: sparsity.expression.Expression,
            bindings: (Column => MimirAttribute)): Expression = SqlToRA(v, bindings)

  def convertSelect(
    s : sparsity.statement.Select,
    alias: Option[TableName] = None
  ) : (Operator, Seq[(SparsityAttribute, MimirAttribute)]) = {
    convertSelectBody(s.body, alias)
  }

  /**
   * Convert a PlainSelect into an Operator + A projection map.
   */
  def convertSelectBody(
    select: sparsity.select.SelectBody,
    tableAlias: Option[TableName] = None
  ) : (Operator, Seq[(SparsityAttribute, MimirAttribute)]) =
  {
    // Start with an empty table.  The following variable will be incrementally
    // built up over the course of this function
    var ret:Operator = HardTable(Seq(),Seq())

    logger.debug(s"Converting query: $select")

    //////////////////////// CONVERT FROM CLAUSE /////////////////////////////
    val fromClauses   = select.from.map { convertFromElement(_) }
    val fromOperators = fromClauses.map { _._1 }
    val fromSchemas   = fromClauses.flatMap { _._2 }

    // If there are from elements, we use those instead of the
    // blank table.
    if(!fromOperators.isEmpty){
      ret = fromOperators
              .tail
              .fold(fromOperators.head)
                   { Join(_, _) }
    } else {
      logger.trace("No FROM items.  Using an empty table")
    }

    // Unlike SQL, Mimir's relational algebra does not use range variables.  Rather,
    // variables are renamed into the form TABLENAME_VAR to prevent name conflicts.
    // Because SQL allows variables without a matching range variable, we need to keep
    // track of the variable's "base" name (without alias) and a mapping back to the
    // variable's real name.
    //
    // The following variable facilitates this conversion
    //
    // Bindings: A map from the base name to the extended name (or an arbitrary
    //           name, if there are multiple source tables with the same variable)
    val fromSchemaLookup = NameLookup(fromSchemas)
    val bindings = lookupColumn(_:Column, fromSchemaLookup)

    //////////////////////// CONVERT WHERE CLAUSE /////////////////////////////

    // This one's super simple.  The where clause just becomes a Select on top
    // of the return value.
    select.where match {
      case Some(where) =>
        ret = Select(
          convertExpression(where, bindings),
          ret
        )
      case None => ()
    }

    //////////////////// CONVERT SORT AND LIMIT CLAUSES ///////////////////////

    // Sort and limit are an odd and really really really annoying case, because of
    // how they interact with aggregate and non-aggregate queries.
    //
    // - For non-aggregate queries, SORT and LIMIT get applied BEFORE projection.
    //     - This is actually not entirely true... some SQL variants allow you to
    //       use names in both the target and source columns...  eeeew
    // - For aggregate queries, SORT and LIMIT get applied AFTER aggregation.
    //
    // Because they could get applied in either of two places, we don't actually
    // do the conversion here.  Instead we define the entire conversion in one
    // place (here), wrapped in a function that gets called at the right place
    // below, once we figure out whether we're dealing with an aggregate or
    // flat query.
    //
    val applySortAndLimit =
    (sortBindings:(Column => MimirAttribute)) => {
      if(!select.orderBy.isEmpty){
        ret = Sort(
          select.orderBy.map { ob => SortColumn(
            convertExpression(ob.expression, sortBindings),
            ob.ascending
          )},
          ret
        )
      };
      if(!select.offset.isEmpty || !select.limit.isEmpty) {
        ret = Limit(
          select.offset.getOrElse(0),
          select.limit,
          ret
        )
      }
    }

    //////////////////////// CONVERT SELECT TARGETS /////////////////////////////

    // Utility function to compute expansions for table wildcard
    // targets (i.e., table.*).
    // Returns a 2-tuple:
    //   t._1 : The base name of the variable in the output.
    //   t._2 : The expression of the variable in the input.
    // Some examples:
    //   SELECT A FROM R
    //     -> ("A", Var("A"))
    //   SELECT A AS B FROM R
    //     -> ("B", Var("A"))
    val defaultTargetsForTable:(TableName => Seq[(SparsityAttribute, sparsity.expression.Expression)]) =
      (table: TableName) => {
        fromSchemas.find { _._1.equals(table) }
                   .get._2
                   .toSeq
                   .map { case (name, id) => (name, sparsity.expression.Column(name, Some(table)):sparsity.expression.Expression) }
      }

    // Start by converting to Mimir expressions and expanding clauses
    // Follows the same pattern as the utility function above
    val baseTargets: Seq[(SparsityAttribute, sparsity.expression.Expression)] =
      select.target.flatMap({
        case se@SelectExpression(expr, _) => {
          // Come up with a name for the expression
          // Note, this doesn't need to be unique (yet).  We assign unique
          // names in a post-processing step
          val alias: SparsityAttribute = SqlUtils.getAlias(se);
          Some( (alias, expr) )
        }

        case SelectAll() =>
          fromSchemas.flatMap { case (table, attrs) => attrs.toSeq.map {
            case (name, id) => (name, sparsity.expression.Column(name, Some(table)):sparsity.expression.Expression)
          }}

        case SelectTable(table) =>
          defaultTargetsForTable(table)
      })

    // After wildcard expansion, do some post-processing on the targets.
    // First, it's possible that the aliases assigned here might contain
    // duplicates.  Make sure that all of the aliases have unique names
    val uniqueAliases:Seq[SparsityAttribute] =
      SqlUtils.makeAliasesUnique(baseTargets.map(_._1))

    val targetsWithUniqueAliases:Seq[(SparsityAttribute, SparsityExpression)] =
      uniqueAliases.zip(baseTargets.map(_._2))

    // We're also responsible for assigning a globally visible name based
    // on the table alias (if it's present), and retaining a mapping back
    // to the original name.  To do this, we need to create the global
    // name by prepending the table alias we've been given.  The globally
    // visible schema is what the ProjectArgs should use.
    val targets: Seq[(SparsityAttribute, MimirAttribute, SparsityExpression)] =
      tableAlias match {
        case None =>
          // No table alias given.  The globally visible alias is just the one we picked
          targetsWithUniqueAliases.map({ case (alias, expr) =>
                                            (alias, ID.upper(alias), expr) })
        case Some(tableAlias) =>
          // Table alias exists.  The globally visible alias needs the table name prepended
          targetsWithUniqueAliases.map({ case (alias, expr) =>
                                            (alias, ID(ID.upper(tableAlias),"_",ID.upper(alias)), expr) })
      }

    // Check if this is an Aggregate Select or Flat Select
    // This is an Aggregate Select if ...
    //   ... any target column references an aggregate function
    //   ... there is a group by clause
    //   ... there is a having clause
    val containsAggregates = targets.map { _._3 }.exists { SqlUtils.expressionContainsAggregate(_, db.aggregates) }
    val hasGroupByRefs     = select.groupBy != None
    val hasHavingClause    = select.having != None
    val isAggSelect = hasGroupByRefs || hasHavingClause || containsAggregates

    if(!isAggSelect){
      // NOT an aggregate select.

      // Apply the sort and limit clauses before the projection if necessary
      applySortAndLimit(bindings)

      // Create a simple projection around the return value.
      ret =
        Project(
          targets.map({
            case (baseName, extendedName, inputExpr) =>
              ProjectArg(
                extendedName,
                convertExpression(inputExpr, bindings)
              )
          }),
          ret
        )
    } else {
      // This is an aggregate select.

      // It's legitimate SQL to write an aggregate query with a
      // post-processing projection.  For example:
      // SELECT A + SUM(B) FROM R GROUP BY A
      // is entirely acceptable.
      //
      // Below, we've defined a function that segments this larger
      // expression, extracting the post-processing step:
      //   (A + TMP)
      // And returning the set of actual aggregates that we need
      // to compute:
      //   TMP -> SUM(B)

      val fragmentedTargets =
        targets.map( tgt => fragmentAggregateExpression(tgt._3, tgt._2.withPrefix("MIMIR_AGG_"), bindings ) )

      val (targetPostProcExprs, perTargetGBVars, perTargetAggExprs) =
        fragmentedTargets.unzip3

      // The full set of referenced group by variables
      var referencedGBVars: Set[Var] = perTargetGBVars.flatten.toSet

      // The full list of aggregate expressions we need to compute
      var allAggFunctions =
        perTargetAggExprs.flatten
          .map({ case (aggName, distinct, args, alias) =>
            AggFunction(aggName, distinct, args.map { convertExpression(_, bindings) }, alias)
          })

      // And pull out the list of group by variables that the user has declared for
      // this expression
      val declaredGBColumns: Seq[(TableName, Column)] =
        select.groupBy
              .toSeq
              .flatten
              .map {
                case col:Column => {
                  val completedColumn = populateColumnTable(col, fromSchemaLookup)
                  (completedColumn.table.get, completedColumn)
                }
                case _ => unhandled("GroupBy[Expression]")
              }

      val preAggregateGroupByColumnSchema:Map[TableName, Bindings] =
        declaredGBColumns.groupBy { _._1 }
                         .mapValues { _.map { case (table, col) =>
                                        col.column -> bindings(col)
                                      } }
                         .mapValues { NameLookup(_) }

      val postAggregateGroupByColumnSchema:Map[TableName, Bindings] =
        declaredGBColumns.groupBy { _._1 }
                         .mapValues { _.map { case (table, col) =>
                                        col.column -> ID.upper(col.column)
                                      } }
                         .mapValues { NameLookup(_) }

      logger.trace(s"Pre-Aggregate Group By Column Schema: $preAggregateGroupByColumnSchema")
      logger.trace(s"Post-Aggregate Group By Column Schema: $postAggregateGroupByColumnSchema")

      // Column names in the output schema
      val targetNames = targets.map( _._2 )

      // Schema and lookup operations for the post-projection aggregate query.
      // e.g., for SELECT A, SUM(B) AS C FROM R
      // should allow lookups for A, R.A, and C
      //
      // This is used in two places: For interpreting (some types) of HAVING
      // clauses (see below for the insanity) and for interpreting ORDER BY clauses
      val postAggregateSchema:TableBindings =
        NameLookup(Map(
          sparsity.Name("__AGGREGATE") -> NameLookup(targets.map { case (sparsity, mimir, _) => (sparsity, mimir) })
        ) ++ postAggregateGroupByColumnSchema)

      val postAggregateBindings = lookupColumn(_:Column, postAggregateSchema)

      // The having clause.  "Some" if there is one, "None" if not.
      // The Boolean is TRUE if the having expression is applied to the
      // post-aggregate schema and FALSE if applied to the pre-aggregate schema
      val havingExprAndIsPostAgg: Option[(Expression, Boolean)] =
        select.having.map { having =>
          // SQL is Ugh...
          // HAVING can be interpreted in one of two ways: Either it applies
          // to the output of the SELECT (i.e., referencing variables in the
          // output schema of the aggregate), or it can define new aggregate
          // values.  Worse, the signaling about which is which is fairly weak
          //
          // We adopt a pragmatic approach: If you use an aggregate function
          // in the HAVING clause, we assume it uses the pre-aggregate schema.
          // Otherwise it's the post-aggregate schema.

          // Our first attempt at conversion: A post-aggregate
          val postAggregateHavingExpr: Option[Expression] =
            // Either the expression contains an aggregate, in which case we
            // fail over to the post-aggregate case.  Alternatively the conversion could
            // also fail due to missing bindings.  In this case, we also try to
            // parse the expression pre-aggregate style before giving up.
            //
            // TODO: A cleaner version of this code would be to first check to
            // see if any post-aggregate variables are used.
            try {
              if(SqlUtils.expressionContainsAggregate(having, db.aggregates)){ None }
              else { Some(convertExpression(having, postAggregateBindings)) }
            } catch { case e: SQLException => None }

          // At this point, if `postAggregateHavingExpr` has something, then
          // it's safe to convert it directly.  Otherwise, we need to do some
          // finagling to create temporary attributes in the aggregate.
          postAggregateHavingExpr match {
            case Some(havingExpr) => (havingExpr, true)

            case None => {
              // If we're here, it means that we're dealing with a pre-aggregate
              // HAVING expression.  Use the original bindings to convert the
              // expression.  If this fails, the SQL actually does have an error.
              val (havingPostExpression, havingGBVars, havingAggExprs) =
                fragmentAggregateExpression(having, ID("MIMIR_HAVING"), bindings)

              // Tack on the newly generated aggregate expressions
              referencedGBVars = referencedGBVars ++ havingGBVars
              allAggFunctions = allAggFunctions ++
                havingAggExprs.map({ case (aggName, distinct, args, alias) =>
                  AggFunction(aggName, distinct, args.map { convertExpression(_, bindings) }, alias)
                })

              val havingSchema:TableBindings = NameLookup(Map(
                sparsity.Name("__HAVING") -> NameLookup(havingAggExprs.map { case (_, _, _, alias) => alias.quoted -> alias })
              ) ++ preAggregateGroupByColumnSchema)
              val havingBindings = lookupColumn(_:Column, havingSchema)

              // And then the PostExpression is what we want to use in the
              // Select() that gets attached to the query.
              /* return */ (convertExpression(havingPostExpression, havingBindings), false)
            }
          }

        }

      val declaredGBVars = declaredGBColumns.map { case (_, col) => Var(bindings(col)) }
      // Sanity Check: We should not be referencing a variable that's not in the GB list.
      val referencedNonGBVars = referencedGBVars -- declaredGBVars
      if(!referencedNonGBVars.isEmpty){
        throw new SQLException(s"Variables $referencedNonGBVars not in group by list")
      }

      val interAggregateSchema:TableBindings = NameLookup(Map(
        sparsity.Name("__AGGREGATE") ->
          NameLookup(allAggFunctions.map { fn => fn.alias.quoted -> fn.alias })
      ) ++ preAggregateGroupByColumnSchema)
      val interAggregateBindings = lookupColumn(_:Column, interAggregateSchema)

      // Assemble the Aggregate
      ret = Aggregate(declaredGBVars, allAggFunctions, ret)

      // Generate the post-processing projection targets
      val postProcTargets =
        targetNames.zip(targetPostProcExprs).
          map( tgt => ProjectArg(tgt._1, convertExpression(tgt._2, interAggregateBindings)) )

      // If the having clause is applied to the pre-aggregate schema,
      // then we need to apply it before projecting down to the post-aggregate
      // schema.
      havingExprAndIsPostAgg match {
        case Some( (havingExpr, false) ) => {
          ret = Select(havingExpr, ret)
        }
        case _ => ()
      }

      // Assemble the post-processing Project
      ret = Project(postProcTargets, ret)

      // If the having clause is applied to the post-aggregate schema,
      // then we need to apply it after projecting down to the post-aggregate
      // schema.
      havingExprAndIsPostAgg match {
        case Some( (havingExpr, true) ) => {
          ret = Select(havingExpr, ret)
        }
        case _ => ()
      }

      logger.trace(s"Bindings after aggregate: $postAggregateSchema")
      // Apply sort and limit if necessary
      applySortAndLimit(postAggregateBindings)
    } // end Aggregate Select case

    //////////////////////////// Convert Distinct /////////////////////////////
    if(select.distinct) {
      ret = ret.distinct
    }

    // We're responsible for returning bindings for this specific
    // query, so extract those from the target expressions we
    // produced earlier
    val returnedBindings =
      targets.map( tgt => (tgt._1, tgt._2) )

    // The base operator should now be fully assembled.  Recur into any
    // unions if necessary and return.
    select.union match {
      case Some( (t, rhs) ) => {
        val (rhsOper, rhsBindings) = convertSelectBody(rhs, tableAlias)

        //TODO: Check that returnedBindings == rhsBindings

        ret = Union(ret, rhsOper)
        t match {
          case sparsity.select.Union.Distinct => ret = ret.distinct
          case sparsity.select.Union.All      => ()
        }
      }
      case None => ()
    }

    return (ret, returnedBindings)
  }

  def convertFromElement(
    from : FromElement
  ) : (Operator, Seq[(TableName, Bindings)]) =
    from match {
      case FromSelect(query, alias) => {
        val (ret, bindings) = convertSelectBody(query, Some(alias))
        (
          ret,
          Seq(alias -> NameLookup(bindings))
        )
      }
      case FromTable(schemaMaybe, table, aliasMaybe) => {
        val alias = aliasMaybe.getOrElse(table)
        val tableOp:Operator =
          schemaMaybe match {
            case None => db.catalog.tableOperator(table)
            case Some(source) => db.catalog.tableOperator(source, table)
          }
        val bindings = NameLookup(
          tableOp.columnNames.map { col =>
            sparsity.Name(col.id) -> ID(ID.upper(alias), "_", col)
          }
        )
        val rewrites =
          tableOp.columnNames.map { col =>
            ID(ID.upper(alias), "_", col) -> Var(col)
          }
        logger.trace(s"From Table: $table( $rewrites )")
        (
          tableOp.mapByID( rewrites:_* ),
          Seq(alias -> bindings)
        )
      }
      case FromJoin(lhsFrom, rhsFrom, t, onClause, aliasMaybe) => {
        val (lhs, lhsSchema) = convertFromElement(lhsFrom)
        val (rhs, rhsSchema) = convertFromElement(rhsFrom)
        val columnBindings = (lhsSchema++rhsSchema).map { _._2 }
                                                   .flatMap { _.toSeq }
        val onExpr = convertExpression(onClause, lookupColumn(_:Column, NameLookup(lhsSchema ++ rhsSchema)))
        val joinOp =
          t match {
            case SparsityJoin.Inner =>
              lhs.join(rhs).filter { onExpr }
            case SparsityJoin.LeftOuter =>
              LeftOuterJoin(lhs, rhs, onExpr)
            case SparsityJoin.RightOuter =>
              LeftOuterJoin(rhs, lhs, onExpr)
            case SparsityJoin.FullOuter =>
              unhandled("FromElement[FullOuterJoin]")
            case SparsityJoin.Natural => {
              val lhsAttrs = lhsSchema
                                .map { _._2 }
                                .fold(NameLookup())( _ ++ _ )
              val rhsAttrs = rhsSchema
                                .map { _._2 }
                                .fold(NameLookup())( _ ++ _ )
              val joinAttrs = lhsAttrs.keySet & rhsAttrs.keySet
              val joinExpression = ExpressionUtils.makeAnd(
                joinAttrs.map { attr =>
                  val lhsVar = Var(lhsAttrs(attr).get)
                  val rhsVar = Var(rhsAttrs(attr).get)
                  lhsVar.eq(rhsVar)
                } + onExpr
              )
              lhs.join(rhs).filter(joinExpression)
            }
          }

        aliasMaybe match {
          case None =>
            (
              joinOp,
              lhsSchema ++ rhsSchema
            )
          case Some(alias) => {
            val newBindings =
              joinOp.columnNames.map { col => sparsity.Name(col.id) -> ID(ID.upper(alias), "_", col) }
            val rewrites =
              columnBindings.map { case (_, id) => ID(ID.upper(alias), "_", id) -> Var(id) }
            (
              joinOp.mapByID( rewrites:_* ),
              Seq(alias -> NameLookup(newBindings))
            )
          }
        }
      }

    }

  def lookupColumnInTableBindings(
    c: Column,
    bindings: Bindings
  ): MimirAttribute =
  {
    bindings(c.column) match {
      case Some(columnBinding) => columnBinding
      case None => {
        val tableColumns = bindings.keys.map { col => Column(col, c.table) }
        throw new SQLException(s"No such column `$c` out of ${tableColumns.mkString(", ")}")
      }
    }
  }

  def populateColumnTable(
    c: Column,
    bindings: TableBindings
  ): Column =
  {
    c.table match {
      case Some(_) => return c
      case None => {
        for( (table, tableBindings) <- bindings.all ){
          if(tableBindings.hasKey(c.column)){
            return Column(c.column, Some(table))
          }
        }
        val allColumns = NameLookup.merge(bindings.values).keys.map { col => Column(col, c.table) }
        throw new SQLException(s"No such column `${c.column}` out of ${allColumns.mkString(", ")}")
      }
    }
  }

  def lookupColumn(
    c: Column,
    bindings: TableBindings
  ): MimirAttribute =
  {
    c.table match {
      case Some(table) => {
        bindings( table ) match {
          case Some(tableBindings) =>
            lookupColumnInTableBindings(c, tableBindings)
          case None =>
            throw new SQLException(s"No such table `$table` out of ${bindings.keys.mkString(", ")}")
        }
      }
      case None => {
        lookupColumnInTableBindings(
          c,
          NameLookup.merge(bindings.values)
        )
      }
    }
  }

  /**
   * Split an aggregate target expression into its component parts.
   *
   * This is needed to handle complex aggregate expressions.
   * For example (if X is a group-by var):
   * > X + SUM(Y) / COUNT(*) AS FOO
   * This expression will return:
   * > X + (FOO_1_0 / FOO_1_1)
   * > [X]
   * > [(SUM, [Y], FOO_1_0), (COUNT, [], FOO_1_1)]
   *
   * In short, this function descends through the expression tree
   * and picks out all aggregates and var leaves that it hits.
   *
   * Aggregate expressions are removed from the nested expression
   * and replaced by unique placeholder variables (as long as
   * alias is a unique prefix), and the entire expression is
   * reassembled.
   *
   * - Raw Variables are returned in the second tuple element
   * - Aggregates are returned in the third tuple element
   *
   * Unique placeholder variables are assigned unique names based
   * on the path through the operator tree.
   */
  def fragmentAggregateExpression(
    expr: sparsity.expression.Expression,
    alias: MimirAttribute,
    bindings: (Column => MimirAttribute)
  ): (
    SparsityExpression,                                      // The wrapper expression
    Set[Var],                                                // Referenced Group-By Variables
    Seq[(ID,Boolean,Seq[SparsityExpression],MimirAttribute)] // Referenced Expressions (fn, distinct, args, alias)
  ) =  {
    logger.debug(s"Fragmenting: $alias <- $expr")
    val recur = () => {
      val fragmentedChildren =
        expr.children.zipWithIndex.
          map { case (child, index) =>
                  fragmentAggregateExpression(child, ID(alias,"_"+index), bindings) }

      val (childExprs, childGBVars, childAggs) =
        fragmentedChildren.unzip3

      (
        expr.rebuild(childExprs),
        childGBVars.flatten.toSet,
        childAggs.flatten
      )
    }

    expr match {
      case c:Column =>
        (
          c,
          Set(Var(bindings(c))),
          List()
        )

      case SparsityFunction(function, args, distinct)
            if distinct || db.aggregates.isAggregate(ID.lower(function))
          =>
        (
          Column(alias.quoted, None),
          Set(),
          Seq((
            ID.lower(function),
            distinct,
            args.toSeq.flatten,
            alias
          ))
        )

      case _ => recur()
    }
  }

}

object SqlToRA
  extends LazyLogging
{

  type TableName             = sparsity.Name
  type SparsityAttribute     = sparsity.Name
  type MimirAttribute        = ID
  type Bindings              = NameLookup[MimirAttribute]
  type TableBindings         = NameLookup[Bindings]
  type SourceSchema          = Seq[(TableName, Seq[MimirAttribute])]

  def apply(v: sparsity.expression.PrimitiveValue): PrimitiveValue = convertPrimitive(v)
  def apply(v: sparsity.expression.Expression): Expression = convertExpression(v, Map())
  def apply(v: sparsity.expression.Expression,
            bindings: (Column => MimirAttribute)): Expression = convertExpression(v, bindings)

  def unhandled(feature : String) = {
    println("ERROR: Unhandled Feature: " + feature)
    throw new SQLException("Unhandled Feature: "+feature)
  }

  def literalBindings(x:Column) = ID.upper(x.column)

  //
  def convertPrimitive(e: SparsityPrimitive) : PrimitiveValue =
  {
    e match {
      case SparsityLong(v)   => return IntPrimitive(v)
      case SparsityDouble(v) => return FloatPrimitive(v)
      case SparsityString(v) => return StringPrimitive(v)
      case SparsityBool(v)   => return BoolPrimitive(v)
      case SparsityNull()    => return NullPrimitive()
    }
  }

  def convertExpression(
    e : sparsity.expression.Expression,
    bindings: (Column => MimirAttribute)
  ) : Expression = {
    e match {
      case prim: SparsityPrimitive => convertPrimitive(prim)
      case SparsityNot(child) =>
        return Not(convertExpression(child, bindings))
      case SparsityComparison(lhs, op, rhs) =>
        Comparison(op, convertExpression(lhs, bindings),
                       convertExpression(rhs, bindings))
      case SparsityArithmetic(lhs, op, rhs) =>
        Arithmetic(op, convertExpression(lhs, bindings),
                       convertExpression(rhs, bindings))

      case col:Column => Var(bindings(col))

      case SparsityFunction(rawName, Some(args), false) =>
        // Special-case some function conversions
        (ID.lower(rawName), args) match {
          case (ID("rowid"), Seq()) =>
            RowIdVar()
          case (ID("rowid"), Seq(x:SparsityPrimitive)) =>
            RowIdPrimitive(convertPrimitive(x).asString)
          case (ID("mimir_vgterm"), args) => {
            args.take(2) match {
              case Seq(model:Column, idx:SparsityPrimitive) =>
                VGTerm(
                  ID(model.column.name),
                  convertPrimitive(idx).asLong.toInt,
                  args.tail.tail.map { convertExpression(_, bindings) },
                  Seq()
                )
            }
          }
          case (name, _) =>
            Function(name,
              args.map {
                convertExpression(_, bindings)
              }
            )
        }

      case SparsityFunction(_, _, _) =>
        throw new SQLException("Error: Can't interpret aggregate function in normal expression")

      case SparsityCast(target, t) =>
        CastExpression(
          convertExpression(target, bindings),
          Type.fromString(t.lower)
        )

      case InExpression(targetRaw, Left(options)) =>
        val target = convertExpression(targetRaw, bindings)
        ExpressionUtils.makeOr(
          options.map { convertExpression(_, bindings) }
                 .map { Comparison(Cmp.Eq, target, _) }
        )

      case InExpression(targetRaw, Right(query)) =>
        unhandled("InExpression[Query]")

      case CaseWhenElse(targetRaw, whenClauses, elseClause) => {
        val inlineSwitch: Expression => Expression =
          targetRaw match {
            case None => (x => x)
            case Some(target) => Comparison(Cmp.Eq, convertExpression(target, bindings), _)
          }
        return ExpressionUtils.makeCaseExpression(
          whenClauses.map { case (condition, thenClause) =>
            (
              inlineSwitch(convertExpression(condition, bindings)),
              convertExpression(thenClause, bindings)
            )
          },
          convertExpression(elseClause, bindings)
        )
      }

      case SparsityIsNull(target) =>
        IsNullExpression( convertExpression(target, bindings) )

    }
  }

}


text:
namespace {

bool HasValidWindowsPrefetchArgument(const base::CommandLine& command_line) {
  const base::char16 kPrefetchArgumentPrefix[] = L"/prefetch:";

  for (const auto& arg : command_line.argv()) {
    if (arg.size() == arraysize(kPrefetchArgumentPrefix) &&
        base::StartsWith(arg, kPrefetchArgumentPrefix,
                         base::CompareCase::SENSITIVE)) {
      return arg[arraysize(kPrefetchArgumentPrefix) - 1] >= L'1' &&
             arg[arraysize(kPrefetchArgumentPrefix) - 1] <= L'8';
    }
  }
  return false;
}

int RunFallbackCrashHandler(const base::CommandLine& cmd_line) {
  // Retrieve the product & version details we need to report the crash
  // correctly.
  wchar_t exe_file[MAX_PATH] = {};
  CHECK(::GetModuleFileName(nullptr, exe_file, arraysize(exe_file)));

  base::string16 product_name;
  base::string16 version;
  base::string16 channel_name;
  base::string16 special_build;
  install_static::GetExecutableVersionDetails(exe_file, &product_name, &version,
                                              &special_build, &channel_name);

  return crash_reporter::RunAsFallbackCrashHandler(
      cmd_line, base::UTF16ToUTF8(product_name), base::UTF16ToUTF8(version),
      base::UTF16ToUTF8(channel_name));
}

}  // namespace
#endif  // defined(OS_WIN)

#if defined(OS_MACOSX)
extern "C" {
__attribute__((visibility("default")))
int ChromeMain(int argc, const char* argv[]);
}
#endif  // OS_MACOSX

#if defined(OS_WIN)
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE, wchar_t* cmd, int) {
  int argc = 0;
  wchar_t** argv_setup = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
  base::CommandLine::Init(0, nullptr);

  install_static::InitializeFromPrimaryModule();
#else  // OS_WIN
#if defined(OS_MACOSX)
int ChromeMain(int argc, const char* argv[]) {
#else  // OS_MACOSX
int main(int argc, const char* argv[]) {
#endif
  char** argv_setup = uv_setup_args(argc, const_cast<char**>(argv));
  base::CommandLine::Init(argc, argv_setup);
#endif  // OS_WIN
  int64_t exe_entry_point_ticks = 0;
  // const base::TimeTicks exe_entry_point_ticks = base::TimeTicks::Now();

  const base::CommandLine* command_line =
      base::CommandLine::ForCurrentProcess();

  std::unique_ptr<base::Environment> environment(base::Environment::Create());
  base::FilePath user_data_dir;

  std::string user_data_dir_string;
  if (environment->GetVar("CHROME_USER_DATA_DIR", &user_data_dir_string) &&
      base::IsStringUTF8(user_data_dir_string)) {
    user_data_dir = base::FilePath::FromUTF8Unsafe(user_data_dir_string);
  } else if (command_line->HasSwitch(switches::kUserDataDir)) {
    user_data_dir = command_line->GetSwitchValuePath(switches::kUserDataDir);
  } else {
#if defined(OS_WIN) || defined(OS_MACOSX)
    base::PathService::Get(base::DIR_APP_DATA, &user_data_dir);
#else
    user_data_dir = base::nix::GetXDGDirectory(environment.get(),
                                  base::nix::kXdgConfigHomeEnvVar,
                                  base::nix::kDotConfigDir);
#endif
    if (command_line->HasSwitch(atom::options::kUserDataDirName)) {
      user_data_dir = user_data_dir.Append(
          command_line->GetSwitchValuePath(atom::options::kUserDataDirName));
    } else {
#if defined(OS_MACOSX)
      if (!chrome::GetDefaultUserDataDirectory(&user_data_dir))
        user_data_dir = user_data_dir.Append(FILE_PATH_LITERAL("brave"));
#else
      user_data_dir = user_data_dir.Append(FILE_PATH_LITERAL("brave"));
#endif
    }
  }
  base::PathService::Override(chrome::DIR_CRASH_DUMPS,
      user_data_dir.Append(FILE_PATH_LITERAL("CrashPad")));
  environment->SetVar("CHROME_USER_DATA_DIR", user_data_dir.AsUTF8Unsafe());

#if defined(OS_WIN)
  SignalInitializeCrashReporting();

  const std::string process_type =
      command_line->GetSwitchValueASCII(switches::kProcessType);

  // Confirm that an explicit prefetch profile is used for all process types
  // except for the browser process. Any new process type will have to assign
  // itself a prefetch id. See kPrefetchArgument* constants in
  // content_switches.cc for details.
  DCHECK(process_type.empty() ||
         HasValidWindowsPrefetchArgument(*command_line));

  if (process_type == crash_reporter::switches::kCrashpadHandler) {
    crash_reporter::SetupFallbackCrashHandling(*command_line);
    return crash_reporter::RunAsCrashpadHandler(
        *base::CommandLine::ForCurrentProcess(), user_data_dir,
        switches::kProcessType, switches::kUserDataDir);
  } else if (process_type == crash_reporter::switches::kFallbackCrashHandler) {
    return RunFallbackCrashHandler(*command_line);
  }

  // Signal Chrome Elf that Chrome has begun to start.
  SignalChromeElf();

  // Initialize the sandbox services.
  sandbox::SandboxInterfaceInfo sandbox_info = {0};
  const bool is_browser = process_type.empty();
  const bool is_sandboxed =
      !command_line->HasSwitch(service_manager::switches::kNoSandbox);
  if (is_browser || is_sandboxed) {
    // For child processes that are running as --no-sandbox, don't initialize
    // the sandbox info, otherwise they'll be treated as brokers (as if they
    // were the browser).
    content::InitializeSandboxInfo(&sandbox_info);
  }

#endif
  atom::AtomMainDelegate chrome_main_delegate(
      base::TimeTicks::FromInternalValue(exe_entry_point_ticks));
  content::ContentMainParams params(&chrome_main_delegate);

#if defined(OS_WIN)
  // The process should crash when going through abnormal termination.
  base::win::SetShouldCrashOnProcessDetach(true);
  base::win::SetAbortBehaviorForCrashReporting();
  params.instance = instance;
  params.sandbox_info = &sandbox_info;

  // Pass chrome_elf's copy of DumpProcessWithoutCrash resolved via load-time
  // dynamic linking.
  base::debug::SetDumpWithoutCrashingFunction(&DumpProcessWithoutCrash);

  atom::AtomCommandLine::InitW(argc, argv_setup);
#else
  params.argc = argc;
  params.argv = argv;
  atom::AtomCommandLine::Init(argc, argv_setup);
#endif  // defined(OS_WIN)

  int rv = content::ContentMain(params);

#if defined(OS_WIN)
  base::win::SetShouldCrashOnProcessDetach(false);
#endif

  return rv;
}