text:
* Added a tvOS target in the Example project.
* Carthage should now see the tvOS framework

## 4.0.0

### Breaking changes

* The method `static func loadFromNib(owner:)` of `NibOwnerLoadable` has been replaced by instance method `func loadNibContent()`.
  This is more consistent as we need an instance (owner) anyway, and also avoids possible crashes when used with `UIView` subclasses
  not implementing non-required initializers `init()`/`init(frame:)`.
  _(Method `static func loadFromNib()` of `NibLoadable` is still unchanged)_.
  [@Skoti](https://github.com/Skoti)
  [#40](https://github.com/AliSoftware/Reusable/pull/40)
* The `storyboard` property of `StoryboardBased` and `StoryboardSceneBased` protocols has been renamed to `sceneStoryboard` to avoid conflicts.
  [@jakubgert](https://github.com/jakubgert)
  [#33](https://github.com/AliSoftware/Reusable/pull/33)

### Fixes

* Fixing documentation typos for `CollectionHeaderView` and `MyXIBIndexSquaceCell`.
  [@Skoti](https://github.com/Skoti)

* Fixing TableView Controller scene in Example project, to display cells above `UITabBar`.
  [@Skoti](https://github.com/Skoti)

## 3.0.1

### Bug Fixes

* Fix `instantiate()` implementation on `StoryboardSceneBased` ViewControllers.
  [@jakubgert](https://github.com/jakubgert)
  [#38](https://github.com/AliSoftware/Reusable/pull/38)
* Removed strict `NibReusable` protocol conforming in `register` functions.
  You can now make a `Reusable`-only cell with a `NibLoadable` subclass.
  [@nekrich](https://github.com/nekrich)
  [#37](https://github.com/AliSoftware/Reusable/pull/37)

## 3.0.0

### Breaking Changes

* Converted library and Demo project to Swift 3.
    ⚠ The following methods have new signatures:
    - `dequeueReusableCell(indexPath:)` is now `dequeueReusableCell(for:)`
    - `dequeueReusableCell(indexPath:cellType:)` is now `dequeueReusableCell(for:cellType:)`
    - `registerReusableCell(_:)` is now `register(cellType:)`
    - `registerReusableHeaderFooterView(_:)` is now `register(headerFooterViewType:)`
    - `registerReusableSupplementaryView(_:viewType:)` is now `register(supplementaryViewType:ofKind:)`
    - `dequeueReusableSupplementaryView(_:indexPath:viewType:)` is now `dequeueReusableSupplementaryView(ofKind:for:viewType:)`
  [@phatblat](https://github.com/phatblat)
  [#30](https://github.com/AliSoftware/Reusable/pull/30)
  [@ceyhuno](https://github.com/ceyhuno)
  [#31](https://github.com/AliSoftware/Reusable/pull/31)

## 2.5.1

* Adapted source files and demo project for Swift 2.3
  [@antondomashnev](https://github.com/Antondomashnev)
  [#16](https://github.com/AliSoftware/Reusable/pull/28)

## 2.5.0

* Added the possibility for `NibOwnerLoadable` confirming custom views to pass an existing instance as `owner`
  (used as the File's Owner) in case one already exists. This is especially useful to implement `init(coder:)`
  to load the content of the XIB as subviews of `self` after initialization. See `MyCustomWidget.swift` for an example.
  [@AliSoftware](https://github.com/AliSoftware)

## 2.4.0

* Added `StoryboardBased` and `StoryboardSceneBased` protocols for storyboard based `UIViewController` easy instantiation.
  [@AliSoftware](https://github.com/AliSoftware)

## 2.3.0

* Added ` NibOwnerLoadable` protocol for `UIView` set as XIB's File's Owner.
  [@PoissonBallon](https://github.com/PoissonBallon)
  [#16](https://github.com/AliSoftware/Reusable/pull/16)

_While the `NibLoadable` protocol is adapted to views loaded from XIB but that are set as the root view of the XIB,
this new `NibOwnerLoadable` protocol is adapted to view loaded from XIB too, but that are set as the XIB's File's Owner._

## 2.2.1

* Fixed issue with `register…` methods registering the superclass `T` instead of the dynamic class `cellType` / `viewType`.
  [@narirou](https://github.com/narirou)
  [#13](https://github.com/AliSoftware/Reusable/pull/13)

## 2.2.0

* Added optional `viewType` & `cellType` parameters to the dequeue functions.
  [@k3zi](https://github.com/k3zi)
  [#11](https://github.com/AliSoftware/Reusable/pull/11)

This parameter is only needed if you can't write `… as MyCell` (to let Swift infer the cell type from the return type),
which might be the case for example when your cell class is stored in a variable:

```swift
let cellType: Any.Type = self.cellTypeForIndexPath(indexPath)
// Can't do this in this case (because cellType is a variable):
let cell = tableView.dequeueReusableCell(indexPath: indexPath) as cellType ❌ // compiler error
// But now we can use that alternate way for such cases:
let cell = tableView.dequeueReusableCell(indexPath: indexPath, cellType: cellType)
```

But if you know the type at compile time, you can omit the `cellType` parameter and still do this, letting the return type infer it for you:

```swift
let cell = tableView.dequeueReusableCell(indexPath: indexPath) as MyCell
```

## 2.1.1

* Made every method `final` to allow more optimizations.
  [@AliSoftware](https://github.com/AliSoftware)

* Banned the use of `as!` in the source code in favour of `guard let x = y else { fatalError(…) }`.
  This avoids force-casts (which are considered bad practice) and generate a more explicit fatal error in case the developer forgot something (typically forgot to set the reuseIdentifier in IB).
  [@AliSoftware](https://github.com/AliSoftware)
  [#6](https://github.com/AliSoftware/Reusable/issues/6)

* Fixed bundle location of nibs. By default, `nib: UINib` of `NibLoadable` protocol will now use the nib located in the bundle of the conforming class.
  [@chrisamanse](https://github.com/chrisamanse)
  [#10](https://github.com/AliSoftware/Reusable/pull/10)

* Fixed issue with subclasses of types conforming to `Reusable` — due to the [Swift bug SR-617](https://bugs.swift.org/browse/SR-617).
  [@chrisamanse](https://github.com/chrisamanse)
  [#2](https://github.com/AliSoftware/Reusable/issues/2)

## 2.1.0

* Added support for direct instantiation of arbitrary `UIView` from a nib.
  [@jakubvano](https://github.com/jakubvano)
  [#5](https://github.com/AliSoftware/Reusable/pull/5)

There is now a dedicated `NibLoadable` protocol which can be used on any arbitrary `UIView` (even non-"reusable" views) to load it from a XIB (via the `loadFromNib()` function injected via the protocol extension).

_The `NibReusable` protocol still exists for reusable cells but is now declared just as a combination of both the `Reusable` and `NibLoadable` protocols.

## 2.0.0

* Fixed missing `public` visibility for the protocols and extensions
* Improved README documentation

## 1.1.0

* Added documentation
* Fixed generic constraints on the API working with `UICollectionView`'s `SupplementaryView`
* Updated Example project to add an UICollectionView with cells from XIB & Code + Header views

## 1.0.0

* Split protocol in two: `Reusable` and `NibReusable`
* Now contains a Demo project

## 0.1.0

Initial version. Only one `Reusable` protocol
No demo project, but has a `podspec` and a `Package.swift`


text:
/**
 * @brief Manages Content Apps
 */

#pragma once

#include <app-common/zap-generated/enums.h>
#include <app/app-platform/ContentApp.h>
#include <app/app-platform/ContentAppPlatform.h>
#include <app/util/attribute-storage.h>
#include <functional>
#include <stdbool.h>
#include <stdint.h>

#include "CommissionerMain.h"
#include "include/account-login/AccountLoginManager.h"
#include "include/application-basic/ApplicationBasicManager.h"
#include "include/application-launcher/ApplicationLauncherManager.h"
#include "include/channel/ChannelManager.h"
#include "include/content-launcher/ContentLauncherManager.h"
#include "include/keypad-input/KeypadInputManager.h"
#include "include/media-playback/MediaPlaybackManager.h"
#include "include/target-navigator/TargetNavigatorManager.h"
#include <app/clusters/account-login-server/account-login-delegate.h>
#include <app/clusters/application-basic-server/application-basic-delegate.h>
#include <app/clusters/application-launcher-server/application-launcher-delegate.h>
#include <app/clusters/channel-server/channel-delegate.h>
#include <app/clusters/content-launch-server/content-launch-delegate.h>
#include <app/clusters/keypad-input-server/keypad-input-delegate.h>
#include <app/clusters/media-playback-server/media-playback-delegate.h>
#include <app/clusters/target-navigator-server/target-navigator-delegate.h>

CHIP_ERROR InitVideoPlayerPlatform();

#if CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED

namespace chip {
namespace AppPlatform {

using AccountLoginDelegate        = app::Clusters::AccountLogin::Delegate;
using ApplicationBasicDelegate    = app::Clusters::ApplicationBasic::Delegate;
using ApplicationLauncherDelegate = app::Clusters::ApplicationLauncher::Delegate;
using ChannelDelegate             = app::Clusters::Channel::Delegate;
using ContentLauncherDelegate     = app::Clusters::ContentLauncher::Delegate;
using KeypadInputDelegate         = app::Clusters::KeypadInput::Delegate;
using MediaPlaybackDelegate       = app::Clusters::MediaPlayback::Delegate;
using TargetNavigatorDelegate     = app::Clusters::TargetNavigator::Delegate;
using SupportedStreamingProtocol  = app::Clusters::ContentLauncher::SupportedStreamingProtocol;

static const int kCatalogVendorId = CHIP_DEVICE_CONFIG_DEVICE_VENDOR_ID;

// for this platform, appid is just vendor id
#define BuildAppId(vid) std::to_string(vid).c_str()

class DLL_EXPORT ContentAppImpl : public ContentApp
{
public:
    ContentAppImpl(const char * szVendorName, uint16_t vendorId, const char * szApplicationName, uint16_t productId,
                   const char * szApplicationVersion, const char * setupPIN) :
        mApplicationBasicDelegate(kCatalogVendorId, BuildAppId(vendorId), szVendorName, vendorId, szApplicationName, productId,
                                  szApplicationVersion),
        mAccountLoginDelegate(setupPIN), mContentLauncherDelegate({ "image/*", "video/*" },
                                                                  to_underlying(SupportedStreamingProtocol::kDash) |
                                                                      to_underlying(SupportedStreamingProtocol::kHls)),
        mTargetNavigatorDelegate({ "home", "search", "info", "guide", "menu" }, 0){};
    virtual ~ContentAppImpl() {}

    AccountLoginDelegate * GetAccountLoginDelegate() override { return &mAccountLoginDelegate; };
    ApplicationBasicDelegate * GetApplicationBasicDelegate() override { return &mApplicationBasicDelegate; };
    ApplicationLauncherDelegate * GetApplicationLauncherDelegate() override { return &mApplicationLauncherDelegate; };
    ChannelDelegate * GetChannelDelegate() override { return &mChannelDelegate; };
    ContentLauncherDelegate * GetContentLauncherDelegate() override { return &mContentLauncherDelegate; };
    KeypadInputDelegate * GetKeypadInputDelegate() override { return &mKeypadInputDelegate; };
    MediaPlaybackDelegate * GetMediaPlaybackDelegate() override { return &mMediaPlaybackDelegate; };
    TargetNavigatorDelegate * GetTargetNavigatorDelegate() override { return &mTargetNavigatorDelegate; };

protected:
    ApplicationBasicManager mApplicationBasicDelegate;
    AccountLoginManager mAccountLoginDelegate;
    ApplicationLauncherManager mApplicationLauncherDelegate;
    ChannelManager mChannelDelegate;
    ContentLauncherManager mContentLauncherDelegate;
    KeypadInputManager mKeypadInputDelegate;
    MediaPlaybackManager mMediaPlaybackDelegate;
    TargetNavigatorManager mTargetNavigatorDelegate;
};

class DLL_EXPORT ContentAppFactoryImpl : public ContentAppFactory
{
#define APP_LIBRARY_SIZE 4
public:
    ContentAppFactoryImpl();
    virtual ~ContentAppFactoryImpl() {}

    // Lookup CatalogVendor App for this client (vendor id/product id client)
    // and then write it to destinationApp
    // return error if not found
    CHIP_ERROR LookupCatalogVendorApp(uint16_t vendorId, uint16_t productId, CatalogVendorApp * destinationApp) override;

    // Lookup ContentApp for this catalog id / app id and load it
    ContentApp * LoadContentApp(const CatalogVendorApp & vendorApp) override;

    // Gets the catalog vendor ID used by this platform
    uint16_t GetPlatformCatalogVendorId() override;

    // Converts application (any catalog) into the platform's catalog Vendor
    // and then writes it to destinationApp
    CHIP_ERROR ConvertToPlatformCatalogVendorApp(const CatalogVendorApp & sourceApp, CatalogVendorApp * destinationApp) override;

    // Get the privilege this vendorId should have on endpoints 1, 2, and content app endpoints
    // In the case of casting video clients, this should usually be Access::Privilege::kOperate
    // and for voice agents, this may be Access::Privilege::kAdminister
    // When a vendor has admin privileges, it will get access to all clusters on ep1
    Access::Privilege GetVendorPrivilege(uint16_t vendorId) override;

    // Get the cluster list this vendorId/productId should have on static endpoints such as ep1 for casting video clients.
    // When a vendor has admin privileges, it will get access to all clusters on ep1
    std::list<ClusterId> GetAllowedClusterListForStaticEndpoint(EndpointId endpointId, uint16_t vendorId,
                                                                uint16_t productId) override;

    void AddAdminVendorId(uint16_t vendorId);

protected:
    ContentAppImpl mContentApps[APP_LIBRARY_SIZE] = {
        ContentAppImpl("Vendor1", 1, "exampleid", 11, "Version1", "34567890"),
        ContentAppImpl("Vendor2", 65521, "exampleString", 32768, "Version2", "20202021"),
        ContentAppImpl("Vendor3", 9050, "App3", 22, "Version3", "20202021"),
        ContentAppImpl("TestSuiteVendor", 1111, "applicationId", 22, "v2", "20202021")
    };

    std::vector<uint16_t> mAdminVendorIds{};
};

} // namespace AppPlatform
} // namespace chip

chip::AppPlatform::ContentAppFactoryImpl * GetContentAppFactoryImpl();

#endif // CHIP_DEVICE_CONFIG_APP_PLATFORM_ENABLED

redpajama_set_name: RedPajamaGithub


text:
package org.cipres.treebase.web.webservices;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

import com.sun.jersey.multipart.*;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
//import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;

import org.cipres.treebase.TreebaseUtil;
import org.cipres.treebase.web.util.UnTarTool;

@Path("/dryadImport")

public class DryadImportor {

	@Context
	HttpServletRequest httpRequest;

	@PUT
    //@POST
    //@GET

    @Consumes("multipart/mixed")

public String processMultiparts(MultiPart multiPart) {

        String ip = httpRequest.getRemoteAddr();
    	// apache server re-write the ip to 127.0.0.1
        //if(!AllowIP.isAllowIP(ip))return "client " + ip + " is not authorized";

        BodyPartEntity bpe = (BodyPartEntity) multiPart.getBodyParts().get(0).getEntity();
        File unzipFold;
        String systemTime;

        do{
        	systemTime = "" + System.currentTimeMillis();
        	String uploadDir = httpRequest.getSession().getServletContext()
        	.getRealPath(TreebaseUtil.FILESEP + "DryadFileUpload")
        	+ TreebaseUtil.FILESEP + systemTime;
        	unzipFold = new File(uploadDir);
        }while(unzipFold.exists());

        File zipfile = new File(unzipFold,"data.tar.gz");

        try {
        	unzipFold.mkdirs();
        	zipfile.createNewFile();
        	InputStream in = bpe.getInputStream();
        	OutputStream out=new FileOutputStream(zipfile);

            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0){
            	out.write(buf, 0, len);
            }
            in.close();
            out.close();
            UnTarTool.unTarGz(zipfile,unzipFold);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));
			return sw.getBuffer().toString();
		}

		String BASEURL = TreebaseUtil.getSiteUrl();
		// apache server re-write the application path to localhost
		//String[] baseURL=httpRequest.getRequestURL().toString().split("handshaking");
        String importURL= BASEURL + "login.jsp?importKey=" + systemTime;

        return importURL;

    }

}

class AllowIP{
	private static final String dryad1 = "152.1.24.8";
	private static final String dryad2 = "152.3.105.16";
	private static final String yale1 = "130.132.27.141";
	private static final String yale2 = "130.132.27.212";

	static boolean isAllowIP(String ip){
		if (ip.compareTo(dryad1)==0) return true;
		if (ip.compareTo(dryad2)==0) return true;
		if (ip.compareTo(yale1)==0)return true;
		if (ip.compareTo(yale2)==0)return true;

	    return false;
	}

}


text:
package tech.fuge.www.forgotfirstlinecode.chapter3;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;

import java.util.ArrayList;
import java.util.List;

import tech.fuge.www.forgotfirstlinecode.R;

public class Main3ActivityRecycleView extends AppCompatActivity {
    private RecyclerView mRecyclerView;
    private Main3ActivityRecycleViewAdapter mAdapter;
//    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<String> myDataset = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3_recycle_view);
        mRecyclerView = (RecyclerView) findViewById(R.id.activity_main3_recycle_view_rv);
        mRecyclerView.setHasFixedSize(true);
        //默认垂直方向
        mLayoutManager = new LinearLayoutManager(this);

        //设置水平方向
//        LinearLayoutManager manager=new LinearLayoutManager(this);
//        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
//        mRecycleView.setLayoutManager(manager);
        //默认的布局
//        mRecyclerView.setLayoutManager(mLayoutManager);
        //gridLayout布局
        mRecyclerView.setLayoutManager(new GridLayoutManager(this, 4));
//StaggeredGridLayoutManager布局
//        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,
//
//        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL));

        for (int i = 0; i < 200; i++) {
            myDataset.add("这是myDataset里的元素" + i);
        }
        mAdapter = new Main3ActivityRecycleViewAdapter(myDataset);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL));
        // 设置item动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter);

    }

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, Main3ActivityRecycleView.class);
        context.startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main3_recycle_view_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_add:
                mAdapter.addData(1);
                break;
            case R.id.action_delete:
                mAdapter.removeData(1);
                break;

        }
        return true;
    }
}


text:
/*
* DescriptionBuilder.java
*
* User: Greg Schueler greg@dtosolutions.com
* Created: 11/21/12 10:47 AM
*
*/
package com.dtolabs.rundeck.plugins.util;

import com.dtolabs.rundeck.core.plugins.configuration.Description;
import com.dtolabs.rundeck.core.plugins.configuration.Property;
import com.dtolabs.rundeck.core.plugins.configuration.PropertyUtil;

import java.util.*;

/**
 * DescriptionBuilder is a builder for creating a Description object.
 *
 * @author Greg Schueler greg@dtosolutions.com
 */
public class DescriptionBuilder {
    private ArrayList<Property> properties;
    private HashMap<String, String> mapping;
    private HashMap<String, String> fwkmapping;
    private String name;
    private String title;
    private String description;

    private DescriptionBuilder() {
        properties = new ArrayList<Property>();
        mapping = new HashMap<String, String>();
        fwkmapping = new HashMap<String, String>();
    }

    private DescriptionBuilder(final Description original) {
        properties = new ArrayList<Property>(original.getProperties());
        mapping = new HashMap<String, String>(original.getPropertiesMapping());
        fwkmapping = new HashMap<String, String>(original.getFwkPropertiesMapping());
        this.name = original.getName();
        this.title = original.getTitle();
        this.description = original.getDescription();
    }

    /**
     * @return a builder
     */
    public static DescriptionBuilder builder() {
        return new DescriptionBuilder();
    }

    /**
     * @return a builder with a given description
     * @param original source
     */
    public static DescriptionBuilder builder(final Description original) {
        return new DescriptionBuilder(original);
    }

    /**
     * @param name the name
     * @return this builder
     */
    public DescriptionBuilder name(final String name) {
        this.name = name;
        return this;
    }

    /**
     * @param title a title string
     * @return this builder
     */
    public DescriptionBuilder title(final String title) {
        this.title = title;
        return this;
    }

    /**
     * @param description a description string
     * @return this builder
     */
    public DescriptionBuilder description(final String description) {
        this.description = description;
        return this;
    }

    /**
     * @param key property key
     * @param name a property name mapping
     *
     * @return this builder
     */
    public DescriptionBuilder mapping(final String key, final String name) {
        mapping.put(key, name);
        return this;
    }
    /**
     * Add a property mapping for framework properties
     * @param key property key
     * @param name a property name mapping
     *
     * @return this builder
     */
    public DescriptionBuilder frameworkMapping(final String key, final String name) {
        fwkmapping.put(key, name);
        return this;
    }
    /**
     * Add all entries to the mapping
     * @param mapping property key to properties name mapping
     *
     * @return this builder
     */
    public DescriptionBuilder mapping(final Map<String,String> mapping) {
        this.mapping.putAll(mapping);
        return this;
    }
    /**
     * Add all entries to the frameworkMapping
     * @param mapping property key to properties name mapping
     *
     * @return this builder
     */
    public DescriptionBuilder frameworkMapping(final Map<String,String> mapping) {
        this.fwkmapping.putAll(mapping);
        return this;
    }

    /**
     * Add a String property
     * @param name name
     * @param defaultValue default
     * @param required true if required
     * @param propTitle optional title
     * @param propDescription optional description
     *
     * @return this builder
     */
    public DescriptionBuilder stringProperty(final String name,
                                             final String defaultValue,
                                             final boolean required,
                                             final String propTitle, final String propDescription) {
        properties.add(PropertyUtil.string(name, propTitle, propDescription, required, defaultValue));
        return this;
    }

    /**
     * Add a Boolean property
     * @param name name
     * @param defaultValue default
     * @param required true if required
     * @param propTitle optional title
     * @param propDescription optional description
     *
     * @return this builder
     */
    public DescriptionBuilder booleanProperty(final String name,
                                              final String defaultValue,
                                              final boolean required,
                                              final String propTitle, final String propDescription) {
        properties.add(PropertyUtil.bool(name, propTitle, propDescription, required, defaultValue));
        return this;
    }

    /**
     * Add an Integer property
     * @param name name
     * @param defaultValue default
     * @param required true if required
     * @param propTitle optional title
     * @param propDescription optional description
     *
     * @return this builder
     */
    public DescriptionBuilder integerProperty(final String name,
                                              final String defaultValue,
                                              final boolean required,
                                              final String propTitle, final String propDescription) {
        properties.add(PropertyUtil.integer(name, propTitle, propDescription, required, defaultValue));
        return this;
    }

    /**
     * Add a Select property
     * @param name name
     * @param defaultValue default
     * @param required true if required
     * @param propTitle optional title
     * @param propDescription optional description
     * @param selectValues select values
     *
     * @return this builder
     */
    public DescriptionBuilder selectProperty(final String name,
                                             final String defaultValue,
                                             final boolean required,
                                             final String propTitle,
                                             final String propDescription, final List<String> selectValues) {
        properties.add(PropertyUtil.select(name, propTitle, propDescription, required, defaultValue, selectValues));
        return this;
    }

    /**
     * Add a FreeSelect property
     * @param name name
     * @param defaultValue default
     * @param required true if required
     * @param propTitle optional title
     * @param propDescription optional description
     * @param selectValues select values
     *
     * @return this builder
     */
    public DescriptionBuilder freeSelectProperty(final String name,
                                                 final String defaultValue,
                                                 final boolean required,
                                                 final String propTitle,
                                                 final String propDescription, final List<String> selectValues) {
        properties.add(PropertyUtil.freeSelect(name, propTitle, propDescription, required, defaultValue, selectValues));
        return this;
    }

    /**
     * Add a new property, or replace an existing property with the same name by passing in a builder.
     * @param property builder
     * @return this builder
     */
    public DescriptionBuilder property(final PropertyBuilder property) {
        replaceOrAddProperty(property.build());
        return this;
    }

    /**
     * Add a new property, or replace an existing property with the same name.
     * @param property property
     * @return this builder
     */
    public DescriptionBuilder property(final Property property) {
        replaceOrAddProperty(property);
        return this;
    }

    /**
     * Remove a previously defined property by name
     * @param name property name
     * @return this builder
     */
    public DescriptionBuilder removeProperty(final String name) {
        final Property found = findProperty(name);
        if (null != found) {
            properties.remove(found);
        }
        return this;
    }

    private Property findProperty(String name) {
        for (final Property property : properties) {
            if (property.getName().equals(name)) {
                return property;
            }
        }
        return null;
    }

    private void replaceOrAddProperty(Property p) {

        for (final Property property : properties) {
            if (property.getName().equals(p.getName())) {
                properties.set(properties.indexOf(property), p);
                return;
            }
        }
        properties.add(p);
    }

    /**
     * Returns a new {@link PropertyBuilder} preconfigured with an existing property or a new one to add a new property.
     * Be sure to call {@link #property(com.dtolabs.rundeck.core.plugins.configuration.Property)} to add the result of
     * the final call to {@link com.dtolabs.rundeck.plugins.util.PropertyBuilder#build()}.
     *
     * @param name name
     *
     * @return this builder
     */
    public PropertyBuilder property(final String name) {
        final Property found = findProperty(name);
        if (null != found) {
            return PropertyBuilder.builder(found);
        } else {
            return PropertyBuilder.builder().name(name);
        }
    }

    /**
     * @return the built description
     *
     */
    public Description build() {
        if (null == name) {
            throw new IllegalStateException("name is not set");
        }
        final String title1 = null != title ? title : name;
        final List<Property> properties1 = Collections.unmodifiableList(properties);
        final Map<String, String> mapping1 = Collections.unmodifiableMap(mapping);
        final Map<String, String> mapping2 = Collections.unmodifiableMap(fwkmapping);
        return new Description() {
            @Override
            public String getName() {
                return name;
            }

            @Override
            public String getTitle() {
                return title1;
            }

            @Override
            public String getDescription() {
                return description;
            }

            @Override
            public List<Property> getProperties() {
                return properties1;
            }

            @Override
            public Map<String, String> getPropertiesMapping() {
                return mapping1;
            }

            @Override
            public Map<String, String> getFwkPropertiesMapping() {
                return mapping2;
            }

            @Override
            public String toString() {
                return "PropertyDescription{" +
                        "name = " + getName() + ", " +
                        "title = " + getTitle() + ", " +
                        "description = " + getDescription() + ", " +
                        "properties = " + getProperties() + ", " +
                        "mapping = " + getPropertiesMapping() +
                        "frameworkMapping = " + getFwkPropertiesMapping() +
                        "}";
            }
        };
    }

    /**
     * Allows the Collaborator to assist using this DescriptionBuilder.
     *
     * @param colab collaborator
     *
     * @return this builder
     */
    public DescriptionBuilder collaborate(final Collaborator colab) {
        colab.buildWith(this);
        return this;
    }

    /**
     * Allows any object to collaborate on this DescriptionBuilder if it implements {@link Collaborator}, otherwise
     * simply returns this builder.
     *
     * @param colab collaborator
     *
     * @return this builder
     */
    public DescriptionBuilder collaborate(final Object colab) {
        if (colab instanceof Collaborator) {
            return collaborate((Collaborator) colab);
        }
        return this;
    }

    /**
     * Allows a class to collaborate in building a Description using a DescriptionBuilder
     */
    public static interface Collaborator {
        /**
         * visit the builder and do some work
         * @param builder the builder
         */
        public void buildWith(DescriptionBuilder builder);
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>net.sourceforge.pmd.testframework (PMD 5.0.4 Test API)</title>
<meta name="date" content="2013-05-01">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Package net.sourceforge.pmd.testframework

Class Summary

Class
Description

AbstractTokenizerTest

ParserTst

RuleTst

Advanced methods for test cases

SimpleAggregatorTst

Standard methods for (simple) testcases.

SimpleAggregatorTst.CustomXmlTestClassMethodsRunner

TestDescriptor

Stores the information required to run a complete test.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2002-2013 InfoEther. All Rights Reserved.


text:
set -e;
## All created files will have permission 760
umask 007;

### define script file locations.
user=$1;
project=$2;
main_dir=$(pwd)"/../../";

##==============================================================================
## Cleanup intermediate processing files.
##------------------------------------------------------------------------------

projectDirectory=$main_dir"users/"$user"/projects/"$project"/";
logName=$projectDirectory"process_log.txt";
condensedLog=$projectDirectory"condensed_log.txt";

. $main_dir"config.sh";
if [ $debug -eq 1 ];
then
	echo "\tReached cleanup stage, but skipping it because the debug flag is on." >> $logName;
	echo "\tCreating complete.txt, so that the front-end recognizes the completion." >> $logName;

	completeFile=$projectDirectory"complete.txt";
	echo "complete" > $completeFile;
	timestamp=$(date +%T);
	echo $timestamp >> $completeFile;
	echo "\tGenerated 'complete.txt' file." >> $logName;
	chmod 0744 $completeFile;

	## changing working.txt to working_done.txt
	if [ -f $projectDirectory"working.txt" ]
	then
		mv $projectDirectory"working.txt" $projectDirectory"working_done.txt";
		echo "\t changed working.txt to working_done.txt" >> $logName;
	fi

	exit 0;
fi

echo "#=======================================#" >> $logName;
echo "# Cleaning up intermediate WGseq files. #" >> $logName;
echo "#=======================================#" >> $logName;
echo "Cleaning and archiving." >> $condensedLog;

if [ -f $projectDirectory"zipTemp.txt" ]
then
	rm $projectDirectory"zipTemp.txt";
	echo "\tzipTemp.txt" >> $logName;
fi

if [ -f $projectDirectory"processing1.m" ]
then
	rm $projectDirectory"processing1.m";
	echo "\tprocessing1.m" >> $logName;
fi

if [ -f $projectDirectory"processing2.m" ]
then
	rm $projectDirectory"processing2.m";
	echo "\tprocessing2.m" >> $logName;
fi

if [ -f $projectDirectory"processing3.m" ]
then
	rm $projectDirectory"processing3.m";
	echo "\tprocessing3.m" >> $logName;
fi

if [ -f $projectDirectory"processing4.m" ]
then
	rm $projectDirectory"processing4.m";
	echo "\tprocessing4.m" >> $logName;
fi

if [ -f $projectDirectory"matlab.CNV_and_GCbias.log" ]
then
	rm $projectDirectory"matlab.CNV_and_GCbias.log";
	echo "\tmatlab.CNV_and_GCbias.log" >> $logName;
fi

if [ -f $projectDirectory"matlab.ChARM.log" ]
then
	rm $projectDirectory"matlab.ChARM.log";
	echo "\tmatlab.ChARM.log" >> $logName;
fi

if [ -f $projectDirectory"matlab.SNP_analysis.log" ]
then
	rm $projectDirectory"matlab.SNP_analysis.log";
	echo "\tmatlab.SNP_analysis.log" >> $logName;
fi

if [ -f $projectDirectory"matlab.final_figs.log" ]
then
	rm $projectDirectory"matlab.final_figs.log";
	echo "\tmatlab.final_figs.log" >> $logName;
fi

if [ -f $projectDirectory"data_sorted.bam.bai" ]
then
	rm $projectDirectory"data_sorted.bam.bai";
	echo "\tdata_sorted.bam.bai" >> $logName;
fi

if [ -f $projectDirectory"data_sorted.bam" ]
then
	rm $projectDirectory"data_sorted.bam";
	echo "\tdata_sorted.bam" >> $logName;
fi
if [ -f $projectDirectory"data.bam" ]
then
	rm $projectDirectory"data.bam";
	echo "\tdata.bam" >> $logName;
fi
if [ -f $projectDirectory"data.pileup" ]
then
	rm $projectDirectory"data.pileup";
	echo "\tdata.pileup" >> $logName;
fi
if [ -f $projectDirectory"data_indelRealigned.bam" ]
then
	rm $projectDirectory"data_indelRealigned.bam";
	echo "\tdata_indelRealigned.bam" >> $logName;
fi
if [ -f $projectDirectory"data_indelRealigned.bai" ]
then
	rm $projectDirectory"data_indelRealigned.bai";
	echo "\tdata_indelRealigned.bai" >> $logName;
fi

if [ -d $projectDirectory"fastqc_temp/" ]
then
	rm -rf $projectDirectory"fastqc_temp/";
	echo "\tfastqc_temp/" >> $logName;
fi
if [ -f $projectDirectory"datafiles.txt" ]
then
	# Get first data file name from "datafiles.txt";
	datafile1=$(head -n 1 $projectDirectory"datafiles.txt");
	echo "\tdatafile 1 = '"$datafile1"'" >> $logName;
	# Get second data file name from "datafiles.txt";
	datafile2=$(tail -n 1 $projectDirectory"datafiles.txt");
	echo "\tdatafile 2 = '"$datafile2"'" >> $logName;
	if [ "$datafile1" = "$datafile2" ]
	then
		# deleting only if a valid file name is written
		if [ "$datafile1" != "null1" ]
		then
			if [ -f $projectDirectory$datafile1 ]
			then
				rm $projectDirectory$datafile1;
				echo "\t"$datafile1 >> $logName;
			fi
		fi
	else
		if [ -f $projectDirectory$datafile1 ]
		then
			rm $projectDirectory$datafile1;
			echo "\t"$datafile1 >> $logName;
		fi
		if [ -f $projectDirectory$datafile2 ]
		then
			rm $projectDirectory$datafile2;
			echo "\t"$datafile2 >> $logName;
		fi
	fi
	rm $projectDirectory"datafiles.txt";
	echo "\tdatafiles.txt" >> $logName;
fi

# Remove potential leftovers from upload restarts.
#pattern="*.zip";
#if [ "$(echo $pattern)" != "$pattern" ]; then rm *.zip; fi
#pattern="*.gz";
#if [ "$(echo $pattern)" != "$pattern" ]; then rm *.gz; fi
#pattern="*.bam";
#if [ "$(echo $pattern)" != "$pattern" ]; then rm *.bam; fi
#pattern="*.sam";
#if [ "$(echo $pattern)" != "$pattern" ]; then rm *.sam; fi
#pattern="*.fastq";
#if [ "$(echo $pattern)" != "$pattern" ]; then rm *.fastq; fi

# Compress 'putative_SNPs_v1.txt' and 'SNP_CNVs_v1.txt'.
if [ -f $projectDirectory"putative_SNPs_v4.txt" ]
then
	zip -9 $projectDirectory"putative_SNPs_v4.zip" $projectDirectory"putative_SNPs_v4.txt";
	rm $projectDirectory"putative_SNPs_v4.txt";
	echo "\tputative_SNPs_v4.txt (created putative_SNPs_v4.zip)" >> $logName;
fi
if [ -f $projectDirectory"SNP_CNV_v1.txt" ]
then
	zip -9 $projectDirectory"SNP_CNV_v1.zip" $projectDirectory"SNP_CNV_v1.txt";
	rm $projectDirectory"SNP_CNV_v1.txt";
	echo "\tSNP_CNV_v1.txt (created SNP_CNV_v1.zip)" >> $logName;
fi

## Generate "complete.txt" to indicate processing has completed normally.
timestamp=$(date +%T);

	timesLogFile=$main_dir"completion_times.log";
	if [ -f $timesLogFile ]
	then
		echo -n $user"("$project")[WGseq " >> $timesLogFile;
		cat $projectDirectory"dataType.txt" >> $timesLogFile;
		echo -n "]\t" >> $timesLogFile;
		cat $projectDirectory"working.txt" >> $timesLogFile;
		echo " -> "$timestamp >> $timesLogFile;
	fi

completeFile=$projectDirectory"complete.txt";
echo "complete" > $completeFile;
echo $timestamp >> $completeFile;
echo "\tGenerated 'complete.txt' file." >> $logName;
chmod 0755 $completeFile;

if [ -f $projectDirectory"working.txt" ]
then
	mv $projectDirectory"working.txt" $projectDirectory"working_done.txt";
	echo "\tworking.txt" >> $logName;
fi


text:
package de.rosebud.sample;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import de.rosebud.Data;
import de.rosebud.core.ContentBuilder;
import de.rosebud.core.Fragment;
import de.rosebud.core.RosebudHelper;

@Controller
public class SimpleRosebud {

    @Autowired
    ContentBuilder simpleContentBuilder;

    // simplest variant: render a json pagetype without dynamic data
    @RequestMapping("/simple")
    public @ResponseBody
    String simple(HttpServletRequest req) {
        return simpleContentBuilder.run("/pagetypes/bootstrap/sample", req);
    }

    // typical mvc example: template, wrapper, model: go!
    @RequestMapping("/blueprint")
    public @ResponseBody
    String blueprint(HttpServletRequest req) {
        return simpleContentBuilder.runWithHole("/pagetypes/bootstrap/blueprint",
                provideData(req), provideGlobalData(),
                "/de/rosebud/sample/frags/article/article", req);
    }

    // advanced mvc example: modify several holes
    @RequestMapping("/blueprint2")
    public @ResponseBody
    String blueprint2(HttpServletRequest req) {
        Fragment root = simpleContentBuilder.load("/pagetypes/bootstrap/blueprint");

        /*
         *  if you want, you can load another pagetree here and append it.
         *  This might be useful to integrate different teaser-columns
         */
        RosebudHelper.getFragmentWithName(root, "content_container").
                addChild(Fragment.build().setStartTemplate("/de/rosebud/sample/frags/article/article").
                        setData(provideData(req)));
        return simpleContentBuilder.createPage(provideGlobalData(), root, req);
    }

    // simplest variant: render a json pagetype without dynamic data
    @RequestMapping("/wrap")
    public @ResponseBody
    String wrap(HttpServletRequest req) {
        return simpleContentBuilder.run("/pagetypes/test/wrapper/sample_test", req);
    }

    private Data provideData(HttpServletRequest req) {
        Data data = new Data();
        data.addData("headline", "Sample Headline Blueprint");
        data.addData("text", "Lorem Ipsum Blueprint");
        data.addData("link", "My Blueprint Link");
        return data;
    }

    private Data provideGlobalData() {
        Data data = new Data();
        data.addData("title", "This is the Start Page Blueprint");
        return data;
    }

}


text:
<?php

namespace UserFrosting\Sprinkle\Admin\Controller;

use Illuminate\Database\Capsule\Manager as Capsule;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use UserFrosting\Fortress\Adapter\JqueryValidationAdapter;
use UserFrosting\Fortress\RequestDataTransformer;
use UserFrosting\Fortress\RequestSchema;
use UserFrosting\Fortress\ServerSideValidator;
use UserFrosting\Sprinkle\Account\Database\Models\Role;
use UserFrosting\Sprinkle\Core\Controller\SimpleController;
use UserFrosting\Support\Exception\BadRequestException;
use UserFrosting\Support\Exception\ForbiddenException;
use UserFrosting\Support\Exception\NotFoundException;

/**
 * Controller class for role-related requests, including listing roles, CRUD for roles, etc.
 *
 * @author Alex Weissman (https://alexanderweissman.com)
 */
class RoleController extends SimpleController
{
    /**
     * Processes the request to create a new role.
     *
     * Processes the request from the role creation form, checking that:
     * 1. The role name and slug are not already in use;
     * 2. The user has permission to create a new role;
     * 3. The submitted data is valid.
     * This route requires authentication (and should generally be limited to admins or the root user).
     *
     * Request type: POST
     *
     * @see getModalCreateRole
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws ForbiddenException If user is not authorized to access page
     */
    public function create(Request $request, Response $response, $args)
    {
        // Get POST parameters: name, slug, description
        $params = $request->getParsedBody();

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled page
        if (!$authorizer->checkAccess($currentUser, 'create_role')) {
            throw new ForbiddenException();
        }

        /** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */
        $ms = $this->ci->alerts;

        // Load the request schema
        $schema = new RequestSchema('schema://requests/role/create.yaml');

        // Whitelist and set parameter defaults
        $transformer = new RequestDataTransformer($schema);
        $data = $transformer->transform($params);

        $error = false;

        // Validate request data
        $validator = new ServerSideValidator($schema, $this->ci->translator);
        if (!$validator->validate($data)) {
            $ms->addValidationErrors($validator);
            $error = true;
        }

        /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        // Check if name or slug already exists
        if ($classMapper->getClassMapping('role')::where('name', $data['name'])->first()) {
            $ms->addMessageTranslated('danger', 'ROLE.NAME_IN_USE', $data);
            $error = true;
        }

        if ($classMapper->getClassMapping('role')::where('slug', $data['slug'])->first()) {
            $ms->addMessageTranslated('danger', 'SLUG_IN_USE', $data);
            $error = true;
        }

        if ($error) {
            return $response->withJson([], 400);
        }

        /** @var \UserFrosting\Support\Repository\Repository $config */
        $config = $this->ci->config;

        // All checks passed!  log events/activities and create role
        // Begin transaction - DB will be rolled back if an exception occurs
        Capsule::transaction(function () use ($classMapper, $data, $ms, $currentUser) {
            // Create the role
            $role = $classMapper->createInstance('role', $data);

            // Store new role to database
            $role->save();

            // Create activity record
            $this->ci->userActivityLogger->info("User {$currentUser->user_name} created role {$role->name}.", [
                'type'    => 'role_create',
                'user_id' => $currentUser->id,
            ]);

            $ms->addMessageTranslated('success', 'ROLE.CREATION_SUCCESSFUL', $data);
        });

        return $response->withJson([], 200);
    }

    /**
     * Processes the request to delete an existing role.
     *
     * Deletes the specified role.
     * Before doing so, checks that:
     * 1. The user has permission to delete this role;
     * 2. The role is not a default for new users;
     * 3. The role does not have any associated users;
     * 4. The submitted data is valid.
     * This route requires authentication (and should generally be limited to admins or the root user).
     *
     * Request type: DELETE
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws NotFoundException   If role is not found
     * @throws ForbiddenException  If user is not authorized to access page
     * @throws BadRequestException
     */
    public function delete(Request $request, Response $response, $args)
    {
        $role = $this->getRoleFromParams($args);

        // If the role doesn't exist, return 404
        if (!$role) {
            throw new NotFoundException();
        }

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled page
        if (!$authorizer->checkAccess($currentUser, 'delete_role', [
            'role' => $role,
        ])) {
            throw new ForbiddenException();
        }

        /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        // Check that we are not deleting a default role
        $defaultRoleSlugs = $classMapper->getClassMapping('role')::getDefaultSlugs();

        // Need to use loose comparison for now, because some DBs return `id` as a string
        if (in_array($role->slug, $defaultRoleSlugs)) {
            $e = new BadRequestException();
            $e->addUserMessage('ROLE.DELETE_DEFAULT');

            throw $e;
        }

        // Check if there are any users associated with this role
        $countUsers = $role->users()->count();
        if ($countUsers > 0) {
            $e = new BadRequestException();
            $e->addUserMessage('ROLE.HAS_USERS');

            throw $e;
        }

        $roleName = $role->name;

        // Begin transaction - DB will be rolled back if an exception occurs
        Capsule::transaction(function () use ($role, $roleName, $currentUser) {
            $role->delete();
            unset($role);

            // Create activity record
            $this->ci->userActivityLogger->info("User {$currentUser->user_name} deleted role {$roleName}.", [
                'type'    => 'role_delete',
                'user_id' => $currentUser->id,
            ]);
        });

        /** @var \UserFrosting\Sprinkle\Core\Alert\AlertStream $ms */
        $ms = $this->ci->alerts;

        $ms->addMessageTranslated('success', 'ROLE.DELETION_SUCCESSFUL', [
            'name' => $roleName,
        ]);

        return $response->withJson([], 200);
    }

    /**
     * Returns info for a single role, along with associated permissions.
     *
     * This page requires authentication.
     *
     * Request type: GET
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws ForbiddenException If user is not authorized to access page
     * @throws NotFoundException  If role is not found
     */
    public function getInfo(Request $request, Response $response, $args)
    {
        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled page
        if (!$authorizer->checkAccess($currentUser, 'uri_roles')) {
            throw new ForbiddenException();
        }

        $slug = $args['slug'];

        /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        $role = $classMapper->getClassMapping('role')::where('slug', $slug)->first();

        // If the role doesn't exist, return 404
        if (!$role) {
            throw new NotFoundException();
        }

        // Get role
        $result = $role->load('permissions')->toArray();

        // Be careful how you consume this data - it has not been escaped and contains untrusted user-supplied content.
        // For example, if you plan to insert it into an HTML DOM, you must escape it on the client side (or use client-side templating).
        return $response->withJson($result, 200, JSON_PRETTY_PRINT);
    }

    /**
     * Returns a list of Roles.
     *
     * Generates a list of roles, optionally paginated, sorted and/or filtered.
     * This page requires authentication.
     *
     * Request type: GET
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws ForbiddenException If user is not authorized to access page
     */
    public function getList(Request $request, Response $response, $args)
    {
        // GET parameters
        $params = $request->getQueryParams();

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled page
        if (!$authorizer->checkAccess($currentUser, 'uri_roles')) {
            throw new ForbiddenException();
        }

        /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        $sprunje = $classMapper->createInstance('role_sprunje', $classMapper, $params);

        // Be careful how you consume this data - it has not been escaped and contains untrusted user-supplied content.
        // For example, if you plan to insert it into an HTML DOM, you must escape it on the client side (or use client-side templating).
        return $sprunje->toResponse($response);
    }

    /**
     * Display deletion confirmation modal.
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws NotFoundException   If role is not found
     * @throws ForbiddenException  If user is not authorized to access page
     * @throws BadRequestException
     */
    public function getModalConfirmDelete(Request $request, Response $response, $args)
    {
        // GET parameters
        $params = $request->getQueryParams();

        $role = $this->getRoleFromParams($params);

        // If the role no longer exists, forward to main role listing page
        if (!$role) {
            throw new NotFoundException();
        }

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled page
        if (!$authorizer->checkAccess($currentUser, 'delete_role', [
            'role' => $role,
        ])) {
            throw new ForbiddenException();
        }

        /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        // Check that we are not deleting a default role
        $defaultRoleSlugs = $classMapper->getClassMapping('role')::getDefaultSlugs();

        // Need to use loose comparison for now, because some DBs return `id` as a string
        if (in_array($role->slug, $defaultRoleSlugs)) {
            $e = new BadRequestException();
            $e->addUserMessage('ROLE.DELETE_DEFAULT', $role->toArray());

            throw $e;
        }

        // Check if there are any users associated with this role
        $countUsers = $role->users()->count();
        if ($countUsers > 0) {
            $e = new BadRequestException();
            $e->addUserMessage('ROLE.HAS_USERS', $role->toArray());

            throw $e;
        }

        return $this->ci->view->render($response, 'modals/confirm-delete-role.html.twig', [
            'role' => $role,
            'form' => [
                'action' => "api/roles/r/{$role->slug}",
            ],
        ]);
    }

    /**
     * Renders the modal form for creating a new role.
     *
     * This does NOT render a complete page.  Instead, it renders the HTML for the modal, which can be embedded in other pages.
     * This page requires authentication.
     *
     * Request type: GET
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws ForbiddenException If user is not authorized to access page
     */
    public function getModalCreate(Request $request, Response $response, $args)
    {
        // GET parameters
        $params = $request->getQueryParams();

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        /** @var \UserFrosting\I18n\Translator $translator */
        $translator = $this->ci->translator;

        // Access-controlled page
        if (!$authorizer->checkAccess($currentUser, 'create_role')) {
            throw new ForbiddenException();
        }

        /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        // Create a dummy role to prepopulate fields
        $role = $classMapper->createInstance('role', []);

        $fieldNames = ['name', 'slug', 'description'];
        $fields = [
            'hidden'   => [],
            'disabled' => [],
        ];

        // Load validation rules
        $schema = new RequestSchema('schema://requests/role/create.yaml');
        $validator = new JqueryValidationAdapter($schema, $this->ci->translator);

        return $this->ci->view->render($response, 'modals/role.html.twig', [
            'role' => $role,
            'form' => [
                'action'      => 'api/roles',
                'method'      => 'POST',
                'fields'      => $fields,
                'submit_text' => $translator->translate('CREATE'),
            ],
            'page' => [
                'validators' => $validator->rules('json', false),
            ],
        ]);
    }

    /**
     * Renders the modal form for editing an existing role.
     *
     * This does NOT render a complete page.  Instead, it renders the HTML for the modal, which can be embedded in other pages.
     * This page requires authentication.
     *
     * Request type: GET
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws NotFoundException  If role is not found
     * @throws ForbiddenException If user is not authorized to access page
     */
    public function getModalEdit(Request $request, Response $response, $args)
    {
        // GET parameters
        $params = $request->getQueryParams();

        $role = $this->getRoleFromParams($params);

        // If the role doesn't exist, return 404
        if (!$role) {
            throw new NotFoundException();
        }

        /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        /** @var \UserFrosting\I18n\Translator $translator */
        $translator = $this->ci->translator;

        // Access-controlled resource - check that currentUser has permission to edit basic fields "name", "slug", "description" for this role
        $fieldNames = ['name', 'slug', 'description'];
        if (!$authorizer->checkAccess($currentUser, 'update_role_field', [
            'role' => $role,
            'fields' => $fieldNames,
        ])) {
            throw new ForbiddenException();
        }

        // Generate form
        $fields = [
            'hidden'   => [],
            'disabled' => [],
        ];

        // Load validation rules
        $schema = new RequestSchema('schema://requests/role/edit-info.yaml');
        $validator = new JqueryValidationAdapter($schema, $translator);

        return $this->ci->view->render($response, 'modals/role.html.twig', [
            'role' => $role,
            'form' => [
                'action'      => "api/roles/r/{$role->slug}",
                'method'      => 'PUT',
                'fields'      => $fields,
                'submit_text' => $translator->translate('UPDATE'),
            ],
            'page' => [
                'validators' => $validator->rules('json', false),
            ],
        ]);
    }

    /**
     * Renders the modal form for editing a role's permissions.
     *
     * This does NOT render a complete page.  Instead, it renders the HTML for the form, which can be embedded in other pages.
     * This page requires authentication.
     *
     * Request type: GET
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws NotFoundException  If role is not found
     * @throws ForbiddenException If user is not authorized to access page
     */
    public function getModalEditPermissions(Request $request, Response $response, $args)
    {
        // GET parameters
        $params = $request->getQueryParams();

        $role = $this->getRoleFromParams($params);

        // If the role doesn't exist, return 404
        if (!$role) {
            throw new NotFoundException();
        }

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled resource - check that currentUser has permission to edit "permissions" field for this role
        if (!$authorizer->checkAccess($currentUser, 'update_role_field', [
            'role' => $role,
            'fields' => ['permissions'],
        ])) {
            throw new ForbiddenException();
        }

        return $this->ci->view->render($response, 'modals/role-manage-permissions.html.twig', [
            'role' => $role,
        ]);
    }

    /**
     * Returns a list of Permissions for a specified Role.
     *
     * Generates a list of permissions, optionally paginated, sorted and/or filtered.
     * This page requires authentication.
     *
     * Request type: GET
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws NotFoundException  If role is not found
     * @throws ForbiddenException If user is not authorized to access page
     */
    public function getPermissions(Request $request, Response $response, $args)
    {
        $role = $this->getRoleFromParams($args);

        // If the role no longer exists, forward to main role listing page
        if (!$role) {
            throw new NotFoundException();
        }

        // GET parameters
        $params = $request->getQueryParams();

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled page
        if (!$authorizer->checkAccess($currentUser, 'view_role_field', [
            'role' => $role,
            'property' => 'permissions',
        ])) {
            throw new ForbiddenException();
        }

        /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        $sprunje = $classMapper->createInstance('permission_sprunje', $classMapper, $params);
        $sprunje->extendQuery(function ($query) use ($role) {
            return $query->forRole($role->id);
        });

        // Be careful how you consume this data - it has not been escaped and contains untrusted user-supplied content.
        // For example, if you plan to insert it into an HTML DOM, you must escape it on the client side (or use client-side templating).
        return $sprunje->toResponse($response);
    }

    /**
     * Returns users associated with a single role.
     *
     * This page requires authentication.
     *
     * Request type: GET
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws NotFoundException  If role is not found
     * @throws ForbiddenException If user is not authorized to access page
     */
    public function getUsers(Request $request, Response $response, $args)
    {
        $role = $this->getRoleFromParams($args);

        // If the role doesn't exist, return 404
        if (!$role) {
            throw new NotFoundException();
        }

        /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        // GET parameters
        $params = $request->getQueryParams();

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled page
        if (!$authorizer->checkAccess($currentUser, 'view_role_field', [
            'role' => $role,
            'property' => 'users',
        ])) {
            throw new ForbiddenException();
        }

        $sprunje = $classMapper->createInstance('user_sprunje', $classMapper, $params);
        $sprunje->extendQuery(function ($query) use ($role) {
            return $query->forRole($role->id);
        });

        // Be careful how you consume this data - it has not been escaped and contains untrusted user-supplied content.
        // For example, if you plan to insert it into an HTML DOM, you must escape it on the client side (or use client-side templating).
        return $sprunje->toResponse($response);
    }

    /**
     * Renders a page displaying a role's information, in read-only mode.
     *
     * This checks that the currently logged-in user has permission to view the requested role's info.
     * It checks each field individually, showing only those that you have permission to view.
     * This will also try to show buttons for deleting and editing the role.
     * This page requires authentication.
     *
     * Request type: GET
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws ForbiddenException If user is not authorized to access page
     */
    public function pageInfo(Request $request, Response $response, $args)
    {
        $role = $this->getRoleFromParams($args);

        // If the role no longer exists, forward to main role listing page
        if (!$role) {
            throw new NotFoundException();
        }

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled page
        if (!$authorizer->checkAccess($currentUser, 'uri_role', [
            'role' => $role,
        ])) {
            throw new ForbiddenException();
        }

        // Determine fields that currentUser is authorized to view
        $fieldNames = ['name', 'slug', 'description'];

        // Generate form
        $fields = [
            'hidden' => [],
        ];

        foreach ($fieldNames as $field) {
            if (!$authorizer->checkAccess($currentUser, 'view_role_field', [
                'role' => $role,
                'property' => $field,
            ])) {
                $fields['hidden'][] = $field;
            }
        }

        // Determine buttons to display
        $editButtons = [
            'hidden' => [],
        ];

        if (!$authorizer->checkAccess($currentUser, 'update_role_field', [
            'role' => $role,
            'fields' => ['name', 'slug', 'description'],
        ])) {
            $editButtons['hidden'][] = 'edit';
        }

        if (!$authorizer->checkAccess($currentUser, 'delete_role', [
            'role' => $role,
        ])) {
            $editButtons['hidden'][] = 'delete';
        }

        return $this->ci->view->render($response, 'pages/role.html.twig', [
            'role'            => $role,
            'fields'          => $fields,
            'tools'           => $editButtons,
            'delete_redirect' => $this->ci->router->pathFor('uri_roles'),
        ]);
    }

    /**
     * Renders the role listing page.
     *
     * This page renders a table of roles, with dropdown menus for admin actions for each role.
     * Actions typically include: edit role, delete role.
     * This page requires authentication.
     *
     * Request type: GET
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws ForbiddenException If user is not authorized to access page
     */
    public function pageList(Request $request, Response $response, $args)
    {
        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled page
        if (!$authorizer->checkAccess($currentUser, 'uri_roles')) {
            throw new ForbiddenException();
        }

        return $this->ci->view->render($response, 'pages/roles.html.twig');
    }

    /**
     * Processes the request to update an existing role's details.
     *
     * Processes the request from the role update form, checking that:
     * 1. The role name/slug are not already in use;
     * 2. The user has the necessary permissions to update the posted field(s);
     * 3. The submitted data is valid.
     * This route requires authentication (and should generally be limited to admins or the root user).
     *
     * Request type: PUT
     *
     * @see getModalRoleEdit
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws NotFoundException  If role is not found
     * @throws ForbiddenException If user is not authorized to access page
     */
    public function updateInfo(Request $request, Response $response, $args)
    {
        // Get the role based on slug in the URL
        $role = $this->getRoleFromParams($args);

        if (!$role) {
            throw new NotFoundException();
        }

        /** @var \UserFrosting\Support\Repository\Repository $config */
        $config = $this->ci->config;

        // Get PUT parameters: (name, slug, description)
        $params = $request->getParsedBody();

        /** @var \UserFrosting\I18n\Translator $translator */
        $ms = $this->ci->alerts;

        // Load the request schema
        $schema = new RequestSchema('schema://requests/role/edit-info.yaml');

        // Whitelist and set parameter defaults
        $transformer = new RequestDataTransformer($schema);
        $data = $transformer->transform($params);

        $error = false;

        // Validate request data
        $validator = new ServerSideValidator($schema, $this->ci->translator);
        if (!$validator->validate($data)) {
            $ms->addValidationErrors($validator);
            $error = true;
        }

        // Determine targeted fields
        $fieldNames = [];
        foreach ($data as $name => $value) {
            $fieldNames[] = $name;
        }

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled resource - check that currentUser has permission to edit submitted fields for this role
        if (!$authorizer->checkAccess($currentUser, 'update_role_field', [
            'role' => $role,
            'fields' => array_values(array_unique($fieldNames)),
        ])) {
            throw new ForbiddenException();
        }

        /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        // Check if name or slug already exists
        if (
            isset($data['name']) &&
            $data['name'] != $role->name &&
            $classMapper->getClassMapping('role')::where('name', $data['name'])->first()
        ) {
            $ms->addMessageTranslated('danger', 'ROLE.NAME_IN_USE', $data);
            $error = true;
        }

        if (
            isset($data['slug']) &&
            $data['slug'] != $role->slug &&
            $classMapper->getClassMapping('role')::where('slug', $data['slug'])->first()
        ) {
            $ms->addMessageTranslated('danger', 'SLUG_IN_USE', $data);
            $error = true;
        }

        if ($error) {
            return $response->withJson([], 400);
        }

        // Begin transaction - DB will be rolled back if an exception occurs
        Capsule::transaction(function () use ($data, $role, $currentUser) {
            // Update the role and generate success messages
            foreach ($data as $name => $value) {
                if ($value != $role->$name) {
                    $role->$name = $value;
                }
            }

            $role->save();

            // Create activity record
            $this->ci->userActivityLogger->info("User {$currentUser->user_name} updated details for role {$role->name}.", [
                'type'    => 'role_update_info',
                'user_id' => $currentUser->id,
            ]);
        });

        $ms->addMessageTranslated('success', 'ROLE.UPDATED', [
            'name' => $role->name,
        ]);

        return $response->withJson([], 200);
    }

    /**
     * Processes the request to update a specific field for an existing role, including permissions.
     *
     * Processes the request from the role update form, checking that:
     * 1. The logged-in user has the necessary permissions to update the putted field(s);
     * 2. The submitted data is valid.
     * This route requires authentication.
     *
     * Request type: PUT
     *
     * @param Request  $request
     * @param Response $response
     * @param array    $args
     *
     * @throws NotFoundException   If role is not found
     * @throws ForbiddenException  If user is not authorized to access page
     * @throws BadRequestException
     */
    public function updateField(Request $request, Response $response, $args)
    {
        // Get the username from the URL
        $role = $this->getRoleFromParams($args);

        if (!$role) {
            throw new NotFoundException();
        }

        // Get key->value pair from URL and request body
        $fieldName = $args['field'];

        /** @var \UserFrosting\Sprinkle\Account\Authorize\AuthorizationManager $authorizer */
        $authorizer = $this->ci->authorizer;

        /** @var \UserFrosting\Sprinkle\Account\Database\Models\Interfaces\UserInterface $currentUser */
        $currentUser = $this->ci->currentUser;

        // Access-controlled resource - check that currentUser has permission to edit the specified field for this user
        if (!$authorizer->checkAccess($currentUser, 'update_role_field', [
            'role' => $role,
            'fields' => [$fieldName],
        ])) {
            throw new ForbiddenException();
        }

        /** @var \UserFrosting\Support\Repository\Repository $config */
        $config = $this->ci->config;

        // Get PUT parameters: value
        $put = $request->getParsedBody();

        if (!isset($put['value'])) {
            throw new BadRequestException();
        }

        $params = [
            $fieldName => $put['value'],
        ];

        // Validate key -> value pair

        // Load the request schema
        $schema = new RequestSchema('schema://requests/role/edit-field.yaml');
        $schema->set('password.validators.length.min', $config['site.password.length.min']);
        $schema->set('password.validators.length.max', $config['site.password.length.max']);

        // Whitelist and set parameter defaults
        $transformer = new RequestDataTransformer($schema);
        $data = $transformer->transform($params);

        // Validate, and throw exception on validation errors.
        $validator = new ServerSideValidator($schema, $this->ci->translator);
        if (!$validator->validate($data)) {
            // TODO: encapsulate the communication of error messages from ServerSideValidator to the BadRequestException
            $e = new BadRequestException();
            foreach ($validator->errors() as $idx => $field) {
                foreach ($field as $eidx => $error) {
                    $e->addUserMessage($error);
                }
            }

            throw $e;
        }

        // Get validated and transformed value
        $fieldValue = $data[$fieldName];

        /** @var \UserFrosting\I18n\Translator $translator */
        $ms = $this->ci->alerts;

        // Begin transaction - DB will be rolled back if an exception occurs
        Capsule::transaction(function () use ($fieldName, $fieldValue, $role, $currentUser) {
            if ($fieldName == 'permissions') {
                $newPermissions = collect($fieldValue)->pluck('permission_id')->all();
                $role->permissions()->sync($newPermissions);
            } else {
                $role->$fieldName = $fieldValue;
                $role->save();
            }

            // Create activity record
            $this->ci->userActivityLogger->info("User {$currentUser->user_name} updated property '$fieldName' for role {$role->name}.", [
                'type'    => 'role_update_field',
                'user_id' => $currentUser->id,
            ]);
        });

        // Add success messages
        if ($fieldName == 'permissions') {
            $ms->addMessageTranslated('success', 'ROLE.PERMISSIONS_UPDATED', [
                'name' => $role->name,
            ]);
        } else {
            $ms->addMessageTranslated('success', 'ROLE.UPDATED', [
                'name' => $role->name,
            ]);
        }

        return $response->withJson([], 200);
    }

    /**
     * Get role instance from params.
     *
     * @param array $params
     *
     * @throws BadRequestException
     *
     * @return Role
     */
    protected function getRoleFromParams($params)
    {
        // Load the request schema
        $schema = new RequestSchema('schema://requests/role/get-by-slug.yaml');

        // Whitelist and set parameter defaults
        $transformer = new RequestDataTransformer($schema);
        $data = $transformer->transform($params);

        // Validate, and throw exception on validation errors.
        $validator = new ServerSideValidator($schema, $this->ci->translator);
        if (!$validator->validate($data)) {
            // TODO: encapsulate the communication of error messages from ServerSideValidator to the BadRequestException
            $e = new BadRequestException();
            foreach ($validator->errors() as $idx => $field) {
                foreach ($field as $eidx => $error) {
                    $e->addUserMessage($error);
                }
            }

            throw $e;
        }

        /** @var \UserFrosting\Sprinkle\Core\Util\ClassMapper $classMapper */
        $classMapper = $this->ci->classMapper;

        // Get the role
        $role = $classMapper->getClassMapping('role')::where('slug', $data['slug'])
            ->first();

        return $role;
    }
}


text:
cask 'avira-antivirus' do
  version :latest
  sha256 :no_check

  # install.avira-update.com was verified as official when first introduced to the cask
  url 'https://install.avira-update.com/package/wks_avira/osx/int/pecl/Avira_Antivirus.pkg'
  name 'Avira Antivirus'
  homepage 'https://www.avira.com/en/free-antivirus-mac'
  license :commercial

  pkg 'Avira_Antivirus.pkg'

  uninstall script:  '/Applications/Utilities/Avira-Uninstall.app/Contents/MacOS/uninstall',
            pkgutil: 'com.avira.pkg.AviraMacSecurity'
end


text:
module CommonScope::Integer
    # module ClassMethods
      def self.scopes_for_attr(model, key)
        # TODO: Find a cleaner way to extend models, I hate to use `eval` methods...
        model.class_eval do
          # Add a scope :by_[attribute name]_greater to perform a Greater than or equal query
          scope "by_#{key}_greater".to_sym, -> (param) {
            where(model.arel_table[key.to_sym].gte(param.to_i))
          }

          # Add a scope :by_[attribute name]_lesser to perform a Lesser than or equal query
          scope "by_#{key}_lesser".to_sym, -> (param) {
            where(model.arel_table[key.to_sym].lte(param.to_i))
          }

          scope "by_#{key}_between".to_sym, -> (min, max) {
            where(model.arel_table[key.to_sym].between?(min, max))
          }

          # Add a scope :by_[attribute name] to perform an exact match
          scope "by_#{key}".to_sym, -> (value) {
            where(model.arel_table[key.to_sym].eq(value.to_i))
          }
        end
      end
    # end
end