text:
<?php

class Facade_WP_MetaBox
{
  public
    $id,
    $title,
    $type,
    $pageTemplate,
    $metaTemplate,
    $context,
    $priority;

  protected function __construct($id, $title, $description, $type,
    $metaTemplate, $pageTemplate, $context, $priority)
  {
    $metaTemplate = implode(
      '',
      array_map(
      'ucfirst',
      explode(
        '-',
        $metaTemplate )));

    $this->title        = $title;
    $this->id           = sanitize_title( $id );
    $this->type         = $type;
    $this->description  = $description;
    $this->context      = $context;
    $this->pageTemplate = $pageTemplate;
    $this->priority     = $priority;

    if( class_exists( $metaTemplate ))
      $this->metaTemplate = new $metaTemplate( $this->id, $description );

    if( !( $this->metaTemplate instanceof Facade_WP_MetaBox_Template ))
    {
      $this->metaTemplate = 'Facade_WP_MetaBox_Template_' . $metaTemplate;
      $this->metaTemplate = new $this->metaTemplate( $this->id, $description );
    }
  }

  public static function add($id, $title, $description = '', $type = 'post',
    $metaTemplate = 'simple', $pageTemplate = 'any', $context = 'normal',
    $priority = 'high')
  {
    $instance = new self(
      $id,
      $title,
      $description,
      $type,
      $metaTemplate,
      $pageTemplate,
      $context,
      $priority );

    add_action(
      'add_meta_boxes',
      [
        $instance,
        'addMetaBox'
      ]);

    add_action(
      'save_post',
      [
        $instance,
        'saveMetaBox'
      ],
      1,
      0);
  }

  public static function get( $key, $post = null )
  {
    if( $post === null )
      global $post;

    $data = get_post_meta(
      is_object( $post )
        ? $post->ID
        : (int) $post,
      sanitize_title( $key ),
      true );

    if( is_serialized( $data ) )
      $data = unserialize( $data );

    return $data;
  }

  public function addMetaBox()
  {
    $templates = get_page_templates();
    $template  = get_page_template_slug();

    if($this->pageTemplate == 'any'
    || $templates[$this->pageTemplate] == $template)
      add_meta_box(
        $this->id,
        $this->title,
        [$this->metaTemplate, 'getHtml'],
        $this->type,
        $this->context,
        $this->priority );
  }

  public function saveMetaBox()
  {
    global $post;

    // Verify noncename
    if(!isset($_POST[ 'noncename-' . $this->id ])
    || !wp_verify_nonce( $_POST[ 'noncename-' . $this->id ], $this->id ))
      return $post->ID;

    // Authorized?
    if ( !current_user_can( 'edit_post', $post->ID ))
      return $post->ID;

    // Prohibits saving data twice
    if( $post->post_type == 'revision' )
      return $post->ID;

    foreach( $this->metaTemplate->getKeys() as $key )
    {
      $value = $_POST[ $key ];

      // If the value is defined as an array then serialize it
      if( empty( $value ))
      {
        delete_post_meta( $post->ID, $key );
        continue;
      }

      // Insert or update the db depending on if the value alredy exist
      get_post_meta( $post->ID, $key )
        ? update_post_meta( $post->ID, $key, $value )
        : add_post_meta( $post->ID, $key, $value );
    }
  }
}


text:
package org.kie.workbench.common.services.refactoring.backend.server.query;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

import org.kie.workbench.common.services.refactoring.model.index.terms.IndexTerm;

@ApplicationScoped
public class NamedQueries {

    private Map<String, NamedQuery> namedQueries = new HashMap<String, NamedQuery>();

    public NamedQueries() {
        //Make proxyable
    }

    @Inject
    public NamedQueries( @Any final Instance<NamedQuery> namedQueries ) {
        for (NamedQuery namedQuery : namedQueries) {
            this.namedQueries.put( namedQuery.getName(), namedQuery );
        }
    }

    public Set<IndexTerm> getTerms( final String queryName ) {

        for (NamedQuery namedQuery : namedQueries.values()) {
            if ( namedQuery.getName().equals( queryName ) ) {
                return namedQuery.getTerms();
            }
        }
        throw new IllegalArgumentException( "Named Query '" + queryName + "' does not exist." );
    }

    public Set<String> getQueries() {
        final Set<String> queryNames = new HashSet<String>();
        for (NamedQuery namedQuery : namedQueries.values()) {
            queryNames.add( namedQuery.getName() );
        }
        return queryNames;
    }

    public NamedQuery findNamedQuery( String queryName ) {
        if ( namedQueries.containsKey( queryName ) ) {
            return namedQueries.get( queryName );
        } else {
            throw new IllegalArgumentException( "Named Query '" + queryName + "' does not exist." );
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import, division, print_function, unicode_literals

from c7n.manager import resources
from c7n.query import QueryResourceManager
from c7n.utils import get_retry

@resources.register('codecommit')
class CodeRepository(QueryResourceManager):

    retry = staticmethod(get_retry(('Throttling',)))

    class resource_type(object):
        service = 'codecommit'
        enum_spec = ('list_repositories', 'repositories', None)
        batch_detail_spec = (
            'batch_get_repositories', 'repositoryNames', 'repositoryName',
            'repositories')
        id = 'repositoryId'
        name = 'repositoryName'
        date = 'creationDate'
        dimension = None
        filter_name = None

@resources.register('codebuild')
class CodeBuildProject(QueryResourceManager):

    class resource_type(object):
        service = 'codebuild'
        enum_spec = ('list_projects', 'projects', None)
        batch_detail_spec = (
            'batch_get_projects', 'names', None, 'projects')
        name = id = 'project'
        date = 'created'
        dimension = None
        filter_name = None

@resources.register('codepipeline')
class CodeDeployPipeline(QueryResourceManager):

    retry = staticmethod(get_retry(('Throttling',)))

    class resource_type(object):
        service = 'codepipeline'
        enum_spec = ('list_pipelines', 'pipelines', None)
        detail_spec = ('get_pipeline', 'name', 'name', 'pipeline')
        dimension = filter_name = None
        name = id = 'name'
        date = 'created'
        filter_name = None


text:
from zoo.orca.automl.model.base_keras_model import KerasBaseModel
from collections.abc import Iterable
import numpy as np

def model_creator(config):
    from tensorflow.keras.models import Model
    from tensorflow.keras.layers import Input, Dense, LSTM, Dropout
    import tensorflow as tf

    inp = Input(shape=(None, config["input_dim"]))
    if "lstm_1_units" in config and "lstm_2_units" in config:
        lstm_units = (config["lstm_1_units"], config["lstm_2_units"])
    else:
        lstm_units = config.get("lstm_units", [32, 32])
    if "dropout_1" in config and "dropout_2" in config:
        dropout_rates = (config["dropout_1"], config["dropout_2"])
    else:
        dropout_rates = config.get("dropouts", 0.2)
    lstm_units = [lstm_units] if not isinstance(lstm_units, Iterable) else lstm_units
    for i, unit in enumerate(lstm_units):
        return_sequences = True if i != len(lstm_units) - 1 else False
        dropout_rate = dropout_rates[i] if isinstance(dropout_rates, Iterable) else dropout_rates
        lstm_input = inp if i == 0 else dropout
        lstm = LSTM(units=unit, return_sequences=return_sequences)(lstm_input)
        dropout = Dropout(rate=dropout_rate)(lstm)
    out = Dense(config["output_dim"])(dropout)
    model = Model(inputs=inp, outputs=out)
    model.compile(loss=config.get("loss", "mse"),
                  optimizer=getattr(tf.keras.optimizers, config.get("optim", "Adam"))
                  (learning_rate=config.get("lr", 0.001)),
                  metrics=[config.get("metric", "mse")])
    return model

def check_iter_type(obj, type):
    return isinstance(obj, type) or \
        (isinstance(obj, Iterable) and all(isinstance(o, type) for o in obj))

class VanillaLSTM(KerasBaseModel):
    def __init__(self, check_optional_config=False, future_seq_len=1):
        super(VanillaLSTM, self).__init__(model_creator=model_creator,
                                          check_optional_config=check_optional_config)

    def _check_config(self, **config):
        super()._check_config(**config)
        assert isinstance(config["input_dim"], int), "'input_dim' should be int"
        assert isinstance(config["output_dim"], int), "'output_dim' should be int"
        lstm_name = "lstm_units"
        dropout_name = "dropouts"
        if lstm_name in config:
            if not check_iter_type(config[lstm_name], (int, np.integer)):
                raise ValueError(f"{lstm_name} should be int or an list/tuple of ints. "
                                 f"Got {config[lstm_name]}")
        if dropout_name in config:
            if not check_iter_type(config[dropout_name], (float, np.float)):
                raise ValueError(f"{dropout_name} should be float or a list/tuple of floats. "
                                 f"Got {config[dropout_name]}")
        if lstm_name in config and dropout_name in config:
            if (isinstance(config[lstm_name], int) and isinstance(config[dropout_name], Iterable)) \
                or (isinstance(config[lstm_name], Iterable) and
                    isinstance(config[dropout_name], Iterable) and
                    len(config[lstm_name]) != len(config[dropout_name])):
                raise ValueError(f"{lstm_name} should have the same elements num as {dropout_name}")

    def _get_required_parameters(self):
        return {"input_dim",
                "output_dim"
                } | super()._get_required_parameters()

    def _get_optional_parameters(self):
        return {"lstm_units",
                "dropouts",
                "optim",
                "lr"
                } | super()._get_optional_parameters()


text:
var
	utils    = require('./../Utils.js'),
	fs       = require('fs'),
	path     = require('path'),
	numeral  = require('numeral')
	humanize = require('humanize');

function SysInfo() {
	this.prefix   = '';
	this.version  = null;
	this.chanMngr = null;
	this.userMngr = null;
	this.stats    = {
		messages: 0
	};
}

SysInfo.prototype.getKey = function() {
	return null;
};

SysInfo.prototype.setup = function(kabukibot, eventDispatcher) {
	eventDispatcher.onCommand(null, this.onCommand.bind(this));
	eventDispatcher.onText(null, this.onText.bind(this));

	this.prefix   = kabukibot.getCommandPrefix();
	this.chanMngr = kabukibot.getChannelManager();
	this.userMngr = kabukibot.getUserManager();

	// try to read the version file
	var versionFile = path.join(__dirname, '..', '..', 'version');
	var self        = this;

	fs.readFile(versionFile, { encoding: 'utf-8' }, function(err, data) {
		if (!err) {
			self.version = data.trim();
			kabukibot.getLog().info('Version: ' + self.version);
		}
		else {
			kabukibot.getLog().warning('Could not read version file "' + versionFile + '": ' + err);
		}
	});
};

SysInfo.prototype.onText = function() {
	this.stats.messages++;
};

SysInfo.prototype.onCommand = function(command, args, message) {
	if (!message.getUser().isOperator()) return;

	if (command === this.prefix + 'uptime') {
		return message.respondToAll('I have been running for ' + utils.secondsToTime(process.uptime()) + '.');
	}

	if (command === this.prefix + 'sysinfo') {
		var response = [];

		if (this.version) {
			response.push('version ' + this.version);
		}

		response.push(utils.secondsToTime(process.uptime(), true) + ' uptime');
		response.push(this.chanMngr.getChannels().length + ' channels');
		response.push(numeral(this.stats.messages).format('0,0') + ' messages processed');

		if (args.length > 0 && args[0] === 'nerd') {
			var mem = process.memoryUsage();

			response.push(humanize.filesize(mem.rss) + ' res. size');
			response.push(humanize.filesize(mem.heapTotal) + ' heap total');
			response.push(humanize.filesize(mem.heapUsed) + ' heap used');

			// check the current stack size
			var u = this.userMngr, sizes = [], t = 0, key;

			for (key in u.subscribers) {
				if (u.subscribers.hasOwnProperty(key)) {
					t += u.subscribers[key].length;
				}
			}

			sizes.push(t + 's');
			sizes.push(u.turboUsers.length + 't');
			sizes.push(u.twitchStaff.length + 'S');
			sizes.push(u.twitchAdmins.length + 'A');
			sizes.push(utils.getObjectKeys(u.emoteSets).length + 'e');

			response.push('usermngr @ ' + sizes.join(' / '));
		}

		return message.respondToAll('System Info: ' + response.join(', '));
	}
};

module.exports = SysInfo;


text:
import logbook
import matplotlib.pyplot as plt
import numpy as np
import statsmodels.api as sm
from datetime import datetime
import pytz

from zipline.algorithm import TradingAlgorithm
from zipline.transforms import batch_transform
from zipline.utils.factory import load_from_yahoo
from zipline.api import symbol

@batch_transform
def ols_transform(data, sid1, sid2):
    """Computes regression coefficient (slope and intercept)
    via Ordinary Least Squares between two SIDs.
    """
    p0 = data.price[sid1].values
    p1 = sm.add_constant(data.price[sid2].values, prepend=True)
    slope, intercept = sm.OLS(p0, p1).fit().params

    return slope, intercept

class Pairtrade(TradingAlgorithm):
    """Pairtrading relies on cointegration of two stocks.

    The expectation is that once the two stocks drifted apart
    (i.e. there is spread), they will eventually revert again. Thus,
    if we short the upward drifting stock and long the downward
    drifting stock (in short, we buy the spread) once the spread
    widened we can sell the spread with profit once they converged
    again. A nice property of this algorithm is that we enter the
    market in a neutral position.

    This specific algorithm tries to exploit the cointegration of
    Pepsi and Coca Cola by estimating the correlation between the
    two. Divergence of the spread is evaluated by z-scoring.
    """

    def initialize(self, window_length=100):
        self.spreads = []
        self.invested = 0
        self.window_length = window_length
        self.ols_transform = ols_transform(refresh_period=self.window_length,
                                           window_length=self.window_length)
        self.PEP = self.symbol('PEP')
        self.KO = self.symbol('KO')

    def handle_data(self, data):
        ######################################################
        # 1. Compute regression coefficients between PEP and KO
        params = self.ols_transform.handle_data(data, self.PEP, self.KO)
        if params is None:
            return
        intercept, slope = params

        ######################################################
        # 2. Compute spread and zscore
        zscore = self.compute_zscore(data, slope, intercept)
        self.record(zscores=zscore,
                    PEP=data[symbol('PEP')].price,
                    KO=data[symbol('KO')].price)

        ######################################################
        # 3. Place orders
        self.place_orders(data, zscore)

    def compute_zscore(self, data, slope, intercept):
        """1. Compute the spread given slope and intercept.
           2. zscore the spread.
        """
        spread = (data[self.PEP].price -
                  (slope * data[self.KO].price + intercept))
        self.spreads.append(spread)
        spread_wind = self.spreads[-self.window_length:]
        zscore = (spread - np.mean(spread_wind)) / np.std(spread_wind)
        return zscore

    def place_orders(self, data, zscore):
        """Buy spread if zscore is > 2, sell if zscore < .5.
        """
        if zscore >= 2.0 and not self.invested:
            self.order(self.PEP, int(100 / data[self.PEP].price))
            self.order(self.KO, -int(100 / data[self.KO].price))
            self.invested = True
        elif zscore <= -2.0 and not self.invested:
            self.order(self.PEP, -int(100 / data[self.PEP].price))
            self.order(self.KO, int(100 / data[self.KO].price))
            self.invested = True
        elif abs(zscore) < .5 and self.invested:
            self.sell_spread()
            self.invested = False

    def sell_spread(self):
        """
        decrease exposure, regardless of position long/short.
        buy for a short position, sell for a long.
        """
        ko_amount = self.portfolio.positions[self.KO].amount
        self.order(self.KO, -1 * ko_amount)
        pep_amount = self.portfolio.positions[self.PEP].amount
        self.order(self.PEP, -1 * pep_amount)

# Note: this function can be removed if running
# this algorithm on quantopian.com
def analyze(context=None, results=None):
    ax1 = plt.subplot(211)
    plt.title('PepsiCo & Coca-Cola Co. share prices')
    results[['PEP', 'KO']].plot(ax=ax1)
    plt.ylabel('Price (USD)')
    plt.setp(ax1.get_xticklabels(), visible=False)

    ax2 = plt.subplot(212, sharex=ax1)
    results.zscores.plot(ax=ax2, color='r')
    plt.ylabel('Z-scored spread')

    plt.gcf().set_size_inches(18, 8)
    plt.show()

# Note: this if-block should be removed if running
# this algorithm on quantopian.com
if __name__ == '__main__':
    logbook.StderrHandler().push_application()

    # Set the simulation start and end dates.
    start = datetime(2000, 1, 1, 0, 0, 0, 0, pytz.utc)
    end = datetime(2002, 1, 1, 0, 0, 0, 0, pytz.utc)

    # Load price data from yahoo.
    data = load_from_yahoo(stocks=['PEP', 'KO'], indexes={},
                           start=start, end=end)

    # Create and run the algorithm.
    pairtrade = Pairtrade()
    results = pairtrade.run(data)

    # Plot the portfolio data.
    analyze(results=results)


text:
function tab_group(_args) {
	var win = Titanium.UI.createWindow({
		title:_args.title
	});

	// get tab group object
	var tabGroup = _args.tabGroup;

	//
	//  ADD/REMOVE TAB
	//
	var addTabButton = Titanium.UI.createButton({
		title:'Add/Remove Tab',
		top:10,
		height:40,
		width:200
	});

	// create button event listener
	addTabButton.addEventListener('click', function(e)
	{
		if (tabGroup.tabs.length == 5)
		{
			var win = Ti.UI.createWindow({title:'New Tab Window',barColor:'#000'});
			var newtab = Titanium.UI.createTab({
				icon:'/images/tabs/KS_nav_mashup.png',
				title:'New Tab',
				window:win
			});
			tabGroup.addTab(newtab);
		}
		else
		{
			var newtab = tabGroup.tabs[5];
			tabGroup.removeTab(newtab);
		}
		openLabel.text = 'Tab Group has ' + tabGroup.tabs.length + ' tabs';
	});

	//
	// ANIMATE TAB GROUP
	//
	var animateTabButton = Titanium.UI.createButton({
		title:'Animate Tab Group',
		top:60,
		height:40,
		width:200
	});

	var transformed = false;

	// create button event listener
	animateTabButton.addEventListener('click', function(e)
	{
		if (transformed === false)
		{
			var transform = Ti.UI.create2DMatrix();
			transform = transform.scale(0.6);
			transform = transform.rotate(45);
			tabGroup.animate({transform:transform,duration:1000});

			transformed = true;
		}
		else
		{
			var transform = Ti.UI.create2DMatrix();
			tabGroup.animate({transform:transform,duration:1000});

			transformed = false;
		}
	});

	//
	// CLOSE/OPEN TAB GROUP WITH ANIMATION
	//
	var closeTabGroupButton = Titanium.UI.createButton({
		title:'Close/Animate Tab Group',
		top:110,
		height:40,
		width:200
	});

	closeTabGroupButton.addEventListener('click', function(e)
	{
		tabGroup.animate({opacity:0,duration:1000}, function()
		{
			tabGroup.close();
		});

	});

	//
	// SET ACTIVE TAB (INDEX)
	//
	var setActiveTabButton = Titanium.UI.createButton({
		title:'Set Active Tab (Index)',
		top:160,
		height:40,
		width:200
	});

	setActiveTabButton.addEventListener('click', function(e)
	{
		tabGroup.setActiveTab(1);
	});

	//
	// SET ACTIVE TAB (OBJECT)
	//
	var setActiveTabObjectButton = Titanium.UI.createButton({
		title:'Set Active Tab (Object)',
		top:210,
		height:40,
		width:200
	});
	setActiveTabObjectButton.addEventListener('click', function(e)
	{
		tabGroup.setActiveTab(tabGroup.tabs[1]);
	});

	//
	// CUSTOMIZATION SWITCH - this allows or disables the ability for users to re-order tabs
	//
	var customizationButton = Titanium.UI.createButton({
		title:'Switch customization off',
		top:260,
		height:40,
		width:200
	});
	customizationButton.addEventListener('click', function(e)
	{
		var text = 'Switch customization ';
		if (tabGroup.allowUserCustomization) {
			tabGroup.allowUserCustomization = false;
			text += 'on';
		}
		else {
			tabGroup.allowUserCustomization = true;
			text += 'off';
		}
		customizationButton.title = text;
	});

	//
	// CURRENT TAB GROUP
	//
	var openLabel = Titanium.UI.createLabel({
		text:'Tab Group has ' + tabGroup.tabs.length + ' tabs',
		color:'#999',
		font:{
			fontFamily:'Helvetica Neue',
			fontSize:15
		},
		textAlign:'center',
		top:310,
		width:'auto',
		height:'auto'
	});

	// add views based on platform
	if (Titanium.Platform.name == 'iPhone OS')
	{
		win.add(addTabButton);
		win.add(animateTabButton);
		win.add(closeTabGroupButton);
		win.add(customizationButton);
	}

	win.add(setActiveTabButton);
	win.add(setActiveTabObjectButton);
	win.add(openLabel);
	return win;
};

module.exports = tab_group;


text:
package com.netsteadfast.greenstep.bsc.action;

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

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.struts2.json.annotations.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.netsteadfast.greenstep.base.action.BaseQueryGridJsonAction;
import com.netsteadfast.greenstep.base.exception.AuthorityException;
import com.netsteadfast.greenstep.base.exception.ControllerException;
import com.netsteadfast.greenstep.base.exception.ServiceException;
import com.netsteadfast.greenstep.base.model.ControllerAuthority;
import com.netsteadfast.greenstep.base.model.ControllerMethodAuthority;
import com.netsteadfast.greenstep.base.model.QueryResult;
import com.netsteadfast.greenstep.bsc.service.IKpiService;
import com.netsteadfast.greenstep.po.hbm.BbKpi;
import com.netsteadfast.greenstep.vo.KpiVO;

@ControllerAuthority(check=true)
@Controller("bsc.web.controller.KpiManagementGridQueryAction")
@Scope
public class KpiManagementGridQueryAction extends BaseQueryGridJsonAction {
	private static final long serialVersionUID = 2972896793150804788L;
	protected Logger logger=Logger.getLogger(KpiManagementGridQueryAction.class);
	private IKpiService<KpiVO, BbKpi, String> kpiService;
	private String message = "";
	private String success = IS_NO;
	private List<Map<String, String>> items=new ArrayList<Map<String, String>>();

	public KpiManagementGridQueryAction() {
		super();
	}

	@JSON(serialize=false)
	public IKpiService<KpiVO, BbKpi, String> getKpiService() {
		return kpiService;
	}

	@Autowired
	@Resource(name="bsc.service.KpiService")
	public void setKpiService(IKpiService<KpiVO, BbKpi, String> kpiService) {
		this.kpiService = kpiService;
	}

	private void query() throws ControllerException, AuthorityException, ServiceException, Exception {
		QueryResult<List<KpiVO>> queryResult = this.kpiService.findGridResult(
				super.getSearchValue(),
				super.getPageOf());
		this.success = IS_YES; // 只要有查詢 SQL 沒有產生 Exception , 就是成功, 查尋Grid沒資料也算是一種OK狀態
		if (queryResult.getValue()==null) {
			this.message=super.defaultString(queryResult.getSystemMessage().getValue());
			return;
		}
		this.setGridData(queryResult.getValue());
	}

	private void setGridData(List<KpiVO> searchList) throws Exception {
		if (searchList==null || searchList.size()<1) {
			return;
		}
		this.items = super.transformSearchGridList2JsonDataMapList(
				searchList, new String[]{"oid", "id", "name", "weight", "description",
						"visionTitle", "perspectiveName", "objectiveName"});
	}

	/**
	 * bsc.kpiManagementGridQueryAction.action
	 */
	@ControllerMethodAuthority(programId="BSC_PROG002D0004Q")
	public String execute() throws Exception {
		try {
			if (!this.allowJob()) {
				this.message = this.getNoAllowMessage();
				return SUCCESS;
			}
			this.query();
		} catch (AuthorityException | ControllerException | ServiceException e) {
			this.message = e.getMessage().toString();
		} catch (Exception e) {
			this.message = this.logException(e);
			this.success = IS_EXCEPTION;
		}
		return SUCCESS;
	}

	@JSON
	@Override
	public String getMessage() {
		return this.message;
	}

	@JSON
	@Override
	public String getSuccess() {
		return this.success;
	}

	@JSON
	@Override
	public String getLogin() {
		return super.isAccountLogin();
	}

	@JSON
	@Override
	public String getIsAuthorize() {
		return super.isActionAuthorize();
	}

	@JSON
	@Override
	public String getPageOfShowRow() {
		return super.getPageOf().getShowRow();
	}

	@JSON
	@Override
	public String getPageOfSelect() {
		return super.getPageOf().getSelect();
	}

	@JSON
	@Override
	public String getPageOfCountSize() {
		return super.getPageOf().getCountSize();
	}

	@JSON
	@Override
	public String getPageOfSize() {
		return super.getPageOf().getSize();
	}

	@JSON
	@Override
	public List<Map<String, String>> getItems() {
		return items;
	}

	@JSON
	@Override
	public List<String> getFieldsId() {
		return this.fieldsId;
	}

	@JSON
	@Override
	public Map<String, String> getFieldsMessage() {
		return this.fieldsMessage;
	}

}


text:
static char help[] = "Version of ecjac.c which shows lots of digits.  Demonstrates SNESMonitorSet().\n";

#include <petsc.h>

typedef struct {
  PetscReal  b;
} AppCtx;

extern PetscErrorCode FormFunction(SNES, Vec, Vec, void*);
extern PetscErrorCode FormJacobian(SNES, Vec, Mat, Mat, void*);
extern PetscErrorCode SpewDigitsMonitor(SNES, PetscInt, PetscReal, void*);

int main(int argc,char **argv) {
  SNES   snes;         // nonlinear solver context
  Vec    x,r;          // solution, residual vectors
  Mat    J;
  AppCtx user;

  PetscCall(PetscInitialize(&argc,&argv,NULL,help));
  user.b = 2.0;

  PetscCall(VecCreate(PETSC_COMM_WORLD,&x));
  PetscCall(VecSetSizes(x,PETSC_DECIDE,2));
  PetscCall(VecSetFromOptions(x));
  PetscCall(VecDuplicate(x,&r));

  PetscCall(MatCreate(PETSC_COMM_WORLD,&J));
  PetscCall(MatSetSizes(J,PETSC_DECIDE,PETSC_DECIDE,2,2));
  PetscCall(MatSetFromOptions(J));
  PetscCall(MatSetUp(J));

  PetscCall(SNESCreate(PETSC_COMM_WORLD,&snes));
  PetscCall(SNESSetFunction(snes,r,FormFunction,&user));
  PetscCall(SNESSetJacobian(snes,J,J,FormJacobian,&user));
  PetscCall(SNESMonitorSet(snes,SpewDigitsMonitor,&user,NULL));
  PetscCall(SNESSetFromOptions(snes));

  PetscCall(VecSet(x,1.0));
  PetscCall(SNESSolve(snes,NULL,x));

  VecDestroy(&x);  VecDestroy(&r);  SNESDestroy(&snes);  MatDestroy(&J);
  PetscCall(PetscFinalize());
  return 0;
}

PetscErrorCode FormFunction(SNES snes, Vec x, Vec F, void *ctx) {
    AppCtx          *user = (AppCtx*)ctx;
    const PetscReal b = user->b, *ax;
    PetscReal       *aF;

    PetscCall(VecGetArrayRead(x,&ax));
    PetscCall(VecGetArray(F,&aF));
    aF[0] = (1.0 / b) * PetscExpReal(b * ax[0]) - ax[1];
    aF[1] = ax[0] * ax[0] + ax[1] * ax[1] - 1.0;
    PetscCall(VecRestoreArrayRead(x,&ax));
    PetscCall(VecRestoreArray(F,&aF));
    return 0;
}

PetscErrorCode FormJacobian(SNES snes, Vec x, Mat J, Mat P, void *ctx) {
    AppCtx           *user = (AppCtx*)ctx;
    const PetscReal  b = user->b, *ax;
    PetscReal        v[4];
    PetscInt         row[2] = {0,1}, col[2] = {0,1};

    PetscCall(VecGetArrayRead(x,&ax));
    v[0] = PetscExpReal(b * ax[0]);  v[1] = -1.0;
    v[2] = 2.0 * ax[0];              v[3] = 2.0 * ax[1];
    PetscCall(MatSetValues(P,2,row,2,col,v,INSERT_VALUES));
    PetscCall(VecRestoreArrayRead(x,&ax));
    PetscCall(MatAssemblyBegin(P,MAT_FINAL_ASSEMBLY));
    PetscCall(MatAssemblyEnd(P,MAT_FINAL_ASSEMBLY));
    if (J != P) {
        PetscCall(MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY));
        PetscCall(MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY));
    }
    return 0;
}

PetscErrorCode SpewDigitsMonitor(SNES snes, PetscInt its, PetscReal norm, void *ctx) {
    Vec             x;
    const PetscReal *ax;
    PetscCall(SNESGetSolution(snes, &x));
    PetscCall(VecGetArrayRead(x,&ax));
    PetscCall(PetscPrintf(PETSC_COMM_WORLD,"  %3d:  x[0] = %18.16f,  x[1] = %18.16f\n",
                          its,ax[0],ax[1]));
    PetscCall(VecRestoreArrayRead(x,&ax));
    return 0;
}


text:
"""Tests for rmsprop."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import copy
import itertools
import math

from absl.testing import parameterized
import numpy as np

from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import test_util
from tensorflow.python.keras.optimizer_v2 import learning_rate_schedule
from tensorflow.python.keras.optimizer_v2 import rmsprop
from tensorflow.python.ops import embedding_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import resource_variable_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test

_DATA_TYPES = [dtypes.half, dtypes.float32]

_TEST_PARAM_VALUES = [
    # learning_rate, rho, momentum, epsilon, centered
    [0.05, 0.9, 0.0, 1e-3, True],
    [0.05, 0.9, 0.0, 1e-3, False],
    [0.1, 0.9, 0.0, 1e-3, True],
    [0.01, 0.9, 0.0, 1e-5, True],
    [0.01, 0.9, 0.9, 1e-5, True],
]

_TESTPARAMS = [
    [data_type] + values
    for data_type, values in itertools.product(_DATA_TYPES, _TEST_PARAM_VALUES)
]

class RMSpropOptimizerTest(test.TestCase):

  def _rmsprop_update_numpy(self, var, g, mg, rms, mom, lr, rho, momentum,
                            epsilon, centered):
    rms_t = rms * rho + (1 - rho) * g * g
    if centered:
      mg_t = mg * rho + (1 - rho) * g
      denom_t = rms_t - mg_t * mg_t
    else:
      mg_t = mg
      denom_t = rms_t
    if momentum > 0.:
      mom_t = momentum * mom + lr * g / (np.sqrt(denom_t + epsilon))
      var_t = var - mom_t
    else:
      mom_t = mom
      var_t = var - lr * g / (np.sqrt(denom_t) + epsilon)
    return var_t, mg_t, rms_t, mom_t

  def _sparse_rmsprop_update_numpy(self, var, gindexs, gvalues, mg, rms, mom,
                                   lr, rho, momentum, epsilon, centered):
    mg_t = copy.deepcopy(mg)
    rms_t = copy.deepcopy(rms)
    mom_t = copy.deepcopy(mom)
    var_t = copy.deepcopy(var)
    for i in range(len(gindexs)):
      gindex = gindexs[i]
      gvalue = gvalues[i]
      rms_t[gindex] = rms[gindex] * rho + (1 - rho) * gvalue * gvalue
      if centered:
        mg_t[gindex] = mg_t[gindex] * rho + (1 - rho) * gvalue
        denom_t = rms_t[gindex] - mg_t[gindex] * mg_t[gindex]
      else:
        denom_t = rms_t[gindex]
      if momentum > 0.:
        mom_t[gindex] = momentum * mom[gindex] + lr * gvalue / np.sqrt(denom_t +
                                                                       epsilon)
        var_t[gindex] = var[gindex] - mom_t[gindex]
      else:
        mom_t[gindex] = mom[gindex]
        var_t[gindex] = var[gindex] - lr * gvalue / (np.sqrt(denom_t) + epsilon)
    return var_t, mg_t, rms_t, mom_t

  @test_util.run_deprecated_v1
  def testDense(self):
    for (dtype, learning_rate, rho, momentum, epsilon, centered) in _TESTPARAMS:
      with test_util.use_gpu():
        # Initialize variables for numpy implementation.
        var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)
        grads0_np = np.array([0.1, 0.2], dtype=dtype.as_numpy_dtype)
        var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)
        grads1_np = np.array([0.01, 0.2], dtype=dtype.as_numpy_dtype)

        var0 = resource_variable_ops.ResourceVariable(var0_np, dtype=dtype)
        var1 = resource_variable_ops.ResourceVariable(var1_np, dtype=dtype)
        grads0 = constant_op.constant(grads0_np, dtype=dtype)
        grads1 = constant_op.constant(grads1_np, dtype=dtype)
        opt = rmsprop.RMSprop(
            learning_rate=learning_rate,
            rho=rho,
            momentum=momentum,
            epsilon=epsilon,
            centered=centered)

        update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
        self.evaluate(variables.global_variables_initializer())

        if centered:
          mg0 = opt.get_slot(var0, "mg")
          mg1 = opt.get_slot(var1, "mg")
        else:
          mg0 = None
          mg1 = None

        if momentum > 0.:
          mom0 = opt.get_slot(var0, "momentum")
          mom1 = opt.get_slot(var1, "momentum")
        else:
          mom0 = None
          mom1 = None

        rms0 = opt.get_slot(var0, "rms")
        self.assertTrue(rms0 is not None)
        rms1 = opt.get_slot(var1, "rms")
        self.assertTrue(rms1 is not None)

        mg0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
        mg1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
        rms0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
        rms1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
        mom0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
        mom1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)

        # Fetch params to validate initial values
        self.assertAllClose([1.0, 2.0], self.evaluate(var0))
        self.assertAllClose([3.0, 4.0], self.evaluate(var1))

        # Run 3 steps of RMSprop
        for _ in range(1, 4):
          self.evaluate(update)

          var0_np, mg0_np, rms0_np, mom0_np = self._rmsprop_update_numpy(
              var0_np, grads0_np, mg0_np, rms0_np, mom0_np, learning_rate, rho,
              momentum, epsilon, centered)
          var1_np, mg1_np, rms1_np, mom1_np = self._rmsprop_update_numpy(
              var1_np, grads1_np, mg1_np, rms1_np, mom1_np, learning_rate, rho,
              momentum, epsilon, centered)

          # Validate updated params
          if centered:
            self.assertAllCloseAccordingToType(mg0_np, self.evaluate(mg0))
            self.assertAllCloseAccordingToType(mg1_np, self.evaluate(mg1))
          if momentum > 0.:
            self.assertAllCloseAccordingToType(mom0_np, self.evaluate(mom0))
            self.assertAllCloseAccordingToType(mom1_np, self.evaluate(mom1))
          self.assertAllCloseAccordingToType(rms0_np, self.evaluate(rms0))
          self.assertAllCloseAccordingToType(rms1_np, self.evaluate(rms1))
          self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))
          self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))

  @test_util.run_deprecated_v1
  def testDenseWithLearningRateDecay(self):
    var0_np = np.array([1.0, 2.0])
    grads0_np = np.array([0.1, 0.2])
    var1_np = np.array([3.0, 4.0])
    grads1_np = np.array([0.01, 0.2])

    var0 = resource_variable_ops.ResourceVariable(var0_np)
    var1 = resource_variable_ops.ResourceVariable(var1_np)
    grads0 = constant_op.constant(grads0_np)
    grads1 = constant_op.constant(grads1_np)
    learning_rate = 0.01
    rho = 0.9
    momentum = 0.0
    epsilon = 1e-7
    centered = False
    decay = 0.5
    opt = rmsprop.RMSprop(
        learning_rate=learning_rate,
        rho=rho,
        momentum=momentum,
        epsilon=epsilon,
        centered=centered,
        decay=decay)

    update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
    self.evaluate(variables.global_variables_initializer())

    rms0 = opt.get_slot(var0, "rms")
    self.assertTrue(rms0 is not None)
    rms1 = opt.get_slot(var1, "rms")
    self.assertTrue(rms1 is not None)
    if momentum > 0.:
      mom0 = opt.get_slot(var0, "momentum")
      mom1 = opt.get_slot(var1, "momentum")
    else:
      mom0 = None
      mom1 = None

    mg0_np = np.array([0.0, 0.0])
    mg1_np = np.array([0.0, 0.0])
    rms0_np = np.array([0.0, 0.0])
    rms1_np = np.array([0.0, 0.0])
    mom0_np = np.array([0.0, 0.0])
    mom1_np = np.array([0.0, 0.0])

    # Fetch params to validate initial values
    self.assertAllClose([1.0, 2.0], self.evaluate(var0))
    self.assertAllClose([3.0, 4.0], self.evaluate(var1))

    # Run 4 steps of RMSprop
    for t in range(2):
      self.evaluate(update)

      lr = learning_rate / (1 + decay * t)
      var0_np, mg0_np, rms0_np, mom0_np = self._rmsprop_update_numpy(
          var0_np, grads0_np, mg0_np, rms0_np, mom0_np, lr, rho, momentum,
          epsilon, centered)
      var1_np, mg1_np, rms1_np, mom1_np = self._rmsprop_update_numpy(
          var1_np, grads1_np, mg1_np, rms1_np, mom1_np, lr, rho, momentum,
          epsilon, centered)

      # Validate updated params
      self.assertAllCloseAccordingToType(rms0_np, self.evaluate(rms0))
      self.assertAllCloseAccordingToType(rms1_np, self.evaluate(rms1))
      if momentum > 0.:
        self.assertAllCloseAccordingToType(mom0_np, self.evaluate(mom0))
        self.assertAllCloseAccordingToType(mom1_np, self.evaluate(mom1))
      self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))
      self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))

  @test_util.run_deprecated_v1
  def testDenseWithLearningRateInverseTimeDecay(self):
    var0_np = np.array([1.0, 2.0])
    grads0_np = np.array([0.1, 0.2])
    var1_np = np.array([3.0, 4.0])
    grads1_np = np.array([0.01, 0.2])

    var0 = resource_variable_ops.ResourceVariable(var0_np)
    var1 = resource_variable_ops.ResourceVariable(var1_np)
    grads0 = constant_op.constant(grads0_np)
    grads1 = constant_op.constant(grads1_np)
    learning_rate = 0.01
    rho = 0.9
    momentum = 0.0
    epsilon = 1e-7
    centered = False
    decay = 0.5
    lr_schedule = learning_rate_schedule.InverseTimeDecay(
        learning_rate, decay_steps=1.0, decay_rate=decay)
    opt = rmsprop.RMSprop(
        learning_rate=lr_schedule,
        rho=rho,
        momentum=momentum,
        epsilon=epsilon,
        centered=centered)

    update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
    self.evaluate(variables.global_variables_initializer())

    rms0 = opt.get_slot(var0, "rms")
    self.assertTrue(rms0 is not None)
    rms1 = opt.get_slot(var1, "rms")
    self.assertTrue(rms1 is not None)
    if momentum > 0.:
      mom0 = opt.get_slot(var0, "momentum")
      mom1 = opt.get_slot(var1, "momentum")
    else:
      mom0 = None
      mom1 = None

    mg0_np = np.array([0.0, 0.0])
    mg1_np = np.array([0.0, 0.0])
    rms0_np = np.array([0.0, 0.0])
    rms1_np = np.array([0.0, 0.0])
    mom0_np = np.array([0.0, 0.0])
    mom1_np = np.array([0.0, 0.0])

    # Fetch params to validate initial values
    self.assertAllClose([1.0, 2.0], self.evaluate(var0))
    self.assertAllClose([3.0, 4.0], self.evaluate(var1))

    # Run 4 steps of RMSprop
    for t in range(2):
      self.evaluate(update)

      lr = learning_rate / (1 + decay * t)
      var0_np, mg0_np, rms0_np, mom0_np = self._rmsprop_update_numpy(
          var0_np, grads0_np, mg0_np, rms0_np, mom0_np, lr, rho, momentum,
          epsilon, centered)
      var1_np, mg1_np, rms1_np, mom1_np = self._rmsprop_update_numpy(
          var1_np, grads1_np, mg1_np, rms1_np, mom1_np, lr, rho, momentum,
          epsilon, centered)

      # Validate updated params
      self.assertAllCloseAccordingToType(rms0_np, self.evaluate(rms0))
      self.assertAllCloseAccordingToType(rms1_np, self.evaluate(rms1))
      if momentum > 0.:
        self.assertAllCloseAccordingToType(mom0_np, self.evaluate(mom0))
        self.assertAllCloseAccordingToType(mom1_np, self.evaluate(mom1))
      self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))
      self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))

  @test_util.run_deprecated_v1
  def testMinimizeSparseResourceVariable(self):
    for dtype in [dtypes.float32, dtypes.float64]:
      with self.cached_session():
        var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)
        x = constant_op.constant([[4.0], [5.0]], dtype=dtype)

        def loss():
          pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x)  # pylint: disable=cell-var-from-loop
          return pred * pred

        sgd_op = rmsprop.RMSprop(
            learning_rate=1.0,
            rho=0.0,
            momentum=0.0,
            epsilon=0.0,
            centered=False).minimize(
                loss, var_list=[var0])
        self.evaluate(variables.global_variables_initializer())
        # Fetch params to validate initial values
        self.assertAllCloseAccordingToType([[1.0, 2.0]], self.evaluate(var0))
        # Run 1 step of sgd
        self.evaluate(sgd_op)
        # Validate updated params
        self.assertAllCloseAccordingToType([[0., 1.]],
                                           self.evaluate(var0),
                                           atol=0.01)

  @test_util.run_deprecated_v1
  def testMinimizeSparseResourceVariableCentered(self):
    for dtype in [dtypes.float32, dtypes.float64]:
      with self.cached_session():
        var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)
        x = constant_op.constant([[4.0], [5.0]], dtype=dtype)

        def loss():
          pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x)  # pylint: disable=cell-var-from-loop
          return pred * pred

        # loss = lambda: pred * pred  # pylint: disable=cell-var-from-loop
        sgd_op = rmsprop.RMSprop(
            learning_rate=1.0,
            rho=0.0,
            momentum=0.0,
            epsilon=1.0,
            centered=True).minimize(
                loss, var_list=[var0])
        self.evaluate(variables.global_variables_initializer())
        # Fetch params to validate initial values
        self.assertAllCloseAccordingToType([[1.0, 2.0]], self.evaluate(var0))
        # Run 1 step of sgd
        self.evaluate(sgd_op)
        # Validate updated params
        self.assertAllCloseAccordingToType([[-111, -138]],
                                           self.evaluate(var0),
                                           atol=0.01)

  @test_util.run_deprecated_v1
  def testSparse(self):
    for (dtype, learning_rate, rho, momentum, epsilon, centered) in _TESTPARAMS:
      with test_util.use_gpu():
        # Initialize variables for numpy implementation.
        var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)
        grads0_np = np.array([0.1], dtype=dtype.as_numpy_dtype)
        var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)
        grads1_np = np.array([0.01], dtype=dtype.as_numpy_dtype)

        var0 = variables.Variable(var0_np)
        var1 = variables.Variable(var1_np)
        grads0_np_indices = np.array([0], dtype=np.int32)
        grads0 = ops.IndexedSlices(
            constant_op.constant(grads0_np),
            constant_op.constant(grads0_np_indices), constant_op.constant([1]))
        grads1_np_indices = np.array([1], dtype=np.int32)
        grads1 = ops.IndexedSlices(
            constant_op.constant(grads1_np),
            constant_op.constant(grads1_np_indices), constant_op.constant([1]))
        opt = rmsprop.RMSprop(
            learning_rate=learning_rate,
            rho=rho,
            momentum=momentum,
            epsilon=epsilon,
            centered=centered)
        update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
        self.evaluate(variables.global_variables_initializer())

        if centered:
          mg0 = opt.get_slot(var0, "mg")
          self.assertEqual(mg0 is not None, centered)
          mg1 = opt.get_slot(var1, "mg")
          self.assertEqual(mg1 is not None, centered)
        else:
          mg0 = None
          mg1 = None
        rms0 = opt.get_slot(var0, "rms")
        self.assertTrue(rms0 is not None)
        rms1 = opt.get_slot(var1, "rms")
        self.assertTrue(rms1 is not None)
        if momentum > 0.:
          mom0 = opt.get_slot(var0, "momentum")
          mom1 = opt.get_slot(var1, "momentum")
        else:
          mom0 = None
          mom1 = None

        mg0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
        mg1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
        rms0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
        rms1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
        mom0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
        mom1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)

        # Fetch params to validate initial values
        self.assertAllClose([1.0, 2.0], self.evaluate(var0))
        self.assertAllClose([3.0, 4.0], self.evaluate(var1))

        # Run 3 steps of RMSprop
        for _ in range(1, 4):
          self.evaluate(update)

          var0_np, mg0_np, rms0_np, mom0_np = self._sparse_rmsprop_update_numpy(
              var0_np, grads0_np_indices, grads0_np, mg0_np, rms0_np, mom0_np,
              learning_rate, rho, momentum, epsilon, centered)
          var1_np, mg1_np, rms1_np, mom1_np = self._sparse_rmsprop_update_numpy(
              var1_np, grads1_np_indices, grads1_np, mg1_np, rms1_np, mom1_np,
              learning_rate, rho, momentum, epsilon, centered)

          # Validate updated params
          if centered:
            self.assertAllCloseAccordingToType(mg0_np, self.evaluate(mg0))
            self.assertAllCloseAccordingToType(mg1_np, self.evaluate(mg1))
          self.assertAllCloseAccordingToType(rms0_np, self.evaluate(rms0))
          self.assertAllCloseAccordingToType(rms1_np, self.evaluate(rms1))
          if momentum > 0.:
            self.assertAllCloseAccordingToType(mom0_np, self.evaluate(mom0))
            self.assertAllCloseAccordingToType(mom1_np, self.evaluate(mom1))
          self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0))
          self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1))

  def testCallableParams(self):
    with context.eager_mode():
      for dtype in [dtypes.half, dtypes.float32]:
        var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype)
        var1 = resource_variable_ops.ResourceVariable([3.0, 4.0], dtype=dtype)
        grads0 = constant_op.constant([0.1, 0.1], dtype=dtype)
        grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)

        learning_rate = lambda: 2.0
        rho = lambda: 0.9
        momentum = lambda: 0.0
        epsilon = 1.0
        opt = rmsprop.RMSprop(learning_rate, rho, momentum, epsilon)

        # Fetch params to validate initial values
        self.assertAllClose([1.0, 2.0], self.evaluate(var0))
        self.assertAllClose([3.0, 4.0], self.evaluate(var1))
        # Step 1: the rms accumulators where 1. So we should see a normal
        # update: v -= grad * learning_rate
        opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
        # Check the parameters.
        self.assertAllCloseAccordingToType(
            np.array([
                1.0 - (0.1 * 2.0 / math.sqrt(0.001 + 1.0)),
                2.0 - (0.1 * 2.0 / math.sqrt(0.001 + 1.0))
            ]), self.evaluate(var0))
        self.assertAllCloseAccordingToType(
            np.array([
                3.0 - (0.01 * 2.0 / math.sqrt(0.00001 + 1.0)),
                4.0 - (0.01 * 2.0 / math.sqrt(0.00001 + 1.0))
            ]), self.evaluate(var1))
        # Step 2: the root mean square accumulators contain the previous update.
        opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
        # Check the parameters.
        self.assertAllCloseAccordingToType(
            np.array([
                1.0 - (0.1 * 2.0 / math.sqrt(0.001 + 1.0)) -
                (0.1 * 2.0 / math.sqrt(0.001 * 0.9 + 0.001 + 1.0)),
                2.0 - (0.1 * 2.0 / math.sqrt(0.001 + 1.0)) -
                (0.1 * 2.0 / math.sqrt(0.001 * 0.9 + 0.001 + 1.0))
            ]), self.evaluate(var0))
        self.assertAllCloseAccordingToType(
            np.array([
                3.0 - (0.01 * 2.0 / math.sqrt(0.00001 + 1.0)) -
                (0.01 * 2.0 / math.sqrt(0.00001 * 0.9 + 1e-5 + 1.0)),
                4.0 - (0.01 * 2.0 / math.sqrt(0.00001 + 1.0)) -
                (0.01 * 2.0 / math.sqrt(0.00001 * 0.9 + 1e-5 + 1.0))
            ]), self.evaluate(var1))

  def testConstructRMSpropWithLR(self):
    opt = rmsprop.RMSprop(lr=1.0)
    opt_2 = rmsprop.RMSprop(learning_rate=0.1, lr=1.0)
    opt_3 = rmsprop.RMSprop(learning_rate=0.1)
    self.assertIsInstance(opt.lr, variables.Variable)
    self.assertIsInstance(opt_2.lr, variables.Variable)
    self.assertIsInstance(opt_3.lr, variables.Variable)

    self.evaluate(variables.global_variables_initializer())
    self.assertAllClose(self.evaluate(opt.lr), (1.0))
    self.assertAllClose(self.evaluate(opt_2.lr), (1.0))
    self.assertAllClose(self.evaluate(opt_3.lr), (0.1))

  def testSlotsUniqueEager(self):
    with context.eager_mode():
      v1 = variables.Variable(1.)
      v2 = variables.Variable(1.)

      opt = rmsprop.RMSprop(1., momentum=0., centered=False)
      opt.minimize(lambda: v1 + v2, var_list=[v1, v2])
      # There should be iteration, and one unique slot variable for v1 and v2.
      self.assertEqual(3, len(set(opt.variables())))
      self.assertEqual(
          self.evaluate(opt.variables()[0]), self.evaluate(opt.iterations))

      opt = rmsprop.RMSprop(learning_rate=1., momentum=0.2, centered=False)
      opt.minimize(lambda: v1 + v2, var_list=[v1, v2])
      # There should be iteration, and two unique slot variables for v1 and v2.
      self.assertEqual(5, len(set(opt.variables())))
      self.assertEqual(
          self.evaluate(opt.variables()[0]), self.evaluate(opt.iterations))

      opt = rmsprop.RMSprop(learning_rate=1., momentum=0.2, centered=True)
      opt.minimize(lambda: v1 + v2, var_list=[v1, v2])
      # There should be iteration, and three unique slot variables for v1 and v2
      self.assertEqual(7, len(set(opt.variables())))
      self.assertEqual(
          self.evaluate(opt.variables()[0]), self.evaluate(opt.iterations))

class SlotColocationTest(test.TestCase, parameterized.TestCase):

  @parameterized.parameters([True, False])
  @test_util.run_gpu_only
  @test_util.run_in_graph_and_eager_modes
  def testRunMinimizeOnGPUForCPUVariables(self, use_resource):
    with ops.device("/device:CPU:0"):
      if use_resource:
        var0 = resource_variable_ops.ResourceVariable([1.0, 2.0],
                                                      dtype=dtypes.float32)
        var1 = resource_variable_ops.ResourceVariable([3.0, 4.0],
                                                      dtype=dtypes.float32)
      else:
        var0 = variables.Variable([1.0, 2.0], dtype=dtypes.float32)
        var1 = variables.Variable([3.0, 4.0], dtype=dtypes.float32)

    def loss():
      return 5 * var0 + 3 * var1

    opt = rmsprop.RMSprop(
        learning_rate=1.0, decay=0.9, momentum=0.5, epsilon=1.0)

    # Fetch params to validate initial values
    self.evaluate(variables.global_variables_initializer())
    self.assertAllClose([1.0, 2.0], self.evaluate(var0))
    self.assertAllClose([3.0, 4.0], self.evaluate(var1))

    # Run 1 step through optimizer on GPU.
    # Slot variables are created the first time optimizer is used on some
    # variable. This tests that slot variables will be colocated with the base
    # variable.
    with ops.device("/device:GPU:0"):
      # Note that for eager execution, minimize expects a function instead of a
      # Tensor.
      opt_op = opt.minimize(loss, [var0, var1])
      self.evaluate(variables.global_variables_initializer())
      self.evaluate(opt_op)

    # Validate updated params, All variables should have decreased.
    self.assertTrue(all(v < 0.0 for v in self.evaluate(var0)),
                    msg="updated variables: %s" % self.evaluate(var0))
    self.assertTrue(all(v < 2.0 for v in self.evaluate(var1)),
                    msg="updated variables: %s" % self.evaluate(var1))

if __name__ == "__main__":
  test.main()


text:
package romelo333.notenoughwands.network;

import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import io.netty.buffer.ByteBuf;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import romelo333.notenoughwands.Items.ProtectionWand;
import romelo333.notenoughwands.ProtectedBlocks;
import romelo333.notenoughwands.varia.Coordinate;
import romelo333.notenoughwands.varia.Tools;

import java.util.HashSet;
import java.util.Set;

public class PacketGetProtectedBlocks implements IMessage,IMessageHandler<PacketGetProtectedBlocks, PacketReturnProtectedBlocks> {
    @Override
    public void fromBytes(ByteBuf buf) {
    }

    @Override
    public void toBytes(ByteBuf buf) {
    }

    public PacketGetProtectedBlocks() {
    }

    @Override
    public PacketReturnProtectedBlocks onMessage(PacketGetProtectedBlocks message, MessageContext ctx) {
        EntityPlayerMP player = ctx.getServerHandler().playerEntity;
        World world = player.worldObj;

        ItemStack heldItem = player.getHeldItem();
        if (heldItem == null || !(heldItem.getItem() instanceof ProtectionWand)) {
            // Cannot happen normally
            return null;
        }
        ProtectionWand protectionWand = (ProtectionWand) heldItem.getItem();
        int id = protectionWand.getId(heldItem);

        ProtectedBlocks protectedBlocks = ProtectedBlocks.getProtectedBlocks(world);
        Set<Coordinate> blocks = new HashSet<Coordinate>();
        protectedBlocks.fetchProtectedBlocks(blocks, world, (int)player.posX, (int)player.posY, (int)player.posZ, protectionWand.blockShowRadius, id);
        Set<Coordinate> childBlocks = new HashSet<Coordinate>();
        if (id == -1) {
            // Master wand:
            protectedBlocks.fetchProtectedBlocks(childBlocks, world, (int)player.posX, (int)player.posY, (int)player.posZ, protectionWand.blockShowRadius, -2);
        }
        return new PacketReturnProtectedBlocks(blocks, childBlocks);
    }

}


text:
grunt-seleniuminstall
=====================

Utility to install selenium web-driver


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class UnidadEjecutora extends CI_Controller {
	public function __construct(){
      parent::__construct();
	}
	public function index()
	{
		$this->_load_layout('Front/Administracion/frmUnidadEjecutora');
	}

	function _load_layout($template)
    {
      $this->load->view('layout/ADMINISTRACION/header');
      $this->load->view($template);
      $this->load->view('layout/ADMINISTRACION/footer');
    }
}


text:
import { measureText, convertCoordinateOrigin, avoidCollision } from './charts-util'
import Util from '../util/util'

export function drawRingTitle(opts, config, context) {
    let titlefontSize = opts.title.fontSize || config.titleFontSize;
    let subtitlefontSize = opts.subtitle.fontSize || config.subtitleFontSize;
    let title = opts.title.name || '';
    let subtitle = opts.subtitle.name || '';
    let titleFontColor = opts.title.color || config.titleColor;
    let subtitleFontColor = opts.subtitle.color || config.subtitleColor;
    let titleHeight = title ? titlefontSize : 0;
    let subtitleHeight = subtitle ? subtitlefontSize : 0;
    let margin = 5;
    if (subtitle) {
        let textWidth = measureText(subtitle, subtitlefontSize);
        let startX = (opts.width - textWidth) / 2 + (opts.subtitle.offsetX || 0);
        let startY = (opts.height - config.legendHeight + subtitlefontSize) / 2;
        if (title) {
            startY -= (titleHeight + margin) / 2;
        }
        context.beginPath();
        context.setFontSize(subtitlefontSize);
        context.setFillStyle(subtitleFontColor);
        context.fillText(subtitle, startX, startY);
        context.stroke();
        context.closePath();
    }
    if (title) {
        let textWidth = measureText(title, titlefontSize);
        let startX = (opts.width - textWidth) / 2 + (opts.title.offsetX || 0);
        let startY = (opts.height - config.legendHeight + titlefontSize) / 2;
        if (subtitle) {
            startY += (subtitleHeight + margin) / 2;
        }
        context.beginPath();
        context.setFontSize(titlefontSize);
        context.setFillStyle(titleFontColor);
        context.fillText(title, startX, startY);
        context.stroke();
        context.closePath();
    }
}

export function drawPointText (points, series, config, context) {
    // 绘制数据文案
    let data = series.data;

    context.beginPath();
    context.setFontSize(config.fontSize);
    context.setFillStyle('#666666');
    points.forEach(function(item, index) {
        if (item !== null) {
            let formatVal = series.format ? series.format(data[index]) : data[index];
            context.fillText(formatVal, item.x - measureText(formatVal) / 2, item.y - 2);
        }
    });
    context.closePath();
    context.stroke();
}

export function drawRadarLabel(angleList, radius, centerPosition, opts, config, context) {
    let radarOption = opts.extra.radar || {};
    radius += config.radarLabelTextMargin;
    context.beginPath();
    context.setFontSize(config.fontSize);
    context.setFillStyle(radarOption.labelColor || '#666666');
    angleList.forEach((angle, index) => {
        let pos = {
            x: radius * Math.cos(angle),
            y: radius * Math.sin(angle)
        }
        let posRelativeCanvas = convertCoordinateOrigin(pos.x, pos.y, centerPosition);
        let startX = posRelativeCanvas.x;
        let startY = posRelativeCanvas.y;
        if (Util.approximatelyEqual(pos.x, 0)) {
            startX -= measureText(opts.categories[index] || '') / 2;
        } else if (pos.x < 0) {
            startX -= measureText(opts.categories[index] || '');
        }
        context.fillText(opts.categories[index] || '', startX, startY + config.fontSize / 2);
    });
    context.stroke();
    context.closePath();
}

export function drawPieText (series, opts, config, context, radius, center) {
    let lineRadius = radius + config.pieChartLinePadding;
    let textRadius = lineRadius + config.pieChartTextPadding;
    let textObjectCollection = [];
    let lastTextObject = null;

    let seriesConvert = series.map((item) => {
        let arc = 2 * Math.PI - (item._start_ + 2 * Math.PI * item._proportion_ / 2);
        let text = item.format ? item.format(+item._proportion_.toFixed(2)) : `${Util.toFixed(item._proportion_ * 100)}%`;
        let color = item.color;
        return { arc, text, color };
    });
    seriesConvert.forEach((item) => {
        // line end
        let orginX1 = Math.cos(item.arc)  * lineRadius;
        let orginY1 = Math.sin(item.arc)  * lineRadius;

        // line start
        let orginX2 = Math.cos(item.arc)  * radius;
        let orginY2 = Math.sin(item.arc)  * radius;

        // text start
        let orginX3 = orginX1 >= 0 ? orginX1 + config.pieChartTextPadding : orginX1 - config.pieChartTextPadding ;
        let orginY3 = orginY1;

        let textWidth = measureText(item.text);
        let startY = orginY3;

        if (lastTextObject && Util.isSameXCoordinateArea(lastTextObject.start, {x: orginX3})) {
            if (orginX3 > 0) {
                startY = Math.min(orginY3, lastTextObject.start.y);
            } else if (orginX1 < 0) {
                startY = Math.max(orginY3, lastTextObject.start.y);
            } else {
                if (orginY3 > 0) {
                    startY = Math.max(orginY3, lastTextObject.start.y);
                } else {
                    startY = Math.min(orginY3, lastTextObject.start.y);
                }
            }
        }

        if (orginX3 < 0) {
            orginX3 -= textWidth;
        }

        let textObject = {
            lineStart: {
                x: orginX2,
                y: orginY2
            },
            lineEnd: {
                x: orginX1,
                y: orginY1
            },
            start: {
                x: orginX3,
                y: startY
            },
            width: textWidth,
            height: config.fontSize,
            text: item.text,
            color: item.color
        }

        lastTextObject = avoidCollision(textObject, lastTextObject);
        textObjectCollection.push(lastTextObject);
    });

    textObjectCollection.forEach((item) => {
        let lineStartPoistion = convertCoordinateOrigin(item.lineStart.x, item.lineStart.y, center);
        let lineEndPoistion = convertCoordinateOrigin(item.lineEnd.x, item.lineEnd.y, center);
        let textPosition = convertCoordinateOrigin(item.start.x, item.start.y, center);
        context.setLineWidth(1);
        context.setFontSize(config.fontSize);
        context.beginPath();
        context.setStrokeStyle(item.color);
        context.setFillStyle(item.color);
        context.moveTo(lineStartPoistion.x, lineStartPoistion.y);
        let curveStartX = item.start.x < 0 ? textPosition.x + item.width : textPosition.x;
        let textStartX = item.start.x < 0 ? textPosition.x - 5 : textPosition.x + 5;
        context.quadraticCurveTo(lineEndPoistion.x, lineEndPoistion.y, curveStartX, textPosition.y);
        context.moveTo(lineStartPoistion.x, lineStartPoistion.y);
        context.stroke();
        context.closePath();
        context.beginPath();
        context.moveTo(textPosition.x + item.width, textPosition.y);
        context.arc(curveStartX, textPosition.y, 2, 0, 2 * Math.PI);
        context.closePath();
        context.fill();
        context.beginPath();
        context.setFillStyle('#666666');
        context.fillText(item.text, textStartX, textPosition.y + 3);
        context.closePath();
        context.stroke();

        context.closePath();
    });
}


text:
namespace mediapipe {

// Example config:
//
// node {
//   calculator: "ConcatenateDetectionVectorCalculator"
//   input_stream: "detection_vector_1"
//   input_stream: "detection_vector_2"
//   output_stream: "concatenated_detection_vector"
// }
//
typedef ConcatenateVectorCalculator<::mediapipe::Detection>
    ConcatenateDetectionVectorCalculator;
MEDIAPIPE_REGISTER_NODE(ConcatenateDetectionVectorCalculator);

}  // namespace mediapipe


text:
import {Utils as _} from "../utils";
import {GridOptionsWrapper} from "../gridOptionsWrapper";
import {PopupService} from "../widgets/popupService";
import {ValueService} from "../valueService";
import {ColumnController} from "../columnController/columnController";
import {RowNode} from "../entities/rowNode";
import {Column} from "../entities/column";
import {TextFilter} from "./textFilter";
import {NumberFilter} from "./numberFilter";
import {Bean, PreDestroy, Autowired, PostConstruct, Context} from "../context/context";
import {IRowModel} from "../interfaces/iRowModel";
import {EventService} from "../eventService";
import {Events} from "../events";
import {IFilter, IFilterParams, IDoesFilterPassParams} from "../interfaces/iFilter";
import {GetQuickFilterTextParams} from "../entities/colDef";

@Bean('filterManager')
export class FilterManager {

    @Autowired('$compile') private $compile: any;
    @Autowired('$scope') private $scope: any;
    @Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
    @Autowired('gridCore') private gridCore: any;
    @Autowired('popupService') private popupService: PopupService;
    @Autowired('valueService') private valueService: ValueService;
    @Autowired('columnController') private columnController: ColumnController;
    @Autowired('rowModel') private rowModel: IRowModel;
    @Autowired('eventService') private eventService: EventService;
    @Autowired('enterprise') private enterprise: boolean;
    @Autowired('context') private context: Context;

    private allFilters: any = {};
    private quickFilter: string = null;

    private advancedFilterPresent: boolean;
    private externalFilterPresent: boolean;

    private availableFilters: {[key: string]: any} = {
        'text': TextFilter,
        'number': NumberFilter
    };

    @PostConstruct
    public init(): void {
        this.eventService.addEventListener(Events.EVENT_ROW_DATA_CHANGED, this.onNewRowsLoaded.bind(this));
        this.eventService.addEventListener(Events.EVENT_NEW_COLUMNS_LOADED, this.onNewColumnsLoaded.bind(this));

        this.quickFilter = this.parseQuickFilter(this.gridOptionsWrapper.getQuickFilterText());

        // check this here, in case there is a filter from the start
        this.checkExternalFilter();
    }

    public registerFilter(key: string, Filter: any): void {
        this.availableFilters[key] = Filter;
    }

    public setFilterModel(model: any) {
        if (model) {
            // mark the filters as we set them, so any active filters left over we stop
            var modelKeys = Object.keys(model);
            _.iterateObject(this.allFilters, (colId: string, filterWrapper: FilterWrapper) => {
                _.removeFromArray(modelKeys, colId);
                var newModel = model[colId];
                this.setModelOnFilterWrapper(filterWrapper.filter, newModel);
            });
            // at this point, processedFields contains data for which we don't have a filter working yet
            _.iterateArray(modelKeys, (colId) => {
                var column = this.columnController.getPrimaryColumn(colId);
                if (!column) {
                    console.warn('Warning ag-grid setFilterModel - no column found for colId ' + colId);
                    return;
                }
                var filterWrapper = this.getOrCreateFilterWrapper(column);
                this.setModelOnFilterWrapper(filterWrapper.filter, model[colId]);
            });
        } else {
            _.iterateObject(this.allFilters, (key, filterWrapper) => {
                this.setModelOnFilterWrapper(filterWrapper.filter, null);
            });
        }
        this.onFilterChanged();
    }

    private setModelOnFilterWrapper(filter: IFilter, newModel: any) {
        if (typeof filter.setModel !== 'function') {
            console.warn('Warning ag-grid - filter missing setModel method, which is needed for setFilterModel');
            return;
        }
        filter.setModel(newModel);
    }

    public getFilterModel() {
        var result = <any>{};
        _.iterateObject(this.allFilters, function (key: any, filterWrapper: any) {
            // because user can provide filters, we provide useful error checking and messages
            var filter: IFilter = filterWrapper.filter;
            if (typeof filter.getModel !== 'function') {
                console.warn('Warning ag-grid - filter API missing getModel method, which is needed for getFilterModel');
                return;
            }
            var model = filter.getModel();
            if (_.exists(model)) {
                result[key] = model;
            }
        });
        return result;
    }

    // returns true if any advanced filter (ie not quick filter) active
    public isAdvancedFilterPresent() {
        var atLeastOneActive = false;

        _.iterateObject(this.allFilters, function (key, filterWrapper) {
            if (filterWrapper.filter.isFilterActive()) {
                atLeastOneActive = true;
            }
        });

        return atLeastOneActive;
    }

    private updateFilterFlagInColumns(): void {
        _.iterateObject(this.allFilters, function (key, filterWrapper) {
            var filterActive = filterWrapper.filter.isFilterActive();
            filterWrapper.column.setFilterActive(filterActive);
        });
    }

    // returns true if quickFilter or advancedFilter
    public isAnyFilterPresent(): boolean {
        return this.isQuickFilterPresent() || this.advancedFilterPresent || this.externalFilterPresent;
    }

    private doesFilterPass(node: RowNode, filterToSkip?: any) {
        var data = node.data;
        var colKeys = Object.keys(this.allFilters);
        for (var i = 0, l = colKeys.length; i < l; i++) { // critical code, don't use functional programming
            var colId = colKeys[i];
            var filterWrapper = this.allFilters[colId];

            // if no filter, always pass
            if (filterWrapper === undefined) {
                continue;
            }

            if (filterWrapper.filter === filterToSkip) {
                continue
            }

            // don't bother with filters that are not active
            if (!filterWrapper.filter.isFilterActive()) {
                continue;
            }

            if (!filterWrapper.filter.doesFilterPass) { // because users can do custom filters, give nice error message
                console.error('Filter is missing method doesFilterPass');
            }
            var params: IDoesFilterPassParams = {
                node: node,
                data: data
            };
            if (!filterWrapper.filter.doesFilterPass(params)) {
                return false;
            }
        }
        // all filters passed
        return true;
    }

    private parseQuickFilter(newFilter: string): string {
        if (_.missing(newFilter) || newFilter === "") {
            return null;
        }

        if (this.gridOptionsWrapper.isRowModelVirtual()) {
            console.warn('ag-grid: cannot do quick filtering when doing virtual paging');
            return null;
        }

        return newFilter.toUpperCase();
    }

    // returns true if it has changed (not just same value again)
    public setQuickFilter(newFilter: any): void {
        var parsedFilter = this.parseQuickFilter(newFilter);
        if (this.quickFilter !== parsedFilter) {
            this.quickFilter = parsedFilter;
            this.onFilterChanged();
        }
    }

    private checkExternalFilter(): void {
        this.externalFilterPresent = this.gridOptionsWrapper.isExternalFilterPresent();
    }

    public onFilterChanged(): void {
        this.eventService.dispatchEvent(Events.EVENT_BEFORE_FILTER_CHANGED);

        this.advancedFilterPresent = this.isAdvancedFilterPresent();
        this.updateFilterFlagInColumns();
        this.checkExternalFilter();

        _.iterateObject(this.allFilters, function (key, filterWrapper) {
            if (filterWrapper.filter.onAnyFilterChanged) {
                filterWrapper.filter.onAnyFilterChanged();
            }
        });

        this.eventService.dispatchEvent(Events.EVENT_FILTER_CHANGED);

        this.eventService.dispatchEvent(Events.EVENT_AFTER_FILTER_CHANGED);
    }

    public isQuickFilterPresent(): boolean {
        return this.quickFilter !== null;
    }

    public doesRowPassOtherFilters(filterToSkip: any, node: any): boolean {
        return this.doesRowPassFilter(node, filterToSkip);
    }

    public doesRowPassFilter(node: any, filterToSkip?: any): boolean {
        //first up, check quick filter
        if (this.isQuickFilterPresent()) {
            if (!node.quickFilterAggregateText) {
                this.aggregateRowForQuickFilter(node);
            }
            if (node.quickFilterAggregateText.indexOf(this.quickFilter) < 0) {
                //quick filter fails, so skip item
                return false;
            }
        }

        //secondly, give the client a chance to reject this row
        if (this.externalFilterPresent) {
            if (!this.gridOptionsWrapper.doesExternalFilterPass(node)) {
                return false;
            }
        }

        //lastly, check our internal advanced filter
        if (this.advancedFilterPresent) {
            if (!this.doesFilterPass(node, filterToSkip)) {
                return false;
            }
        }

        //got this far, all filters pass
        return true;
    }

    private aggregateRowForQuickFilter(node: RowNode) {
        var stringParts: string[] = [];
        var columns = this.columnController.getAllPrimaryColumns();
        columns.forEach( column => {
            var value = this.valueService.getValue(column, node);

            var valueAfterCallback: any;
            var colDef = column.getColDef();
            if (column.getColDef().getQuickFilterText) {
                var params: GetQuickFilterTextParams = {
                    value: value,
                    node: node,
                    data: node.data,
                    column: column,
                    colDef: colDef
                };
                valueAfterCallback = column.getColDef().getQuickFilterText(params);
            } else {
                valueAfterCallback = value;
            }

            if (valueAfterCallback && valueAfterCallback !== '') {
                stringParts.push(valueAfterCallback.toString().toUpperCase());
            }
        });
        node.quickFilterAggregateText = stringParts.join('_');
    }

    private onNewRowsLoaded() {
        _.iterateObject(this.allFilters, function (key, filterWrapper) {
            if (filterWrapper.filter.onNewRowsLoaded) {
                filterWrapper.filter.onNewRowsLoaded();
            }
        });
        this.updateFilterFlagInColumns();
    }

    private createValueGetter(column: Column) {
        var that = this;
        return function valueGetter(node: RowNode) {
            return that.valueService.getValue(column, node);
        };
    }

    public getFilterComponent(column: Column) {
        var filterWrapper = this.getOrCreateFilterWrapper(column);
        return filterWrapper.filter;
    }

    public getOrCreateFilterWrapper(column: Column): FilterWrapper {
        var filterWrapper = this.allFilters[column.getColId()];

        if (!filterWrapper) {
            filterWrapper = this.createFilterWrapper(column);
            this.allFilters[column.getColId()] = filterWrapper;
        }

        return filterWrapper;
    }

    private createFilterInstance(column: Column): IFilter {
        let filter = column.getFilter();
        let filterIsComponent = typeof filter === 'function';
        let filterIsName = _.missing(filter) || typeof filter === 'string';
        let FilterClass: {new():IFilter};
        if (filterIsComponent) {
            // if user provided a filter, just use it
            FilterClass = <{new(): IFilter}> filter;
            // now create filter (had to cast to any to get 'new' working)
            this.assertMethodHasNoParameters(FilterClass);
        } else if (filterIsName) {
            let filterName = <string> filter;
            FilterClass = this.getFilterFromCache(filterName);
        } else {
            console.error('ag-Grid: colDef.filter should be function or a string');
            return null;
        }

        var filterInstance = new FilterClass();
        this.checkFilterHasAllMandatoryMethods(filterInstance, column);
        this.context.wireBean(filterInstance);

        return filterInstance;
    }

    private checkFilterHasAllMandatoryMethods(filterInstance: IFilter, column: Column): void {
        // help the user, check the mandatory methods exist
        ['getGui','isFilterActive','doesFilterPass','getModel','setModel'].forEach( methodName => {
            var methodIsMissing = !(<any>filterInstance)[methodName];
            if (methodIsMissing) {
                throw `Filter for column ${column.getColId()} is missing method ${methodName}`;
            }
        });
    }

    private createParams(filterWrapper: FilterWrapper): IFilterParams {
        var filterChangedCallback = this.onFilterChanged.bind(this);
        var filterModifiedCallback = () => this.eventService.dispatchEvent(Events.EVENT_FILTER_MODIFIED);
        var doesRowPassOtherFilters = this.doesRowPassOtherFilters.bind(this, filterWrapper.filter);

        var colDef = filterWrapper.column.getColDef();

        var params: IFilterParams = {
            column: filterWrapper.column,
            colDef: colDef,
            rowModel: this.rowModel,
            filterChangedCallback: filterChangedCallback,
            filterModifiedCallback: filterModifiedCallback,
            valueGetter: this.createValueGetter(filterWrapper.column),
            doesRowPassOtherFilter: doesRowPassOtherFilters,
            context: this.gridOptionsWrapper.getContext(),
            $scope: filterWrapper.scope
        };

        if (colDef.filterParams) {
            _.assign(params, colDef.filterParams);
        }

        return params;
    }

    private createFilterWrapper(column: Column): FilterWrapper {
        var filterWrapper: FilterWrapper = {
            column: column,
            filter: <IFilter> null,
            scope: <any> null,
            gui: <HTMLElement> null
        };

        filterWrapper.filter = this.createFilterInstance(column);

        this.initialiseFilterAndPutIntoGui(filterWrapper);

        return filterWrapper;
    }

    private initialiseFilterAndPutIntoGui(filterWrapper: FilterWrapper): void {
        // first up, create child scope if needed
        if (this.gridOptionsWrapper.isAngularCompileFilters()) {
            filterWrapper.scope = this.$scope.$new();
            filterWrapper.scope.context = this.gridOptionsWrapper.getContext();
        }

        var params = this.createParams(filterWrapper);
        filterWrapper.filter.init(params);

        var eFilterGui = document.createElement('div');
        eFilterGui.className = 'ag-filter';
        var guiFromFilter = filterWrapper.filter.getGui();
        if (_.isNodeOrElement(guiFromFilter)) {
            //a dom node or element was returned, so add child
            eFilterGui.appendChild(guiFromFilter);
        } else {
            //otherwise assume it was html, so just insert
            var eTextSpan = document.createElement('span');
            eTextSpan.innerHTML = guiFromFilter;
            eFilterGui.appendChild(eTextSpan);
        }

        if (filterWrapper.scope) {
            filterWrapper.gui = this.$compile(eFilterGui)(filterWrapper.scope)[0];
        } else {
            filterWrapper.gui = eFilterGui;
        }
    }

    private getFilterFromCache(filterType: string): any {
        var defaultFilterType = this.enterprise ? 'set' : 'text';
        var defaultFilter = this.availableFilters[defaultFilterType];

        if (_.missing(filterType)) {
            return defaultFilter;
        }

        if (!this.enterprise && filterType==='set') {
            console.warn('ag-Grid: Set filter is only available in Enterprise ag-Grid');
            filterType = 'text';
        }

        if (this.availableFilters[filterType]) {
            return this.availableFilters[filterType];
        } else {
            console.error('ag-Grid: Could not find filter type ' + filterType);
            return this.availableFilters[defaultFilter];
        }
    }

    private onNewColumnsLoaded(): void {
        this.destroy();
    }

    // destroys the filter, so it not longer takes part
    public destroyFilter(column: Column): void {
        var filterWrapper = this.allFilters[column.getColId()];
        if (filterWrapper) {
            this.disposeFilterWrapper(filterWrapper);
            this.onFilterChanged();
        }
    }

    private disposeFilterWrapper(filterWrapper: FilterWrapper): void {
        if (filterWrapper.filter.destroy) {
            filterWrapper.filter.destroy();
        }
        filterWrapper.column.setFilterActive(false);
        delete this.allFilters[filterWrapper.column.getColId()];
    }

    @PreDestroy
    public destroy() {
        _.iterateObject(this.allFilters, (key: string, filterWrapper: any) => {
            this.disposeFilterWrapper(filterWrapper);
        });
    }

    private assertMethodHasNoParameters(theMethod: any) {
        var getRowsParams = _.getFunctionParameters(theMethod);
        if (getRowsParams.length > 0) {
            console.warn('ag-grid: It looks like your filter is of the old type and expecting parameters in the constructor.');
            console.warn('ag-grid: From ag-grid 1.14, the constructor should take no parameters and init() used instead.');
        }
    }

}

export interface FilterWrapper {
    column: Column,
    filter: IFilter,
    scope: any,
    gui: HTMLElement
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="author" content="Adil Shaikh" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="keywords" content="Adil Shaikh" />
    <meta name="description" content="Adil Shaikh" />

    <title>Adil Shaikh</title>

    <link rel="stylesheet" href="css/plugins.css" />

    <link rel="stylesheet" href="css/style.css" />

                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbarContent" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                            Home

                            Rentals Home

                            Gallery

                            Room Details

                            Home

                            Rentals Home

                            Gallery

                            Room Details

                            Thanks for stopping by! Check out some of the rooms I have available for short-term lease below. Contact me for more information. I can be reached via Facebook Messenger or email.

Available Rooms Gallery

                    All
                    North Dallas/Richardson

DR 4BR/3.5BA Front Door

DR 4BR/3.5BA Bedroom

DR 4BR/3.5BA Kitchen

Available Rooms Details

                                1BR/1BA | $1149

Private Room in House

Private room and private bathroom in a home in North Dallas/Richardson. Includes garage parking, utilities, and internet. Furnished and unfurnished option available.

                                2BR/1BA | $1000

Two Private Rooms in House

Two private rooms and 1 attached bathroom in a home in North Dallas/Richardson. Includes utilities and internet. Furnished and unfurnished option available.

                        © 2020 Adil Shaikh


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Bull. Soc. mycol. Fr. 38: 85 (1922)

#### Original name
Phaeolus iobaphus Pat., 1922

### Remarks
null


text:
package fr.openwide.maven.artifact.notifier.web.application.artifact.model;

import java.util.List;

import org.apache.wicket.injection.Injector;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

import fr.openwide.core.wicket.more.markup.repeater.data.LoadableDetachableDataProvider;
import fr.openwide.maven.artifact.notifier.core.business.artifact.model.Artifact;
import fr.openwide.maven.artifact.notifier.core.business.artifact.service.IArtifactService;
import fr.openwide.maven.artifact.notifier.core.config.application.MavenArtifactNotifierConfigurer;

public class RecommendedArtifactDataProvider extends LoadableDetachableDataProvider<Artifact> {

	private static final long serialVersionUID = -6735682878632622767L;

	private static final Logger LOGGER = LoggerFactory.getLogger(RecommendedArtifactDataProvider.class);

	@SpringBean
	private IArtifactService artifactService;

	@SpringBean
	private MavenArtifactNotifierConfigurer configurer;

	private IModel<String> globalSearchModel;

	private IModel<String> searchGroupModel;

	private IModel<String> searchArtifactModel;

	public RecommendedArtifactDataProvider(IModel<String> globalSearchModel, IModel<String> searchGroupModel, IModel<String> searchArtifactModel) {
		Injector.get().inject(this);

		if (globalSearchModel == null || searchGroupModel == null || searchArtifactModel == null) {
			throw new IllegalArgumentException("Null models are not supported.");
		}

		this.globalSearchModel = globalSearchModel;
		this.searchGroupModel = searchGroupModel;
		this.searchArtifactModel = searchArtifactModel;
	}

	@Override
	public IModel<Artifact> model(Artifact artifact) {
		return new Model<Artifact>(artifact);
	}

	@Override
	protected List<Artifact> loadList(long first, long count) {
		// TODO : Appliquer des regex pour verifier l'entree utilisateur
		try {
			return artifactService.searchRecommended(globalSearchModel.getObject(), configurer.getAdvisableArtifactItemsLimit(),
					(int) first);
		} catch (Exception e) {
			LOGGER.error("Unable to retrieve the local artifacts for search: '" + globalSearchModel.getObject() + "'", e);
		}
		return Lists.newArrayListWithExpectedSize(0);
	}

	@Override
	protected long loadSize() {
		try {
			return artifactService.countSearchRecommended(globalSearchModel.getObject());
		} catch (Exception e) {
			LOGGER.error("Unable to retrieve the local artifacts for search: '" + globalSearchModel.getObject() + "'", e);
		}
		return 0;
	}

	@Override
	public void detach() {
		super.detach();
		if (globalSearchModel != null) {
			globalSearchModel.detach();
		}
		if (searchGroupModel != null) {
			searchGroupModel.detach();
		}
		if (searchArtifactModel != null) {
			searchArtifactModel.detach();
		}
	}
}


text:
<!DOCTYPE html>

	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
	<meta name="author" content="SemiColonWeb" />

	<link href="http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700|Roboto:300,400,500,700" rel="stylesheet" type="text/css" />
	<link rel="stylesheet" href="../css/bootstrap.css" type="text/css" />
	<link rel="stylesheet" href="../style.css" type="text/css" />

	<link rel="stylesheet" href="onepage.css" type="text/css" />

	<link rel="stylesheet" href="../css/dark.css" type="text/css" />
	<link rel="stylesheet" href="../css/font-icons.css" type="text/css" />
	<link rel="stylesheet" href="css/et-line.css" type="text/css" />
	<link rel="stylesheet" href="../css/animate.css" type="text/css" />
	<link rel="stylesheet" href="../css/magnific-popup.css" type="text/css" />

	<link rel="stylesheet" href="css/fonts.css" type="text/css" />

	<link rel="stylesheet" href="../css/responsive.css" type="text/css" />
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />

	<title>One Page Portfolio with Side Header | Canvas</title>

Home

About

Works

Services

Blog

Contact

Open Imagination

									Media, Icons

Locked Steel Gate

									Illustrations

Mac Sunglasses

									Graphics, UI Elements

Open Imagination

									Media, Icons

Console Activity

									UI Elements, Media

Open Imagination

									Media, Icons

Backpack Contents

									UI Elements, Icons

We are a Creative Media & Design Agency.

We specialize in Creating Engaging & Creative Brand Entities for New Startups.

						Get Quick Quote

Responsive Framework

Beautifully Presented

Extensively Extendable

Powerfully Customizable

Geniusly Transformable

Industrial Support

					Copyright Canvas 2015 | All Rights Reserved


text:
All Notable changes to identity-numbers will be documented in this file

### Added
- Nothing

### Deprecated
- Nothing

### Fixed
- Nothing

### Removed
- Nothing

### Security
- Nothing


text:
let process = require('process');

import { ConfigParams } from 'pip-services3-commons-node';

import { EventLogMongoDbPersistence } from '../../src/persistence/EventLogMongoDbPersistence';
import { EventLogPersistenceFixture } from './EventLogPersistenceFixture';

suite('EventLogMongoDbPersistence', ()=> {
    let persistence: EventLogMongoDbPersistence;
    let fixture: EventLogPersistenceFixture;

    setup((done) => {
        var MONGO_DB = process.env["MONGO_DB"] || "test";
        var MONGO_COLLECTION = process.env["MONGO_COLLECTION"] || "eventlog";
        var MONGO_SERVICE_HOST = process.env["MONGO_SERVICE_HOST"] || "localhost";
        var MONGO_SERVICE_PORT = process.env["MONGO_SERVICE_PORT"] || "27017";
        var MONGO_SERVICE_URI = process.env["MONGO_SERVICE_URI"];

        var dbConfig = ConfigParams.fromTuples(
            "collection", MONGO_COLLECTION,
            "connection.database", MONGO_DB,
            "connection.host", MONGO_SERVICE_HOST,
            "connection.port", MONGO_SERVICE_PORT,
            "connection.uri", MONGO_SERVICE_URI
        );

        persistence = new EventLogMongoDbPersistence();
        persistence.configure(dbConfig);

        fixture = new EventLogPersistenceFixture(persistence);

        persistence.open(null, (err: any) => {
            if (err == null) {
                persistence.clear(null, (err) => {
                    done(err);
                });
            } else {
                done(err);
            }
        });
    });

    teardown((done) => {
        persistence.close(null, done);
    });

    test('CRUD Operations', (done) => {
        fixture.testCrudOperations(done);
    });

});


text:
class QueryType < BaseObject
  field :person, PersonType, null: true do
    argument :id, ID, required: true
  end

  def person(id:)
    ElasticsearchLoader.for(User).load(orcid_from_url(id))
  end

  field :people, PersonConnectionWithMetaType, null: false, connection: true, max_page_size: 1000 do
    argument :query, String, required: false
    argument :first, Int, required: false, default_value: 25
  end

  def people(query: nil, first: nil)
    User.query(query, page: { number: 1, size: first }).results.to_a
  end

  def orcid_from_url(url)
    Array(/\A(http|https):\/\/orcid\.org\/(.+)/.match(url)).last
  end
end


text:
<!DOCTYPE html>

    <title>ufw - usage – Dhval Mudawal – Rants</title>
    <meta charset="utf-8" />
<meta content='text/html; charset=utf-8' http-equiv='Content-Type'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'>
<meta name="description" content="ufw - usage" />
<meta property="og:description" content="ufw - usage" />
<meta name="author" content="Dhval Mudawal" />
<meta property="og:title" content="ufw - usage" />
<meta property="twitter:title" content="ufw - usage" />

    <link href="/css/font-awesome.min.css">
    <link href="/dist/bootstrap/css/bootstrap.css" rel="stylesheet">

    <link href="/css/base-war.css" rel="stylesheet">
    <link href="/css/dhval.css" rel="stylesheet">
    <link href="/css/style.css" rel="stylesheet">
    <link href="/css/responsive.css" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="/style.css" />
    <link rel="alternate" type="application/rss+xml" title="Dhval Mudawal - Rants" href="/feed.xml" />

Dhval Mudawal

                     ufw - usage
                     | Updated: August 23, 2015

                Home
                About

	 View on Evernote.com

<en-note style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;">

The default firewall configuration tool for Ubuntu is ufw (Uncomplicated Firewall). Developed to ease iptables firewall configuration, ufw provides a user friendly way to create an IPv4 or IPv6 host-based firewall.

It is initially disabled. ufw is not intended to provide complete firewall functionality via its command interface, but instead provides an easy way to add or remove simple rules. It is currently mainly used for host-based firewalls.

ufw needs to be enabled

sudo ufw enable

To open a port (ssh in this example):

sudo ufw allow 22

Rules can also be added using a numbered format:

sudo ufw insert 1 allow 80

Similarly, to close an opened port:

sudo ufw deny 22

To remove a rule, use delete followed by the rule:

sudo ufw delete deny 22

It is also possible to allow access from specific hosts or networks to a port. The following example allows ssh access

</en-note>

© I do not claim ownership of this content. Please send me a message, if this infringes any copyright.


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "gaji".
 *
 * @property integer $id_gaji
 * @property integer $id_tingkatan
 * @property integer $gaji
 */
class HrdGaji extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'gaji';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_tingkatan', 'gaji'], 'required'],
            [['id_tingkatan', 'gaji'], 'integer']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id_gaji' => 'Id Gaji',
            'id_tingkatan' => 'Id Tingkatan',
            'gaji' => 'Gaji',
        ];
    }

	//Gaji
    public function findGaji(){
        $sql = "select
					id_gaji, b.tingkatan as tingkatan, b.gaji_min as gaji_min, b.gaji_max as gaji_max, gaji, persetujuan_gaji
                from gaji a, tingkatan b
				where a.id_tingkatan = b.id_tingkatan";

        return self::findBySql($sql)->asArray()->all();
    }

}


text:
<!DOCTYPE html>
<meta charset='UTF-8'><meta name="robots" content="noindex"><link rel="shortcut icon" type="image/x-icon" href="//static.codepen.io/assets/favicon/favicon-8ea04875e70c4b0bb41da869e81236e54394d63638a1ef12fa558a4a835f1164.ico" /><link rel="mask-icon" type="" href="//static.codepen.io/assets/favicon/logo-pin-f2d2b6d2c61838f7e76325261b7195c27224080bc099486ddd6dccb469b8e8e6.svg" color="#111" /><link rel="canonical" href="https://codepen.io/matikbird/pen/bqapXw" />

<link rel='stylesheet prefetch' href='https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css'>


text:
using System.Web;
using System.Web.UI;
using ServiceStack.Common;
using ServiceStack.ServiceHost;
using ServiceStack.WebHost.Endpoints.Support.Templates;

namespace ServiceStack.WebHost.Endpoints.Support.Metadata.Controls
{
    public class OperationControl
    {
        public ServiceEndpointsMetadataConfig MetadataConfig { get; set; }

        public Format Format
        {
            set
            {
                this.ContentType = Common.Web.ContentType.ToContentType(value);
                this.ContentFormat = Common.Web.ContentType.GetContentFormat(value);
            }
        }

        public IHttpRequest HttpRequest { get; set; }
        public string ContentType { get; set; }
        public string ContentFormat { get; set; }

        public string Title { get; set; }
        public string OperationName { get; set; }
        public string HostName { get; set; }
        public string RequestMessage { get; set; }
        public string ResponseMessage { get; set; }

        public string MetadataHtml { get; set; }

        public virtual string RequestUri
        {
            get
            {
                var endpointConfig = MetadataConfig.GetEndpointConfig(ContentType);
                var endpontPath = ResponseMessage != null
                    ? endpointConfig.SyncReplyUri : endpointConfig.AsyncOneWayUri;
                return string.Format("{0}/{1}", endpontPath, OperationName);
            }
        }

        public void Render(HtmlTextWriter output)
        {
            var baseUrl = HttpRequest.GetParentAbsolutePath().ToParentPath();
            if (string.IsNullOrEmpty(baseUrl))
                baseUrl = "/";
            // use a fully qualified path if WebHostUrl is set
            if (EndpointHost.Config.WebHostUrl != null)
            {
                baseUrl = EndpointHost.Config.WebHostUrl.CombineWith(baseUrl);
            }

            var renderedTemplate = HtmlTemplates.Format(HtmlTemplates.OperationControlTemplate,
                Title,
                baseUrl.CombineWith(MetadataConfig.DefaultMetadataUri),
                ContentFormat.ToUpper(),
                OperationName,
                HttpRequestTemplate,
                ResponseTemplate,
                MetadataHtml);

            output.Write(renderedTemplate);
        }

        public virtual string HttpRequestTemplate
        {
            get
            {
                return string.Format(
@"POST {0} HTTP/1.1
Host: {1}
Content-Type: {2}
Content-Length: length

{3}", RequestUri, HostName, ContentType, HttpUtility.HtmlEncode(RequestMessage));
            }
        }

        public virtual string ResponseTemplate
        {
            get
            {
                var httpResponse = this.HttpResponseTemplate;
                return string.IsNullOrEmpty(httpResponse) ? null : string.Format(@"

{0}

", httpResponse);
            }
        }

        public virtual string HttpResponseTemplate
        {
            get
            {
                if (string.IsNullOrEmpty(ResponseMessage)) return null;
                return string.Format(
@"HTTP/1.1 200 OK
Content-Type: {0}
Content-Length: length

{1}", ContentType, HttpUtility.HtmlEncode(ResponseMessage));
            }
        }
    }
}


text:
<?php
//  http://framework.zend.com/manual/current/en/in-depth-guide/services-and-servicemanager.html

 namespace Application\Service;

 use Application\Model\Item;

 interface ItemServiceInterface
 {
 	 /**
      * {@inheritDoc}
      */
     /**
      * Should return a set of all Wordage Items that we can iterate over. Single entries of the array are supposed to be
      * implementing \Application\Model\Item
      *
      * @return array|Items[]
      */
     public function findAllItems();

     /**
      * Should return a single Item
      *
      * @param  int $id Identifier of the Item that should be returned
      * @return Item
      */
     public function findItems($id);

}