text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cometbid.commerce.ut.services;

import com.cometbid.commerce.ut.cdi.ValidationInterceptor;
import com.cometbid.commerce.ut.common.BatchUploadFacade;
import com.cometbid.commerce.ut.common.DomainObject;
import com.cometbid.commerce.ut.extra.GlobalConstants;
import com.cometbid.commerce.ut.extra.MemoryCache;
import com.cometbid.commerce.ut.qualifiers.JavaUtilLogger;
import com.cometbid.commerce.ut.qualifiers.Logged;
import com.cometbid.ut.entities.CurrencyEO;
import com.cometbid.ut.exceptions.CurrencyNotFoundException;
import com.jcabi.aspects.RetryOnFailure;
import java.util.Collection;
import java.util.ArrayList;

import java.util.Iterator;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import javax.ejb.EJBException;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.persistence.OptimisticLockException;

/**
 *
 * @author Gbenga
 */
@Stateless
@Logged
public class CurrencyFacade extends BatchUploadFacade<CurrencyEO> implements CurrencyFacadeLocal {

    @PersistenceContext(unitName = "COMETBID_UT_PU")
    private EntityManager em;

    @Inject
    private MemoryCache memCache;

    @Inject
    @JavaUtilLogger
    private Logger logger;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public CurrencyFacade() {
        super(CurrencyEO.class);
    }

    /**
     *
     * @return @throws com.cometbid.ut.exceptions.CurrencyNotFoundException
     */
  //  @Lock(READ)
    @Override
    public Map<Integer, Collection<DomainObject>> getCurrenciesWithCount() throws CurrencyNotFoundException {

        try {
            Collection<DomainObject> currencies = memCache.getUtilityDataMap(GlobalConstants.currencies).values();

            if (currencies.isEmpty()) {
                logger.log(Level.SEVERE, "No Currency record found");

                throw new CurrencyNotFoundException(
                        new StringBuilder(100)
                                .append("No Currency record found")
                                .toString());
            }

            Map<Integer, Collection<DomainObject>> mapCountRecord = new HashMap<>();
            mapCountRecord.put(currencies.size(), currencies);

            return Collections.unmodifiableMap(mapCountRecord);

        } catch (ExecutionException | RuntimeException ex) {
            logger.log(Level.SEVERE, "Unexpected error occured while retrieving Currencies: {0}", ex.getMessage());

            throw new EJBException("Unexpected error occured while retrieving Currencies", ex);
        }
    }

    /**
     *
     * @return @throws com.cometbid.ut.exceptions.CurrencyNotFoundException
     */
  //  @Lock(READ)
    @Override
    public Collection<DomainObject> getCurrenciesWithoutCount() throws CurrencyNotFoundException {

        try {
            Collection<DomainObject> currencyList = memCache.getUtilityDataMap(GlobalConstants.currencies).values();
            if (currencyList.isEmpty()) {
                logger.log(Level.SEVERE, "No Currency record found");

                throw new CurrencyNotFoundException(
                        new StringBuilder(100)
                                .append("No Currency record found")
                                .toString());
            }

            return Collections.unmodifiableCollection(currencyList);
        } catch (ExecutionException | RuntimeException ex) {
            logger.log(Level.SEVERE, "Unexpected error occured while retrieving Currencies: {0}", ex.getMessage());

            throw new EJBException("Unexpected error occured while retrieving Currencies", ex);
        }
    }

    /**
     *
     * @param pageNumber
     * @param pageSize
     * @return
     * @throws com.cometbid.ut.exceptions.CurrencyNotFoundException
     */
  //  @Lock(READ)
    @Override
    public Map<Integer, Collection<DomainObject>> getCurrenciesPaginated(Integer pageNumber, Integer pageSize)
            throws CurrencyNotFoundException {

        try {
            Collection<DomainObject> currencyCollection = memCache.getUtilityDataMap(GlobalConstants.currencies).values();

            if (currencyCollection.isEmpty()) {
                logger.log(Level.SEVERE, "No Currency record found");

                throw new CurrencyNotFoundException(
                        new StringBuilder(100)
                                .append("No Currency record found")
                                .toString());
            }
            List<DomainObject> currencyList = new ArrayList<>(currencyCollection);
            int fromIndex = (pageNumber - 1) * pageSize;
            int toIndex = (pageNumber * (pageSize - 1)) + pageNumber;

            Map<Integer, Collection<DomainObject>> mapCountRecord = new HashMap<>();
            mapCountRecord.put(currencyList.size(), currencyList.subList(fromIndex, toIndex));

            return Collections.unmodifiableMap(mapCountRecord);

        } catch (ExecutionException | RuntimeException ex) {
            logger.log(Level.SEVERE, "Unexpected error occured while retrieving Currencies: {0}", ex.getMessage());

            throw new EJBException("Unexpected error occured while retrieving Currencies", ex);
        }
    }

    /**
     *
     * @param currencyId
     * @return
     * @throws com.cometbid.ut.exceptions.CurrencyNotFoundException
     */
  //  @Lock(READ)
    @Override
    public CurrencyEO getCurrencyById(Integer currencyId) throws CurrencyNotFoundException {

        try {
            DomainObject currency = memCache.getUtilityDataMap(GlobalConstants.currencies).get(currencyId);

            if (currency == null) {
                throw new CurrencyNotFoundException(
                        new StringBuilder(100)
                                .append("Currency with Id: ")
                                .append(currencyId)
                                .append(" not found")
                                .toString());
            }

            return (CurrencyEO) currency;
        } catch (ExecutionException | RuntimeException ex) {
            logger.log(Level.SEVERE, "Unexpected error occured while retrieving Currencies: {0}", ex.getMessage());

            throw new EJBException("Unexpected error occured while retrieving Currencies", ex);
        }

    }

    /**
     *
     * @param currencyId
     * @return
     * @throws com.cometbid.ut.exceptions.CurrencyNotFoundException
     */
  //  @Lock(READ)
    @Override
    public String getCurrencyCodeById(Integer currencyId) throws CurrencyNotFoundException {

        return getCurrencyById(currencyId).getCurrCode();
    }

    /**
     *
     * @param currencyId
     * @return
     * @throws com.cometbid.ut.exceptions.CurrencyNotFoundException
     */
   // @Lock(READ)
    @Override
    public String getCurrencyNameById(Integer currencyId) throws CurrencyNotFoundException {

        return getCurrencyById(currencyId).getCurrency();
    }

    /**
     *
     * @param fromCurrencyCode
     * @param toCurrencyCode
     * @return @throws com.cometbid.ut.exceptions.CurrencyNotFoundException
     */
    /*@Lock(READ)
    @Override
    public Money getCurrencyExRate(String fromCurrencyCode, String toCurrencyCode)
    throws CurrencyNotFoundException {

    double AMOUNT_TO_CONVERT = 1;
    return doCurrencyConversion(fromCurrencyCode, toCurrencyCode, AMOUNT_TO_CONVERT);
    }*/
    /**
     *
     * @param fromCurrencyCode
     * @param toCurrencyCode
     * @param amountToConvert
     * @return @throws com.cometbid.ut.exceptions.CurrencyNotFoundException
     */
    /*@Lock(READ)
    @Override
    public Money doCurrencyConversion(String fromCurrencyCode, String toCurrencyCode, double amountToConvert)
    throws CurrencyNotFoundException {

    MonetaryAmount fromAmount = Monetary.getDefaultAmountFactory().setCurrency(fromCurrencyCode)
    .setNumber(amountToConvert).create();

    CurrencyConversion currencyConvertedTo = MonetaryConversions.getConversion(toCurrencyCode);

    MonetaryAmount convertedAmount = fromAmount.with(currencyConvertedTo);

    return Money.of(convertedAmount.getNumber(),
    convertedAmount.getCurrency(),
    convertedAmount.getContext());
    }*/
    /**
     *
     * @param currencyId
     * @return
     * @throws com.cometbid.ut.exceptions.CurrencyNotFoundException
     */
  //  @Lock(READ)
    @Override
    public String getCurrencySymbol(Integer currencyId) throws CurrencyNotFoundException {

        return getCurrencyById(currencyId).getHtmlSymbol();
    }

    /**
     *
     * @param newCurrency
     * @return
     */
 //   @Lock(WRITE)
    @Override
    @Interceptors(ValidationInterceptor.class)
    public CurrencyEO addCurrency(CurrencyEO newCurrency) {

        try {
            super.create(newCurrency);

        } catch (Exception exp) {
            logger.log(Level.SEVERE, "Exception occured while creating new Currency: {0}",
                    newCurrency.getCurrCode());

            throw new EJBException(
                    new StringBuilder(100)
                            .append("An unexpected error occured while creating new Currency: ")
                            .append(newCurrency.getCurrCode())
                            .toString(), exp);
        }

        logger.log(Level.INFO, "{0} created successfully.", newCurrency.getCurrencyId());

        return newCurrency;
    }

    /**
     *
     * @param updatedCurrency
     * @return
     * @throws com.cometbid.ut.exceptions.CurrencyNotFoundException
     */
   // @Lock(WRITE)
    @Override
    @Interceptors(ValidationInterceptor.class)
    @RetryOnFailure(attempts = 3, delay = 10, unit = TimeUnit.SECONDS, types = OptimisticLockException.class)
    public CurrencyEO editCurrency(CurrencyEO updatedCurrency)
            throws CurrencyNotFoundException {

        CurrencyEO managedCurrency = super.find(updatedCurrency.getCurrencyId());
        if (managedCurrency == null) {
            throw new CurrencyNotFoundException(
                    new StringBuilder(100)
                            .append("Currency with Id: ")
                            .append(updatedCurrency.getCurrencyId())
                            .append(" not found")
                            .toString());
        }

        try {
            doCurrencyDataTransfer(managedCurrency, updatedCurrency);
            super.edit(managedCurrency);

        } catch (OptimisticLockException ex) {
            throw ex;

        } catch (Exception exp) {
            logger.log(Level.SEVERE, "Exception occured while updating currency with code: {0}",
                    updatedCurrency.getCurrCode());

            throw new EJBException(
                    new StringBuilder(100)
                            .append("An unexpected error occured while updating currency with code: ")
                            .append(updatedCurrency.getCurrCode())
                            .toString(), exp);
        }
        logger.log(Level.INFO, "Currency with id {0} updated successfully.", managedCurrency.getCurrencyId());

        return managedCurrency;
    }

    private void doCurrencyDataTransfer(CurrencyEO updatableCurrency, CurrencyEO updatedCurrency) {
        updatableCurrency.setCurrCode(updatedCurrency.getCurrCode());
        updatableCurrency.setCurrency(updatedCurrency.getCurrency());
        updatableCurrency.setExRate(updatedCurrency.getExRate());
        updatableCurrency.setHtmlSymbol(updatedCurrency.getHtmlSymbol());
        updatableCurrency.setDescription(updatedCurrency.getDescription());
        updatableCurrency.setCurrencySupported(updatedCurrency.isCurrencySupported());
    }

    /**
     *
     * @param currencyId
     * @throws com.cometbid.ut.exceptions.CurrencyNotFoundException
     */
   // @Lock(WRITE)
    @Override
    public void removeCurrency(Integer currencyId) throws CurrencyNotFoundException {

        CurrencyEO managedCurrency = super.find(currencyId);
        if (managedCurrency == null) {
            throw new CurrencyNotFoundException(
                    new StringBuilder(100)
                            .append("Currency with Id: ")
                            .append(currencyId)
                            .append(" not found")
                            .toString());
        }

        try {
            super.remove(managedCurrency);

        } catch (Exception exp) {
            logger.log(Level.SEVERE, "Exception occured while editing Currency with id: {0}",
                    managedCurrency.getCurrencyId());

            throw new EJBException(
                    new StringBuilder(100)
                            .append("An unexpected error occured while editing Currency with id: ")
                            .append(managedCurrency.getCurrencyId())
                            .toString(), exp);
        }

        logger.log(Level.INFO, "Currency with id {0} has been removed successfully.",
                managedCurrency.getCurrencyId());
    }

    @Override
    public void bulkLoadCurrencies(List<CurrencyEO> currencyList) {
        Iterator<CurrencyEO> iter = currencyList.iterator();
        while (iter.hasNext()) {
            CurrencyEO currency = iter.next();
            currency.setCurrencyId(null);

            create(currency);
        }
    }
}


text:
<?php

namespace Illuminate\Queue\Connectors;

use Aws\Sqs\SqsClient;
use Illuminate\Support\Arr;
use Illuminate\Queue\SqsQueue;

class SqsConnector implements ConnectorInterface
{
    /**
     * Establish a queue connection.
     *
     * @param  array  $config
     * @return \Illuminate\Contracts\Queue\Queue
     */
    public function connect(array $config)
    {
        $config = array_merge([
            'version' => 'latest',
            'http' => [
                'timeout' => 60,
                'connect_timeout' => 60,
            ],
        ], $config);

        if ($config['key'] && $config['secret']) {
            $config['credentials'] = Arr::only($config, ['key', 'secret']);
        }

        return new SqsQueue(new SqsClient($config), $config['queue']);
    }
}

redpajama_set_name: RedPajamaGithub


text:
// .NAME vtkQuadraticLinearWedge - cell represents a, 12-node isoparametric wedge
// .SECTION Description
// vtkQuadraticLinearWedge is a concrete implementation of vtkNonLinearCell to
// represent a three-dimensional, 12-node isoparametric linear quadratic
// wedge. The interpolation is the standard finite element, quadratic
// isoparametric shape function in xy - layer and the linear functions in z - direction.
// The cell includes mid-edge node in the triangle edges. The
// ordering of the 12 points defining the cell is point ids (0-5,6-12)
// where point ids 0-5 are the six corner vertices of the wedge; followed by
// six midedge nodes (6-12). Note that these midedge nodes correspond lie
// on the edges defined by (0,1), (1,2), (2,0), (3,4), (4,5), (5,3).
// The Edges (0,3), (1,4), (2,5) dont have midedge nodes.
//
// .SECTION See Also
// vtkQuadraticEdge vtkQuadraticTriangle vtkQuadraticTetra
// vtkQuadraticHexahedron vtkQuadraticQuad vtkQuadraticPyramid
//
// .SECTION Thanks
// Thanks to Soeren Gebbert  who developed this class and
// integrated it into VTK 5.0.

#ifndef __vtkQuadraticLinearWedge_h
#define __vtkQuadraticLinearWedge_h

#include "vtkNonLinearCell.h"

class vtkQuadraticEdge;
class vtkLine;
class vtkQuadraticLinearQuad;
class vtkQuadraticTriangle;
class vtkWedge;
class vtkDoubleArray;

class VTK_FILTERING_EXPORT vtkQuadraticLinearWedge : public vtkNonLinearCell
{
public:
  static vtkQuadraticLinearWedge *New ();
  vtkTypeMacro(vtkQuadraticLinearWedge,vtkNonLinearCell);
  void PrintSelf (ostream & os, vtkIndent indent);

  // Description:
  // Implement the vtkCell API. See the vtkCell API for descriptions
  // of these methods.
  int GetCellType () { return VTK_QUADRATIC_LINEAR_WEDGE; }
  int GetCellDimension () { return 3; }
  int GetNumberOfEdges () { return 9; }
  int GetNumberOfFaces () { return 5; }
  vtkCell *GetEdge (int edgeId);
  vtkCell *GetFace (int faceId);

  int CellBoundary (int subId, double pcoords[3], vtkIdList * pts);

  // Description:
  // The quadratic linear wege is splitted into 4 linear wedges,
  // each of them is contoured by a provided scalar value
  void Contour (double value, vtkDataArray * cellScalars,
    vtkIncrementalPointLocator * locator, vtkCellArray * verts,
    vtkCellArray * lines, vtkCellArray * polys,
    vtkPointData * inPd, vtkPointData * outPd, vtkCellData * inCd,
    vtkIdType cellId, vtkCellData * outCd);
  int EvaluatePosition (double x[3], double *closestPoint,
    int &subId, double pcoords[3], double &dist2, double *weights);
  void EvaluateLocation (int &subId, double pcoords[3], double x[3], double *weights);
  int Triangulate (int index, vtkIdList * ptIds, vtkPoints * pts);
  void Derivatives (int subId, double pcoords[3], double *values, int dim, double *derivs);
  virtual double *GetParametricCoords ();

  // Description:
  // Clip this quadratic linear wedge using scalar value provided. Like
  // contouring, except that it cuts the hex to produce linear
  // tetrahedron.
  void Clip (double value, vtkDataArray * cellScalars,
       vtkIncrementalPointLocator * locator, vtkCellArray * tetras,
       vtkPointData * inPd, vtkPointData * outPd,
       vtkCellData * inCd, vtkIdType cellId, vtkCellData * outCd, int insideOut);

  // Description:
  // Line-edge intersection. Intersection has to occur within [0,1] parametric
  // coordinates and with specified tolerance.
  int IntersectWithLine (double p1[3], double p2[3], double tol, double &t,
    double x[3], double pcoords[3], int &subId);

  // Description:
  // Return the center of the quadratic linear wedge in parametric coordinates.
  int GetParametricCenter (double pcoords[3]);

  // Description:
  // @deprecated Replaced by vtkQuadraticLinearWedge::InterpolateFunctions as of VTK 5.2
  static void InterpolationFunctions (double pcoords[3], double weights[15]);
  // Description:
  // @deprecated Replaced by vtkQuadraticLinearWedge::InterpolateDerivs as of VTK 5.2
  static void InterpolationDerivs (double pcoords[3], double derivs[45]);
  // Description:
  // Compute the interpolation functions/derivatives
  // (aka shape functions/derivatives)
  virtual void InterpolateFunctions (double pcoords[3], double weights[15])
    {
    vtkQuadraticLinearWedge::InterpolationFunctions(pcoords,weights);
    }
  virtual void InterpolateDerivs (double pcoords[3], double derivs[45])
    {
    vtkQuadraticLinearWedge::InterpolationDerivs(pcoords,derivs);
    }
  // Description:
  // Return the ids of the vertices defining edge/face (`edgeId`/`faceId').
  // Ids are related to the cell, not to the dataset.
  static int *GetEdgeArray(int edgeId);
  static int *GetFaceArray(int faceId);

  // Description:
  // Given parametric coordinates compute inverse Jacobian transformation
  // matrix. Returns 9 elements of 3x3 inverse Jacobian plus interpolation
  // function derivatives.
  void JacobianInverse (double pcoords[3], double **inverse, double derivs[45]);

protected:
  vtkQuadraticLinearWedge ();
  ~vtkQuadraticLinearWedge ();

  vtkQuadraticEdge *QuadEdge;
  vtkLine *Edge;
  vtkQuadraticTriangle *TriangleFace;
  vtkQuadraticLinearQuad *Face;
  vtkWedge *Wedge;
  vtkDoubleArray *Scalars;  //used to avoid New/Delete in contouring/clipping

private:
  vtkQuadraticLinearWedge (const vtkQuadraticLinearWedge &);  // Not implemented.
  void operator = (const vtkQuadraticLinearWedge &);  // Not implemented.
};
//----------------------------------------------------------------------------
// Return the center of the quadratic wedge in parametric coordinates.
inline int vtkQuadraticLinearWedge::GetParametricCenter(double pcoords[3])
{
  pcoords[0] = pcoords[1] = 1./3;
  pcoords[2] = 0.5;
  return 0;
}

#endif


text:
<?php
/* SVN FILE: $Id$ */
/**
 * Test App Comment Model
 *
 *
 *
 * PHP versions 4 and 5
 *
 * CakePHP :  Rapid Development Framework (http://cakephp.org)
 * Copyright 2006-2010, Cake Software Foundation, Inc.
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2006-2010, Cake Software Foundation, Inc.
 * @link          http://cakefoundation.org/projects/info/cakephp CakePHP Project
 * @package       cake
 * @subpackage    cake.cake.libs.
 * @since         CakePHP v 1.2.0.7726
 * @version       $Revision$
 * @modifiedby    $LastChangedBy$
 * @lastmodified  $Date$
 * @license       http://www.opensource.org/licenses/mit-license.php The MIT License
 */
class Post extends AppModel {
	var $useTable = 'posts';
	var $name = 'Post';
}
?>


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

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

001
016
017package net.ljcomputing.database.strategy;
018
019import net.ljcomputing.database.strategy.impl.ClassConversionStrategy;
020import net.ljcomputing.database.strategy.impl.JsonConversionStrategy;
021import net.ljcomputing.database.strategy.impl.XmlConversionStrategy;
022
023import org.springframework.stereotype.Component;
024
025/**
026 * Enumeration of database conversion strategies.
027 *
028 * @author James G. Willmore
029 *
030 */
031@Component
032public class DatabaseConversionStrategyType {
033  public enum Type {
034    CLASS(new ClassConversionStrategy()), XML(new XmlConversionStrategy()), JSON(
035        new JsonConversionStrategy());
036
037    /** The database conversion strategy. */
038    private DatabaseConversionStrategy strategy;
039
040    /**
041     * Instantiates a new database conversion strategy type.
042     *
043     * @param strategy the strategy
044     */
045    private Type(DatabaseConversionStrategy strategy) {
046      this.strategy = strategy;
047    }
048
049    /**
050     * Get the the database conversion strategy.
051     *
052     * @return the database conversion strategy
053     */
054    public DatabaseConversionStrategy strategy() {
055      return strategy;
056    }
057  }
058}


text:
using Microsoft.CSharp.RuntimeBinder;
using Mindgaze.Languages;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;

namespace Mindgaze.Languages.Tests.LanguagesTests
{
    public class StringsConfigTests
    {
        private const string StringConfigFolder = "LanguagesTestsData/StringsConfig/";
        private readonly string StringsLanguageFile = $"{StringConfigFolder}Strings.json";

        [Fact]
        public async Task CheckLanguagesDescription()
        {
            // Arrange
            MultiLanguageWorkshop workshop = new MultiLanguageWorkshop();

            // Act
            await workshop.LoadLanguages(StringsLanguageFile, $"{StringConfigFolder}Strings.config.json");

            // Assert
            Assert.Equal("English", workshop.Descriptor.Description);

            // Act
            workshop.CurrentLanguage = "ro_RO";
            // Assert
            Assert.Equal("Română", workshop.Descriptor.Description);
        }

        [Fact]
        public async Task MissingDescriptions()
        {
            // Arrange
            MultiLanguageWorkshop workshop = new MultiLanguageWorkshop();

            // Act
            await workshop.LoadLanguages($"{StringConfigFolder}Strings-missing descriptions.json", $"{StringConfigFolder}Strings-missing descriptions.config.json");

            // Assert
            Assert.ThrowsAny<RuntimeBinderException>(() =>
            {
                Assert.Equal(workshop.DefaultEmptyString, workshop.Descriptor.Description);
            });

            // Act
            workshop.CurrentLanguage = "ro_RO";
            // Assert
            Assert.Equal("Română", workshop.Descriptor.Description);
        }
    }
}


text:
With this example we show another usefull feature of jqGrid - local seraching

You need just enable it.

 HTML
<XMP>
...

</XMP>
Java Scrpt code
<XMP>
...
jQuery("#single").jqGrid({
   	url:'localset.php',
	datatype: "json",
	height: 255,
	width: 600,
   	colNames:['Index','Name', 'Code'],
   	colModel:[
   		{name:'item_id',index:'item_id', width:65, sorttype:'int'},
   		{name:'item',index:'item', width:150},
   		{name:'item_cd',index:'item_cd', width:100}
   	],
   	rowNum:50,
	rowTotal: 2000,
	rowList : [20,30,50],
	loadonce:true,
   	mtype: "GET",
	rownumbers: true,
	rownumWidth: 40,
	gridview: true,
   	pager: '#psingle',
   	sortname: 'item_id',
    viewrecords: true,
    sortorder: "asc",
	caption: "Single search on local data"
});

jQuery("#single").jqGrid('navGrid','#psingle',{del:false,add:false,edit:false});

</XMP>
PHP with MySQL
<XMP>
...
$page = $_REQUEST['page']; // get the requested page
$limit = $_REQUEST['rows']; // get how many rows we want to have into the grid
$sidx = $_REQUEST['sidx']; // get index row - i.e. user click to sort
$sord = $_REQUEST['sord']; // get the direction
if(!$sidx) $sidx =1;

$totalrows = isset($_REQUEST['totalrows']) ? $_REQUEST['totalrows']: false;
if($totalrows) {
	$limit = $totalrows;
}

// connect to the database
$db = mysql_pconnect($dbhost, $dbuser, $dbpassword)
or die("Connection Error: " . mysql_error());

mysql_select_db($database) or die("Error conecting to db.");
//populateDBRandom();
$result = mysql_query("SELECT COUNT(*) AS count FROM items");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$count = $row['count'];

if( $count >0 ) {
	$total_pages = ceil($count/$limit);
} else {
	$total_pages = 0;
}
if ($page > $total_pages) $page=$total_pages;
if ($limit<0) $limit = 0;
$start = $limit*$page - $limit; // do not put $limit*($page - 1)
if ($start<0) $start = 0;
$SQL = "SELECT item_id, item, item_cd FROM items ".$where." ORDER BY $sidx $sord LIMIT $start , $limit";
$result = mysql_query( $SQL ) or die("Couldn't execute query.".mysql_error());
$responce->page = $page;
$responce->total = $total_pages;
$responce->records = $count;
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
	$responce->rows[$i]['id']=$row[item_id];
    $responce->rows[$i]['cell']=array($row[item_id],$row[item],$row[item_cd]);
    $i++;
}
echo json_encode($responce);
mysql_close($db);
...
</XMP>


text:
dofile("common.inc");

askText = singleLine([[
  Choose window
]]);

function findImage(img)
  local tol = 5000;
  if img == "2.select" then
    tol = 10000;
  end
  return srFindImage(img .. ".png", tol);
end

function findAndClick(img, step)
  local pos = findImage(img);
  if (not pos) then
    return false;
  else
    local offset = step.offset;
    if not offset then
      offset = { 5, 2 };
    end
    srClickMouse(pos[0]+offset[1], pos[1]+offset[2], false, 50, 100, 50);
    return true;
  end
end

function moveMouse()
  local pos = srGetWindowSize();
  srSetMousePos(pos[0] / 2 + math.random(-50, 50), pos[1] / 2 + math.random(-50, 50));
end

local auto = false;
local back_pos;

function doStep(name, step)
  local ret = true;
  local count = 1;
  while findImage("quit") or findImage("back") do
    if not back_pos then
      back_pos = findImage("back");
    end
    if back_pos then
      srClickMouse(back_pos[0], back_pos[1], false, 50, 100, 50);
      moveMouse();
      sleepWithStatus(500, "Dismissed back button (" .. count .. ")", 0xFFFFFFff);
    else
      sleepWithStatus(500, "Saw quit, but not back (" .. count .. ")", 0xFFFFFFff);
    end
    count = count + 1;
    srReadScreen();
  end
  if step.click then
    local pos = srGetWindowSize();
    pos[0] = pos[0] * step.click[1];
    pos[1] = pos[1] * step.click[2];
    srClickMouse(pos[0], pos[1], false, 50, 100, 50);
    return true;
  end
  if step.sleep then
    sleepWithStatus(step.sleep, name .. ": Sleeping...", 0xFFFFFFff);
    ret = true;
  end
  if step.find_to_click then
    ret = findAndClick(step.find_to_click, step);
    if ret then
      moveMouse();
    end
  end
  return ret;
end

local prev_step = false;
local cur_step = false;
local jump_to_step = false;
local last_name = false;

function step(name, step)
  local key;
  if last_name then
    key = last_name .. name;
    if cur_step then
      prev_step = cur_step;
    end
    cur_step = key;
  end
  last_name = name;
  if jump_to_step then
    if key == jump_to_step then
      -- good!
      jump_to_step = false;
    else
      -- continue;
      sleepWithStatus(1, "Seeking step " .. jump_to_step .. ", cur=" .. key, 0xFFFFFFff);
      return;
    end
  end
  local step_failed = false;
  local did_step = false;
  local start_time = lsGetTimer();
  while 1 do
    srReadScreen();
    lsShowScreengrab(0x808080ff);
    y = 100;
    lsPrint(10, y, 1, 1, 1, 0xFFFFFFff, "Current step = " .. name);
    y = y + 32;
    if prev_step then
      --lsPrint(10, y, 1, 1, 1, 0xFFFFFFff, "Prev step = " .. prev_step);
      --y = y + 32;
    end
    if auto then
      if lsButtonText(10, y, 1, 150, 0xFFFFFFff, "Disable auto") then
        auto = false;
      end
      y = y + 32;
    end
    if auto and not did_step then
      y = y + 32;
      if doStep(name, step) then
        did_step = lsGetTimer();
      else
        step_failed = true;
        if step.skip_if_no then
          if findImage(step.skip_if_no) then
            start_time = lsGetTimer();
          else
            if lsGetTimer() - start_time > step.timeout then
              sleepWithStatus(10, "Skipping...", 0xFFFFFFff);
              return;
            end
          end
        end
      end
    end

    if not auto then
      if lsButtonText(10, y, 1, 150, 0xFFFFFFff, "Enable auto") then
        auto = true;
      end
      y = y + 32;
      if lsButtonText(10, y, 1, 200, 0xFFFFFFff, "Do step (alt+ctrl)") or (lsAltHeld() and lsControlHeld()) then
        while lsAltHeld() or lsControlHeld() do
          sleepWithStatus(100, "Release Ctrl and Alt")
        end
        if doStep(name, step) then
          did_step = lsGetTimer();
        else
          step_failed = true;
        end
      end
      y = y + 32;
    end
    if lsButtonText(10, y, 1, 150, 0xFFFFFFff, "Next step") then
      sleepWithStatus(10, "Skipping...", 0xFFFFFFff);
      return;
    end
    y = y + 32;
    if prev_step then
      if lsButtonText(10, y, 1, 150, 0xFFFFFFff, "Prev step") then
        jump_to_step = prev_step;
        sleepWithStatus(10, "Skipping...", 0xFFFFFFff);
        return;
      end
    end
    y = y + 32;
    y = y + 32;
    if step_failed then
      lsPrint(10, y, 1, 1, 1, 0xFF7777ff, "Step failed");
    end
    y = y + 32;

    message = "";
    if did_step then
      if step.done then
        -- check done condition
        local is_done = false;
        if step.inv_done then
          is_done = true;
          if findImage(step.done) then
            is_done = false;
          end
        else
          if findImage(step.done) then
            is_done = true;
          end
        end

        if is_done then
          sleepWithStatus(100, "Step complete (found image)", 0xFFFFFFff);
          return;
        else
          message = "Could not find done image ";
          -- timeout
          local timeout = 15000;
          if step.timeout then
            timeout = step.timeout;
          end
          if lsGetTimer() - did_step > timeout then
            did_step = false;
            message = "Timed out";
            if step.skip_if_no then
              if not findImage(step.skip_if_no) then
                sleepWithStatus(10, "Skipping...", 0xFFFFFFff);
                return;
              end
            end
          end
        end
      else
        sleepWithStatus(100, "Step complete", 0xFFFFFFff);
        return;
      end
    end

    sleepWithStatus(10, message, 0xFFFFFFff);
  end
end

function doit()
  local mousePos = askForWindow(askText);
  local index = 1;

  while 1 do
    step("continue", { find_to_click = "1.continue", done = "1.continue", inv_done = true });
    step("sleep", { sleep = 2000 });
    step("select zone", { find_to_click = "2.select", done = "4.done", offset = { 5, 10 }, timeout = 4000 });
    step("click heli", { find_to_click = "3.heli", done = "heli-done", timeout = 2000, skip_if_no = "3.heli" });
    step("place heli", { click = { 0.5; 0.5 }, done = "3.heli", timeout = 2000, skip_if_no = "heli-done"});
    step("done placing troops", { find_to_click = "4.done", done = "4.done", inv_done = true });
    step("win map", { sleep = 1000, done = "1.continue" });
    step("move mouse", { click = { 0.5; 0.5 }});
    step("continue", { find_to_click = "1.continue" });
    step("wait for XP", { sleep = 1000, done = "left" });
    step("dismiss victory", { click = { 0.5; 0.5 }, done = "ok"});
    step("click ok", { find_to_click = "ok", done = "ok", inv_done = true });
    step("wait for victory points", { sleep = 2000, done = "left" });
    step("dismiss victory", { click = { 0.5; 0.5 }});
  end
end


text:
/**
 * @ngdoc object
 * @name Standards.Apps
 * @description

Konga apps are essentially Angular applications who include `konga` module:

angular.module('myAwesomeApp', [ ..., 'konga', ... ]);

This will provide you with a full set of features. Yet, you have to attach the controller.

  ...

You can engage `KongaController` at any level in your app's `dom`, and Konga will work from there. But as is non intrusive and you can call it when you need it, it's recommended to be placed at the root of the structure (or in the `<body>` tag)

Then you will have all the operations engaged and your app ready to run with Konga. You need to define and inject though some metadata.

angular.module('myAwesomeApp')
  .run(['common', 'util', '$rootScope', 'metadata', function(common, util, $rootScope, metadata) {
    common.store('metadata', metadata);
    util.init(metadata);
    $rootScope.metadata = metadata;
  }]);

* * **{@link konga.common `common.store('metadata', metadata)`}:** Store the metadata in the {@link konga.commom common storage}.
* * **{@link Standards.Tools `util.init(metadata)`}:** Initialize the tools.
* * **`$rootScope.metadata = metadata`:** Save metadata on the `$rootScope`.

	When released v1.3.0, these initialisation requirements will disappear, and the `metadata` will be load using a constant with that name.

# Application configuration

## Built-in routes Routing

Konga comes with two built-in `$routes` to handle standard operations:

* * `/entity/:entityName/search`: Used for search entities of `:entityName`'s type.
* * `/entity/:entityName/:entityId`: Used for updating `:entityName`'s entity identified with `:entityId`. If the `:entityId` attribute is set to the String `new`, then the updation will be a creation, and the system will act accordingly.

You can configure several things in your konga application using {@link konga.kongaConfig `kongaConfig` value}:

## API connection APIs

Konga's built-in {@link konga.standardApi `standardApi`} needs a valid `endpoint` to connect to. This endpoint must connect to a RESTful API. If you plan to use the {@link konga.standardApi `standardApi`}, provide this value to {@link konga.kongaConfig `kongaConfig`} on startup:

angular.module('myAwesomeApp')
  .run(['kongaConfig', function(kongaConfig) {
    kongaConfig.apiEndpoint = 'http://api.konga.cloud/';
  }]);

And the standard api will be ready to work with your API.

### Using `access_tokens` to query APIs

Konga does not cover natively this feature. But once you've got covered the authentication phase, you can inject the `token` via a request interceptor. This is a handy Angular capability, and it's documented {@link https://docs.angularjs.org/api/ng/service/$http here}.

## View stack UI

Konga views are opened and kept in memory until you close them. It has also features for coming back to your view, restoring the full context and data of your previous form. This allows you to have several things opened at once.

## Application layout UI

Konga places - by default - the forms into your `<div ng-view></div>` tag when you request it via {@link Standards.Operations operations}. Furthermore, it has a layout in case you want your application to be a full Konga-powered app. If you want to use this feature, include the `main.html` view into your app's `index.html`.

This will provide you with common features such as a `toastrs`, loaders, and let you configure further your application:

### Look and feel

You can configure the application's {@link Metadata.ConfigurationParam#properties_LOOK_AND_FEEL `look&field`} via {@link Metadata.Application metadata}. There are two modes you can set your application to:

***Tabbed**

This mode displays a tabbed `navbar` on top of the `<div ng-view></div>` tag, that stores - and accesses - each of the views opened.

***Plain**

Plain rendering of the view. Here the tabs are not rendered, though still present. You can access via `$rootScope.tabs`. You can leverage the tab {@link Standards.Operations operations} for managing them in plain mode.

 */


text:
import React, { Component } from 'react';
import Helmet from 'react-helmet';
import Seo from '../components/seo';
import Sidebar from '../components/sidebar';
import Menu from '../components/menu';
import PostMeta from '../components/post/meta';
import axios from 'axios';
import { browserHistory } from 'react-router';
import { connect } from 'react-redux';
import { loadContent } from '../actions/content';
import { renderHtml } from '../utils/render';
import ContentPost from './content/post';
import ContentPage from './content/page';

import 'styles/templates/content.scss';

class Content extends Component {
  constructor (props) {
    super();
    if (props.loadContent) {
      props.loadContent(Content.getSlug(props));
    }
  }

  static getSlug = (props) => {
    const { postname, splat } = props.params;
    return postname || splat;
  }

  willReceiveProps = (nextProps) => {
    console.log('will receive props', nextProps)
  }

  renderContent () {
    const { content } = this.props;
    console.log('content.isLoading', content.isLoading, content.data.type)
    switch (content.data.type) {
      case 'post':
        return <ContentPost loading={content.isLoading} content={content} />;
      break;

      case 'page':
        return <ContentPage loading={content.isLoading} content={content} />;
      break;

      case 'error':
        // return <ContentError type={content.errorType || 404} content={content} />;
      break;

      default:
        // Loading
        return <ContentPage loading />;
      break;
    }
  }

  render () {
    const { content } = this.props;
    return (
      <div className="content">
        <main className={`content__main`}>
          {this.renderContent()}
        </main>
        <aside className='content__sidebar'>
          <Sidebar id='home' />
        </aside>
      </div>
    );
  }
}

const mapStateToProps = state => {
  return {
    content: state.content
  };
}

const mapDispatchToProps = dispatch => {
  return {
    loadContent: slug => dispatch(loadContent(slug))
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Content);


text:
module Azure::Batch::Mgmt::V2019_04_01
  module Models
    #
    # Details about the current or last completed resize operation.

    # Describes either the current operation (if the pool AllocationState is
    # Resizing) or the previously completed operation (if the AllocationState
    # is Steady).
    #
    class ResizeOperationStatus

      include MsRestAzure

      # @return [Integer] The desired number of dedicated compute nodes in the
      # pool.
      attr_accessor :target_dedicated_nodes

      # @return [Integer] The desired number of low-priority compute nodes in
      # the pool.
      attr_accessor :target_low_priority_nodes

      # @return [Duration] The timeout for allocation of compute nodes to the
      # pool or removal of compute nodes from the pool. The default value is 15
      # minutes. The minimum value is 5 minutes. If you specify a value less
      # than 5 minutes, the Batch service returns an error; if you are calling
      # the REST API directly, the HTTP status code is 400 (Bad Request).
      attr_accessor :resize_timeout

      # @return [ComputeNodeDeallocationOption] Determines what to do with a
      # node and its running task(s) if the pool size is decreasing. The
      # default value is requeue. Possible values include: 'Requeue',
      # 'Terminate', 'TaskCompletion', 'RetainedData'
      attr_accessor :node_deallocation_option

      # @return [DateTime] The time when this resize operation was started.
      attr_accessor :start_time

      # @return [Array<ResizeError>] Details of any errors encountered while
      # performing the last resize on the pool. This property is set only if an
      # error occurred during the last pool resize, and only when the pool
      # allocationState is Steady.
      attr_accessor :errors

      #
      # Mapper for ResizeOperationStatus class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ResizeOperationStatus',
          type: {
            name: 'Composite',
            class_name: 'ResizeOperationStatus',
            model_properties: {
              target_dedicated_nodes: {
                client_side_validation: true,
                required: false,
                serialized_name: 'targetDedicatedNodes',
                type: {
                  name: 'Number'
                }
              },
              target_low_priority_nodes: {
                client_side_validation: true,
                required: false,
                serialized_name: 'targetLowPriorityNodes',
                type: {
                  name: 'Number'
                }
              },
              resize_timeout: {
                client_side_validation: true,
                required: false,
                serialized_name: 'resizeTimeout',
                type: {
                  name: 'TimeSpan'
                }
              },
              node_deallocation_option: {
                client_side_validation: true,
                required: false,
                serialized_name: 'nodeDeallocationOption',
                type: {
                  name: 'Enum',
                  module: 'ComputeNodeDeallocationOption'
                }
              },
              start_time: {
                client_side_validation: true,
                required: false,
                serialized_name: 'startTime',
                type: {
                  name: 'DateTime'
                }
              },
              errors: {
                client_side_validation: true,
                required: false,
                serialized_name: 'errors',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'ResizeErrorElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'ResizeError'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
require "google/cloud/contact_center_insights/v1"

##
# Example demonstrating basic usage of
# Google::Cloud::ContactCenterInsights::V1::ContactCenterInsights::Client#get_view
#
def get_view
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::ContactCenterInsights::V1::ContactCenterInsights::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::ContactCenterInsights::V1::GetViewRequest.new

  # Call the get_view method.
  result = client.get_view request

  # The returned object is of type Google::Cloud::ContactCenterInsights::V1::View.
  p result
end
# [END contactcenterinsights_v1_generated_ContactCenterInsights_GetView_sync]


text:
/* vim: set sw=4 sts=4 : */

/*
 * Copyright (c) 2007-2011, David B. Cortarello
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *   * Redistributions of source code must retain the above copyright notice
 *     and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright notice
 *     and the following disclaimer in the documentation and/or other materials
 *     provided with the distribution.
 *   * Neither the name of Kwort nor the names of its contributors may be used
 *     to endorse or promote products derived from this software without
 *     specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
*/

#include "config.h"
#ifdef SUDOPATH

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <errno.h>
#include <pwd.h>

#if defined(__FreeBSD__)
#include <libutil.h>
#include <utmpx.h>
#else
#include <pty.h>
#include <utmp.h>
#endif

#include <termios.h>
#include <fcntl.h>

#include "errors.h"

#ifndef MAX
#define MAX(a,b) ((a)>(b)?(a):(b))
#endif

#define BUFF_SIZE 1024

static struct termios orig_termios;

/* Check user and password */
int check_password_sudo(const char *username, const char *password)
{
	int status = 0, pid = 0, pip[2];
	char *cmd[10] = { SUDOPATH, "-u", (char *)username, "-k", "-S", "-p", "", "-E", "true", NULL };
	char pass[64];

	if (pipe(pip)) err(1, "pipe()");

	if ((pid = fork()) < 0) err(1, "fork()");
	else if (pid == 0) {
		close(pip[1]);
		status = open("/dev/null", O_WRONLY);
		dup2(status, STDERR_FILENO);
		close(status);
		dup2(pip[0], STDIN_FILENO);
		execv(cmd[0], cmd);
		close(pip[0]);
		err(1, "execv()");
	}
	close(pip[0]);
	sprintf(pass, "%s\n", password);
	write(pip[1], pass, strlen(pass));
	close(pip[1]);

	waitpid(pid, &status, 0);
	if (WIFEXITED(status) && WEXITSTATUS(status) == 0)
		return ERR_SUCCESS;
	else
		if (WIFSIGNALED(status)) {
			fprintf(stderr, "Why I was signaled?: %d\n", WTERMSIG(status));
			return -1;
		}
	return ERR_WRONG_USER_OR_PASSWD;
}

/* Run the given command as the given user */
void run_sudo(char *username, char *password, char *command)
{
	char buf[BUFF_SIZE], *cmd[10] = { SUDOPATH, "-u", (char *)username, "-k", "-S", "-p", "", "-E", command, NULL };
	int fdpty = 0, status = 0, tty = 1, i = 0;
	int pip[2];
	pid_t pid;
	fd_set rfds;
	struct timeval tv;

	char pass[64];

	if (pipe(pip)) err(1, "pipe()");

	/* Creates a new terminal */
	if ((pid = forkpty(&fdpty, NULL, NULL, NULL)) < 0) err(1, "forkpty()");
	else if (pid == 0) {
		setsid();

		close(pip[1]);
		dup2(pip[0], STDIN_FILENO);
		execv(cmd[0], cmd);
		close(pip[0]);

		err(1, "execv()");
		exit(1);
	}

    close(pip[0]);
    sprintf(pass, "%s\n", password);
    write(pip[1], pass, strlen(pass));
    close(pip[1]);

	/* Put the terminal in raw mode */
	if (tcgetattr(STDIN_FILENO, &orig_termios) < 0) {
		if (errno == ENOTTY)
			errno = tty = 0;
		else
			err(1, "tcgetattr()");
	}
	if (tty)
		tty_raw(STDIN_FILENO);

	/*read(fdpty, buf, BUFF_SIZE);*/
	while (!waitpid(pid, &status, WNOHANG)) {

		/* Ok, the program needs some interaction, so this will do it fine */
		tv.tv_sec = 0;
		tv.tv_usec = 10;
		FD_ZERO(&rfds);
		FD_SET(fdpty, &rfds);
		FD_SET(STDIN_FILENO, &rfds);

		if (select(MAX(fdpty, STDIN_FILENO)+1, &rfds, NULL, NULL, &tv) < 0) err(1, "select()");

		if (FD_ISSET(fdpty, &rfds)) {
			status = read(fdpty, buf, BUFF_SIZE);
			write(STDOUT_FILENO, buf, status);
		}
		else if (FD_ISSET(STDIN_FILENO, &rfds)) {
			status = read(STDIN_FILENO, buf, BUFF_SIZE);
			write(fdpty, buf, status);
		}
		usleep(100);
	}

	close(fdpty);

	if (tty)
	    if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios) < 0)
			err(1, "tcsetattr()");
}

#endif


text:
<?php
/**
 * Script to register M2-module
 *
 * User: Alex Gusev <alex@flancer64.com>
 */
use Flancer32\Minify\Config as Config;
use Magento\Framework\Component\ComponentRegistrar as Registrar;

Registrar::register(Registrar::MODULE, Config::MODULE, __DIR__);


text:
package com.kircherelectronics.fsensor.sensor.acceleration;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

import com.kircherelectronics.fsensor.observer.SensorSubject;
import com.kircherelectronics.fsensor.sensor.FSensor;

public class LinearAccelerationSensor implements FSensor {
    private static final String TAG = LinearAccelerationSensor.class.getSimpleName();

    private final SensorManager sensorManager;
    private final SimpleSensorListener listener;
    private float startTime = 0;
    private int count = 0;

    private float[] acceleration = new float[3];
    private float[] output = new float[4];

    private int sensorDelay = SensorManager.SENSOR_DELAY_FASTEST;

    private final SensorSubject sensorSubject;

    public LinearAccelerationSensor(Context context) {
        this.sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        this.listener = new SimpleSensorListener();
        this.sensorSubject = new SensorSubject();
    }

    /**
     * Start the sensor.
     */
    @Override
    public void start() {
        startTime = 0;
        count = 0;

        registerSensors(sensorDelay);
    }

    /**
     * Stop the sensor.
     */
    @Override
    public void stop() {
        unregisterSensors();
    }

    @Override
    public void register(SensorSubject.SensorObserver sensorObserver) {
        sensorSubject.register(sensorObserver);
    }

    @Override
    public void unregister(SensorSubject.SensorObserver sensorObserver) {
        sensorSubject.unregister(sensorObserver);
    }

    /**
     * Set the sensor frequency.
     * @param sensorDelay Must be SensorManager.SENSOR_DELAY_FASTEST, SensorManager.SENSOR_DELAY_GAME, SensorManager.SENSOR_DELAY_NORMAL or SensorManager.SENSOR_DELAY_UI
     */
    public void setSensorDelay(int sensorDelay) {
        if(sensorDelay != SensorManager.SENSOR_DELAY_FASTEST && sensorDelay != SensorManager.SENSOR_DELAY_GAME && sensorDelay != SensorManager.SENSOR_DELAY_NORMAL && sensorDelay != SensorManager.SENSOR_DELAY_UI) {
            throw new IllegalStateException("Sensor Frequency must be SensorManager.SENSOR_DELAY_FASTEST, SensorManager.SENSOR_DELAY_GAME, SensorManager.SENSOR_DELAY_NORMAL or " +
                    "SensorManager.SENSOR_DELAY_UI");
        }
        this.sensorDelay = sensorDelay;
    }

    public void reset() {
        stop();
        acceleration = new float[3];
        output = new float[4];
        start();
    }

    private float calculateSensorFrequency() {
        // Initialize the start time.
        if (startTime == 0) {
            startTime = System.nanoTime();
        }

        long timestamp = System.nanoTime();

        // Find the sample period (between updates) and convert from
        // nanoseconds to seconds. Note that the sensor delivery rates can
        // individually vary by a relatively large time frame, so we use an
        // averaging technique with the number of sensor updates to
        // determine the delivery rate.

        return (count++ / ((timestamp - startTime) / 1000000000.0f));
    }

    private void processAcceleration(float[] acceleration) {
        System.arraycopy(acceleration, 0, this.acceleration, 0, this.acceleration.length);
    }

    private void registerSensors(int sensorDelay) {
        // Register for sensor updates.
        sensorManager.registerListener(listener, sensorManager
                        .getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION),
                sensorDelay);
    }

    private void unregisterSensors() {
        sensorManager.unregisterListener(listener);
    }

    private void setOutput(float[] value) {
        System.arraycopy(value, 0, output, 0, value.length);
        output[3] = calculateSensorFrequency();
        sensorSubject.onNext(output);
    }

    private class SimpleSensorListener implements SensorEventListener {

        @Override
        public void onSensorChanged(SensorEvent event) {
            if (event.sensor.getType() == Sensor.TYPE_LINEAR_ACCELERATION) {

                processAcceleration(event.values);
                setOutput(acceleration);
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {
        }
    }
}


text:
package de.psdev.formvalidations;

import android.support.annotation.NonNull;

public interface FormErrorHandler {
    void handleError(@NonNull final FieldValidationException e);

    void resetError(@NonNull final Field field);
}


text:
/*!
 * AB-fieldValidation
 */

var AB = require('another-brick');

'use strict';

function FieldValidation(el, options) {
  this.el = el;

  var dataOptions = window.AB.isJson(this.el.getAttribute('data-ab-field-validation')) ? JSON.parse(this.el.getAttribute('data-ab-field-validation')) : {};
  this.settings   = window.AB.extend(true, options, dataOptions);

  this.inputEls   = this.el.querySelectorAll('input, select, textarea');
  this.inputEl    = this.inputEls[0]; // no need to loop through inputs to get validity
  this.errorEl    = this.el.querySelector('[data-ab-field-validation-error]');
  this.formEl     = this.el.closest('[data-ab-form-validation]');
  this.isValid    = this.inputEl.validity.valid; // validity status

  this._init();
}

FieldValidation.prototype = {
  _init: function() {
    this._buildError()
        ._events();
  },

  _buildError: function() {
    if (!this.errorEl) {
      return this;
    }
    var errorList = document.createElement('ul'),
        errorId   = 'AB-'+ Math.random().toString(36); // random ID
    this.errorEl  = this.errorEl.appendChild(errorList);

    // accessibility
    this.errorEl.setAttribute('role', 'alert');
    this.errorEl.id = errorId; // for aria-describedby

    for (var i = 0, len = this.inputEls.length; i < len; i++) {
      this.inputEls[i].setAttribute('aria-describedby', errorId);
    }

    return this;
  },

  _events: function() {
    var that = this;

    // validation while typing
    if (this.settings.typing)
      this.inputEl.addEventListener('keyup', that.checkValidity.bind(that));

    for (var i = 0, len = this.inputEls.length; i < len; i++) {
      this.inputEls[i].addEventListener('change', that.checkValidity.bind(that));
    }
  },

  checkValidity: function(mode) {
    this.isValid = this.inputEl.validity.valid;

    // no validate in those cases
    if (!this.inputEl.willValidate || this.el.closest('[disabled]'))
      return this;

    this.isValid ?
      this._setValid() : this._setInvalid(mode);

    // trigger event for external usage
    var event = new CustomEvent('checked.ab-fieldvalidation', {
      detail: {
        field: this.el,
        valid: this.isValid
      }
    });
    document.dispatchEvent(event);

    // update form status (when submit, it's already done)
    if (mode !== 'submit')
      this.formEl.abFormValidation.checkValidation();
  },

  _setValid: function() {
    this._updateDom();
  },

  _setInvalid: function(mode) {
    var newList = ''; // error list

    // when submiting form we keep customError
    if (this.inputEl.validity.customError && mode === 'submit')
      return this;

    this.inputEl.setCustomValidity('');

    // building error list based on HTML5 form API
    for (var prop in this.inputEl.validity) {
      // don't check those informations
      if (prop === 'valid' || prop === 'customError')
        continue;

      if (this.inputEl.validity[prop])
        newList += '
'+ this.settings.validations[prop] +'
';
    }

    if (this.errorEl) {
      this.errorEl.innerHTML = newList;
    }

    this._updateDom();
  },

  // set custom error from outside (custom validation, ajax validation...)
  setCustomError: function(message) {
    this.inputEl.setCustomValidity(message);

    this.isValid = this.inputEl.validity.valid;
    this._updateDom();
    if (this.errorEl) {
      this.errorEl.innerHTML = '
'+ message +'
';
    }
  },

  _updateDom: function() {
    this.inputEl.setAttribute('aria-invalid', !this.isValid);

    if (this.isValid) {
      if (this.errorEl) {
        this.errorEl.innerHTML = '';
      }
      this.el.classList.add(this.settings.classValid);
      this.el.classList.remove(this.settings.classInvalid);
    } else {
      this.el.classList.add(this.settings.classInvalid);
      this.el.classList.remove(this.settings.classValid);
    }
  }
};

// prepare input inside that form
window.abFieldValidation = function(form, options) {
  var elements = form.querySelectorAll('[data-ab-field-validation]');
  for (var i = 0, len = elements.length; i < len; i++) {
    if (elements[i].abFieldValidation) continue;
    elements[i].abFieldValidation = new FieldValidation(elements[i], options);
  }
};


text:
package io.mandrel.common.unit;

import io.mandrel.common.MandrelParseException;
import io.mandrel.common.unit.TimeValue.TimeValueDeserializer;
import io.mandrel.common.unit.TimeValue.TimeValueSerializer;

import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.format.PeriodFormat;
import org.joda.time.format.PeriodFormatter;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@JsonDeserialize(using = TimeValueDeserializer.class)
@JsonSerialize(using = TimeValueSerializer.class)
public class TimeValue {

	/** How many nano-seconds in one milli-second */
	public static final long NSEC_PER_MSEC = 1000000;

	public static TimeValue timeValueNanos(long nanos) {
		return new TimeValue(nanos, TimeUnit.NANOSECONDS);
	}

	public static TimeValue timeValueMillis(long millis) {
		return new TimeValue(millis, TimeUnit.MILLISECONDS);
	}

	public static TimeValue timeValueSeconds(long seconds) {
		return new TimeValue(seconds, TimeUnit.SECONDS);
	}

	public static TimeValue timeValueMinutes(long minutes) {
		return new TimeValue(minutes, TimeUnit.MINUTES);
	}

	public static TimeValue timeValueHours(long hours) {
		return new TimeValue(hours, TimeUnit.HOURS);
	}

	private long duration;

	private TimeUnit timeUnit;

	public TimeValue(long millis) {
		this(millis, TimeUnit.MILLISECONDS);
	}

	public TimeValue(long duration, TimeUnit timeUnit) {
		this.duration = duration;
		this.timeUnit = timeUnit;
	}

	public long nanos() {
		return timeUnit.toNanos(duration);
	}

	public long getNanos() {
		return nanos();
	}

	public long micros() {
		return timeUnit.toMicros(duration);
	}

	public long getMicros() {
		return micros();
	}

	public long millis() {
		return timeUnit.toMillis(duration);
	}

	public long getMillis() {
		return millis();
	}

	public long seconds() {
		return timeUnit.toSeconds(duration);
	}

	public long getSeconds() {
		return seconds();
	}

	public long minutes() {
		return timeUnit.toMinutes(duration);
	}

	public long getMinutes() {
		return minutes();
	}

	public long hours() {
		return timeUnit.toHours(duration);
	}

	public long getHours() {
		return hours();
	}

	public long days() {
		return timeUnit.toDays(duration);
	}

	public long getDays() {
		return days();
	}

	public double microsFrac() {
		return ((double) nanos()) / C1;
	}

	public double getMicrosFrac() {
		return microsFrac();
	}

	public double millisFrac() {
		return ((double) nanos()) / C2;
	}

	public double getMillisFrac() {
		return millisFrac();
	}

	public double secondsFrac() {
		return ((double) nanos()) / C3;
	}

	public double getSecondsFrac() {
		return secondsFrac();
	}

	public double minutesFrac() {
		return ((double) nanos()) / C4;
	}

	public double getMinutesFrac() {
		return minutesFrac();
	}

	public double hoursFrac() {
		return ((double) nanos()) / C5;
	}

	public double getHoursFrac() {
		return hoursFrac();
	}

	public double daysFrac() {
		return ((double) nanos()) / C6;
	}

	public double getDaysFrac() {
		return daysFrac();
	}

	private final PeriodFormatter defaultFormatter = PeriodFormat.getDefault().withParseType(PeriodType.standard());

	public String format() {
		Period period = new Period(millis());
		return defaultFormatter.print(period);
	}

	public String format(PeriodType type) {
		Period period = new Period(millis());
		return PeriodFormat.getDefault().withParseType(type).print(period);
	}

	@Override
	public String toString() {
		if (duration < 0) {
			return Long.toString(duration);
		}
		long nanos = nanos();
		if (nanos == 0) {
			return "0s";
		}
		double value = nanos;
		String suffix = "nanos";
		if (nanos >= C6) {
			value = daysFrac();
			suffix = "d";
		} else if (nanos >= C5) {
			value = hoursFrac();
			suffix = "h";
		} else if (nanos >= C4) {
			value = minutesFrac();
			suffix = "m";
		} else if (nanos >= C3) {
			value = secondsFrac();
			suffix = "s";
		} else if (nanos >= C2) {
			value = millisFrac();
			suffix = "ms";
		} else if (nanos >= C1) {
			value = microsFrac();
			suffix = "micros";
		}
		return format1Decimals(value, suffix);
	}

	/**
	 * Format the double value with a single decimal points, trimming trailing
	 * '.0'.
	 */
	public static String format1Decimals(double value, String suffix) {
		String p = String.valueOf(value);
		int ix = p.indexOf('.') + 1;
		int ex = p.indexOf('E');
		char fraction = p.charAt(ix);
		if (fraction == '0') {
			if (ex != -1) {
				return p.substring(0, ix - 1) + p.substring(ex) + suffix;
			} else {
				return p.substring(0, ix - 1) + suffix;
			}
		} else {
			if (ex != -1) {
				return p.substring(0, ix) + fraction + p.substring(ex) + suffix;
			} else {
				return p.substring(0, ix) + fraction + suffix;
			}
		}
	}

	public static TimeValue parseTimeValue(String sValue) {
		try {
			long millis;
			String lowerSValue = sValue.toLowerCase(Locale.ROOT).trim();
			if (lowerSValue.endsWith("ms")) {
				millis = (long) (Double.parseDouble(lowerSValue.substring(0, lowerSValue.length() - 2)));
			} else if (lowerSValue.endsWith("s")) {
				millis = (long) Double.parseDouble(lowerSValue.substring(0, lowerSValue.length() - 1)) * 1000;
			} else if (lowerSValue.endsWith("m")) {
				millis = (long) (Double.parseDouble(lowerSValue.substring(0, lowerSValue.length() - 1)) * 60 * 1000);
			} else if (lowerSValue.endsWith("h")) {
				millis = (long) (Double.parseDouble(lowerSValue.substring(0, lowerSValue.length() - 1)) * 60 * 60 * 1000);
			} else if (lowerSValue.endsWith("d")) {
				millis = (long) (Double.parseDouble(lowerSValue.substring(0, lowerSValue.length() - 1)) * 24 * 60 * 60 * 1000);
			} else if (lowerSValue.endsWith("w")) {
				millis = (long) (Double.parseDouble(lowerSValue.substring(0, lowerSValue.length() - 1)) * 7 * 24 * 60 * 60 * 1000);
			} else if (lowerSValue.equals("-1")) {
				// Allow this special value to be unit-less:
				millis = -1;
			} else if (lowerSValue.equals("0")) {
				// Allow this special value to be unit-less:
				millis = 0;
			} else {
				millis = (long) Double.parseDouble(lowerSValue);
			}
			return new TimeValue(millis, TimeUnit.MILLISECONDS);
		} catch (NumberFormatException e) {
			throw new MandrelParseException("Failed to parse [{}]", e, sValue);
		}
	}

	static final long C0 = 1L;
	static final long C1 = C0 * 1000L;
	static final long C2 = C1 * 1000L;
	static final long C3 = C2 * 1000L;
	static final long C4 = C3 * 60L;
	static final long C5 = C4 * 60L;
	static final long C6 = C5 * 24L;

	@Override
	public boolean equals(Object o) {
		if (this == o)
			return true;
		if (o == null || getClass() != o.getClass())
			return false;

		TimeValue timeValue = (TimeValue) o;
		return timeUnit.toNanos(duration) == timeValue.timeUnit.toNanos(timeValue.duration);
	}

	@Override
	public int hashCode() {
		long normalized = timeUnit.toNanos(duration);
		return (int) (normalized ^ (normalized >>> 32));
	}

	public static long nsecToMSec(long ns) {
		return ns / NSEC_PER_MSEC;
	}

	public static class TimeValueDeserializer extends JsonDeserializer<TimeValue> {
		@Override
		public TimeValue deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
			String value = jp.getCodec().readValue(jp, String.class);
			return TimeValue.parseTimeValue(value);
		}
	}

	public static class TimeValueSerializer extends JsonSerializer<TimeValue> {
		@Override
		public void serialize(TimeValue value, JsonGenerator jgen, SerializerProvider serializers) throws IOException, JsonProcessingException {
			jgen.writeString(value.toString());
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_vertical" >

	<android.support.v4.view.ViewPager
    	android:id="@+id/pager"
    	android:layout_width="fill_parent"
		android:layout_height="0dip"
		android:layout_weight="1" />

    <include layout="@layout/nowplaying" />

</LinearLayout>


text:
package org.apache.camel.guice.testing;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import com.google.inject.Module;

/**
 * Specifies the default Guice Module to use when running the test case when
 * using Guicey
 * Testing
 *
 */
@Target({ TYPE })
@Retention(RUNTIME)
@Documented
public @interface UseModule {
    Class<? extends Module> value();
}


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

<TITLE>
All Classes
</TITLE>

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

GConnector

GMetric

GMetricDouble

GMetricFloat

GMetricInteger

GMetricString

GMonitor

Incrementable

Metricable


text:
---
id: environment
title: Environment
slug: /guided-tour/rendering/environment/
---

import DocsRating from '@site/src/core/DocsRating';
import {OssOnly, FbInternalOnly} from 'docusaurus-plugin-internaldocs-fb/internal';
import FbActorsAndEnvironments from './fb/FbActorsAndEnvironments.md';
import FbEnvironmentSetup from './fb/FbEnvironmentSetup.md';

## Relay Environment Provider

In order to render Relay components, you need to render a `RelayEnvironmentProvider` component at the root of the app:

```js
// App root

const {RelayEnvironmentProvider} = require('react-relay');
const Environment = require('MyEnvironment');

function Root() {
  return (
    <RelayEnvironmentProvider environment={Environment}>
      {/*... */}
    </RelayEnvironmentProvider>
  );
}
```

* The `RelayEnvironmentProvider` takes an environment, which it will make available to all descendant Relay components, and which is necessary for Relay to function.

<FbEnvironmentSetup />

## Accessing the Relay Environment

If you want to access the *current* Relay Environment within a descendant of a `RelayEnvironmentProvider` component, you can use the `useRelayEnvironment` Hook:

```js
const {useRelayEnvironment} = require('react-relay');

function UserComponent(props: Props) {
  const environment = useRelayEnvironment();

  return (...);
}
```

<FbActorsAndEnvironments />

<DocsRating />


text:
usage() {
  local message="$1"
  if [[ -n $message ]]; then
    echo "$message"
  fi
  exit
}

[[ $EUID -ne 0 ]] && usage "Need to run as root."

echo "Load useradd settings"
. /etc/default/useradd

echo "Removing items from chkconfig"
/sbin/chkconfig --del duke 2>/dev/null || echo "duke not installed"
/sbin/chkconfig --del nuke 2>/dev/null || echo "nuke not installed"

echo "Removing old files"
[[ -d /etc/opus ]] && rm -rf /etc/opus
[[ -d /usr/share/java/opus ]] && rm -rf /usr/share/java/opus
[[ -d /usr/share/javadoc/opus ]] && rm -rf /usr/share/javadoc/opus
[[ -d /var/log/opus ]] && rm -rf /var/log/opus

echo "Creating user"
/usr/bin/getent group opus || /usr/sbin/groupadd -r opus
/usr/bin/getent passwd opus || /usr/sbin/useradd -r -d /home/opus -g opus -s /bin/bash opus

if [ ! -d /home/opus ]; then
  echo "useradd did not create home directory for opus user"
  mkdir -p /home/opus
  /bin/chown opus:opus -R /home/opus
fi

echo "Creating directories"
mkdir -p {/etc/opus,/usr/share/java/opus,/usr/share/javadoc/opus,/var/log/opus/nuke,/var/log/opus/duke}

echo "Copying files"
cp -R ./etc/opus/* /etc/opus
mv ./etc/rc.d/init.d/duke.sh /etc/rc.d/init.d/duke
mv ./etc/rc.d/init.d/nuke.sh /etc/rc.d/init.d/nuke
cp -R ./usr/share/java/opus/* /usr/share/java/opus
cp -R ./usr/share/javadoc/opus/* /usr/share/javadoc/opus

echo "Creating symlinks"
ln -sf /usr/share/java/opus/common*.jar /usr/share/java/opus/common.jar
ln -sf /usr/share/java/opus/duke*.jar /usr/share/java/opus/duke.jar
ln -sf /usr/share/java/opus/nuke*.jar /usr/share/java/opus/nuke.jar

echo "Adding items to chkconfig"
/sbin/chkconfig --add nuke
/sbin/chkconfig --add duke

echo "Setting up folder permissions"
/bin/chown opus:opus -R /etc/opus
/bin/chown opus:opus -R /usr/share/java/opus
/bin/chown opus:opus -R /usr/share/javadoc/opus
/bin/chown opus:opus -R /var/log/opus

echo "Setting rwx rights on folders"
/bin/chmod 775 -R /etc/opus


text:
<?php

namespace Zelenin\Telegram\Bot\Type;

class ReplyKeyboardHide extends ReplyMarkup
{
    /**
     * Requests clients to hide the custom keyboard
     *
     * @var boolean
     */
    public $hide_keyboard = true;
}


text:
//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN
// ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED
// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//==============================================================================
//
// Author: Chip Vincent (cvincent@us.ibm.com)
//
// Modified By: Roger Kumpf, Hewlett-Packard Company (roger_kumpf@hp.com)
//              Nitin Upasani, Hewlett-Packard Company (Nitin_Upasani@hp.com)
//              Mike Day, IBM (mdday@us.ibm.com)
//              Yi Zhou, Hewlett-Packard Company (yi_zhou@hp.com)
//
//%/////////////////////////////////////////////////////////////////////////////

#ifndef Pegasus_ProviderFacade_h
#define Pegasus_ProviderFacade_h

#include <Pegasus/Common/Config.h>
#include <Pegasus/Common/IPC.h>
#include <Pegasus/Provider/CIMProvider.h>
#include <Pegasus/Provider/CIMInstanceQueryProvider.h>
#include <Pegasus/Provider/CIMAssociationProvider.h>
#include <Pegasus/Provider/CIMMethodProvider.h>
#include <Pegasus/Provider/CIMIndicationProvider.h>
#include <Pegasus/Provider/CIMIndicationConsumerProvider.h>

#include <Pegasus/ProviderManager2/SimpleResponseHandler.h>
#include <Pegasus/ProviderManager2/Default/Linkage.h>

PEGASUS_NAMESPACE_BEGIN

/**
    The ProviderFacade class wraps a CIMProvider object to ensure it is
    complete and well behaved.  Regardless of the methods supported by a
    CIMProvider object, the ProviderFacade gives it a predictable interface.
 */
class PEGASUS_DEFPM_LINKAGE ProviderFacade :
    public CIMInstanceQueryProvider,
    public CIMAssociationProvider,
    public CIMMethodProvider,
    public CIMIndicationProvider,
    public CIMIndicationConsumerProvider
{
public:
    ProviderFacade(CIMProvider * provider);
    virtual ~ProviderFacade(void);

    // CIMProvider interface
    virtual void initialize(CIMOMHandle & cimom);
    virtual void terminate(void);

    // CIMInstanceProvider interface
    virtual void getInstance(
        const OperationContext & context,
        const CIMObjectPath & instanceReference,
        const Boolean includeQualifiers,
        const Boolean includeClassOrigin,
        const CIMPropertyList & propertyList,
        InstanceResponseHandler & handler);

    virtual void enumerateInstances(
        const OperationContext & context,
        const CIMObjectPath & classReference,
        const Boolean includeQualifiers,
        const Boolean includeClassOrigin,
        const CIMPropertyList & propertyList,
        InstanceResponseHandler & handler);

    virtual void enumerateInstanceNames(
        const OperationContext & context,
        const CIMObjectPath & classReference,
        ObjectPathResponseHandler & handler);

    virtual void modifyInstance(
        const OperationContext & context,
        const CIMObjectPath & instanceReference,
        const CIMInstance & instanceObject,
        const Boolean includeQualifiers,
        const CIMPropertyList & propertyList,
        ResponseHandler & handler);

    virtual void createInstance(
        const OperationContext & context,
        const CIMObjectPath & instanceReference,
        const CIMInstance & instanceObject,
        ObjectPathResponseHandler & handler);

    virtual void deleteInstance(
        const OperationContext & context,
        const CIMObjectPath & instanceReference,
        ResponseHandler & handler);

    virtual void execQuery(
        const OperationContext & context,
        const CIMObjectPath & nameSpaceAndClass,
        const QueryExpression & query,
        InstanceResponseHandler & handler);

    // CIMAssociationProvider interface
    virtual void associators(
        const OperationContext & context,
        const CIMObjectPath & objectName,
        const CIMName & associationClass,
        const CIMName & resultClass,
        const String & role,
        const String & resultRole,
        const Boolean includeQualifiers,
        const Boolean includeClassOrigin,
        const CIMPropertyList & propertyList,
        ObjectResponseHandler & handler);

    virtual void associatorNames(
        const OperationContext & context,
        const CIMObjectPath & objectName,
        const CIMName & associationClass,
        const CIMName & resultClass,
        const String & role,
        const String & resultRole,
        ObjectPathResponseHandler & handler);

    virtual void references(
        const OperationContext & context,
        const CIMObjectPath & objectName,
        const CIMName & resultClass,
        const String & role,
        const Boolean includeQualifiers,
        const Boolean includeClassOrigin,
        const CIMPropertyList & propertyList,
        ObjectResponseHandler & handler);

    virtual void referenceNames(
        const OperationContext & context,
        const CIMObjectPath & objectName,
        const CIMName & resultClass,
        const String & role,
        ObjectPathResponseHandler & handler);

    // Property operation interfaces
    // Note: Property operations are not supported at the provider level.
    // These methods should be removed, and the caller should be changed to
    // use the CIMInstanceProvider interface.
    virtual void getProperty(
        const OperationContext & context,
        const CIMObjectPath & instanceReference,
        const CIMName & propertyName,
        ValueResponseHandler & handler);

    virtual void setProperty(
        const OperationContext & context,
        const CIMObjectPath & instanceReference,
        const CIMName & propertyName,
        const CIMValue & newValue,
        ResponseHandler & handler);

    // CIMMethodProviderFacade
    virtual void invokeMethod(
        const OperationContext & context,
        const CIMObjectPath & objectReference,
        const CIMName & methodName,
        const Array<CIMParamValue> & inParameters,
        MethodResultResponseHandler & handler);

    // CIMIndicationProvider interface
    virtual void enableIndications(
        IndicationResponseHandler & handler);

    virtual void disableIndications(void);

    virtual void createSubscription(
        const OperationContext & context,
        const CIMObjectPath & subscriptionName,
        const Array<CIMObjectPath> & classNames,
        const CIMPropertyList & propertyList,
        const Uint16 repeatNotificationPolicy);

    virtual void modifySubscription(
        const OperationContext & context,
        const CIMObjectPath & subscriptionName,
        const Array<CIMObjectPath> & classNames,
        const CIMPropertyList & propertyList,
        const Uint16 repeatNotificationPolicy);

    virtual void deleteSubscription(
        const OperationContext & context,
        const CIMObjectPath & subscriptionName,
        const Array<CIMObjectPath> & classNames);

    // CIMIndicationConsumerProvider interface
    virtual void consumeIndication(
        const OperationContext & context,
        const String & destinationPath,
        const CIMInstance& indicationInstance);

protected:
    CIMProvider * _provider;
    AtomicInt _current_operations;
//    AtomicInt _current_ind_operations;
    Boolean _indications_enabled;

};

PEGASUS_NAMESPACE_END

#endif


text:
ActiveRecord::Schema.define(:version => 20120414221252) do

  create_table "articles", :force => true do |t|
    t.string   "name"
    t.text     "content"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

end


text:
layout: post
title: "Using Redis via Observable"
comments: true
tags: [scala, async, future, observable]
---

In the previous [blog post]({% post_url 2015-05-18-scala-future-vs-observable-part-1 %}) we saw how observable was used to create an abstraction over Apache Tailer. In this article I am going to use Observable to abstract over some Redis operations.

I chose [lettue](https://github.com/mp911de/lettuce) for this exercise. It has good support for the scan based operations(scan, hscan etc) in Redis and I was interested in exposing these operations via Observable.

Lets first see how to expose the PubSub APIs subscription as an Observable.

{%highlight scala%}
val obs = Observable[(String, String)] { subscriber =>
  val connection: RedisPubSubConnection[String, String] = client.connectPubSub()
  connection.addListener(new RedisPubSubAdapter[String, String]() {
    override def message(chan: String, msg: String): Unit = {
      if (!subscriber.isUnsubscribed)
        subscriber.onNext((chan, msg))
    }
  })
  connection.subscribe("test-channel")
}

obs subscribe { r => println(s"chan: ${r._1}, msg: ${r._2}") }
{%endhighlight%}

Pretty straightforward. The lettuce library provides a nice listener based API to subscribe to a given channel and I just wrapped that in the Observable's factory method. I have exposed the stream from the pubsub system as a tuple stream of channel & message.

Similarly we can expose iterating over all the keys in Redis as an Observable. Note that it is using the non-blocking `scan` API instead of the blocking `keys` redis operation.

{%highlight scala%}
Observable[String] { subscriber =>
  asyncConnection.scan(new KeyStreamingChannel[String]() {
    override def onKey(key: String) {
      if (!subscriber.isUnsubscribed)
        subscriber.onNext(key)
    }
  })
} subscribe { key => println(s"key => $key") }
{%endhighlight%}

Lettuce again provides a decent streaming API (`KeyStreamingChannel`) that I have wrapped in an Observable.

The code for wrapping `HSCAN` in an Observable looks almost similar to the code for `SCAN`

{%highlight scala%}
Observable[(String, String)] { subscriber =>
  asyncConnection.hscan(new KeyValueStreamingChannel[String, String]() {
    override def onKeyValue(key: String, value: String) {
      if (!subscriber.isUnsubscribed)
        subscriber.onNext((key, value))
    }
  }, "my-key")
} subscribe { kv => println(s"key => ${kv._1}, value = ${kv._2}") }
{%endhighlight%}

The full source code for this article can be found in this [gist](https://gist.github.com/parth-patil/8d105d82b745a6f69cb1)


text:
this.userContainer.$.elementsClear();
this.mask.$.elementsClear();
this.userMenu.$.elementsClear();
UI.Body.elementsClear();
this.init = false;


text:
FROM centos:6

RUN yum update -y && yum install rpm-build make tar python-setuptools -y

COPY ./build-rpms.sh /


text:
var myApp = angular.module('behaviorApp',[],null);

myApp.directive("enter",function(){
    return function(scope,element){
        element.bind("mouseenter",function(){
            console.log("I'm inside of you!");
        })
    }
})

myApp.directive("leave",function(){
    return function(scope,element){
        element.bind("mouseleave",function(){
            console.log("I'm leaving on a jet plane");
        })
    }
})