text:
package com.java110.api.listener.advert;

import com.alibaba.fastjson.JSONObject;
import com.java110.api.listener.AbstractServiceApiListener;
import com.java110.core.annotation.Java110Listener;
import com.java110.core.context.DataFlowContext;
import com.java110.intf.common.IAdvertInnerServiceSMO;
import com.java110.intf.community.ICommunityInnerServiceSMO;
import com.java110.intf.community.IFloorInnerServiceSMO;
import com.java110.intf.community.IRoomInnerServiceSMO;
import com.java110.intf.community.IUnitInnerServiceSMO;
import com.java110.dto.FloorDto;
import com.java110.dto.RoomDto;
import com.java110.dto.advert.AdvertDto;
import com.java110.dto.community.CommunityDto;
import com.java110.dto.unit.FloorAndUnitDto;
import com.java110.core.event.service.api.ServiceDataFlowEvent;
import com.java110.utils.constant.ServiceCodeAdvertConstant;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.vo.api.advert.ApiAdvertDataVo;
import com.java110.vo.api.advert.ApiAdvertVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

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

/**
 * 查询小区侦听类
 */
@Java110Listener("listAdvertsListener")
public class ListAdvertsListener extends AbstractServiceApiListener {

    @Autowired
    private IAdvertInnerServiceSMO advertInnerServiceSMOImpl;

    @Autowired
    private ICommunityInnerServiceSMO communityInnerServiceSMOImpl;

    @Autowired
    private IFloorInnerServiceSMO floorInnerServiceSMOImpl;

    @Autowired
    private IUnitInnerServiceSMO unitInnerServiceSMOImpl;

    @Autowired
    private IRoomInnerServiceSMO roomInnerServiceSMOImpl;

    @Override
    public String getServiceCode() {
        return ServiceCodeAdvertConstant.LIST_ADVERTS;
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.GET;
    }

    @Override
    public int getOrder() {
        return DEFAULT_ORDER;
    }

    public IAdvertInnerServiceSMO getAdvertInnerServiceSMOImpl() {
        return advertInnerServiceSMOImpl;
    }

    public void setAdvertInnerServiceSMOImpl(IAdvertInnerServiceSMO advertInnerServiceSMOImpl) {
        this.advertInnerServiceSMOImpl = advertInnerServiceSMOImpl;
    }

    @Override
    protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {
        super.validatePageInfo(reqJson);
    }

    @Override
    protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
        AdvertDto advertDto = BeanConvertUtil.covertBean(reqJson, AdvertDto.class);
        int count = advertInnerServiceSMOImpl.queryAdvertsCount(advertDto);
        List<ApiAdvertDataVo> adverts = null;
        if (count > 0) {
            List<AdvertDto> advertDtos = advertInnerServiceSMOImpl.queryAdverts(advertDto);
            adverts = BeanConvertUtil.covertBeanList(advertDtos, ApiAdvertDataVo.class);
        } else {
            adverts = new ArrayList<>();
        }
        ApiAdvertVo apiAdvertVo = new ApiAdvertVo();
        apiAdvertVo.setTotal(count);
        apiAdvertVo.setRecords((int) Math.ceil((double) count / (double) reqJson.getInteger("row")));
        apiAdvertVo.setAdverts(adverts);
        ResponseEntity<String> responseEntity = new ResponseEntity<String>(JSONObject.toJSONString(apiAdvertVo), HttpStatus.OK);
        context.setResponseEntity(responseEntity);
    }

    private void refreshAdvert(List<AdvertDto> advertDtos) {
        //批量处理 小区
        refreshCommunitys(advertDtos);
        //批量处理楼栋信息
        refreshFloors(advertDtos);
        //批量处理单元信息
        refreshUnits(advertDtos);
        //批量处理 房屋信息
        refreshRooms(advertDtos);
    }

    /**
     * 获取批量小区
     *
     * @param advertDtos 设备信息
     * @return 批量userIds 信息
     */
    private void refreshCommunitys(List<AdvertDto> advertDtos) {
        List<String> communityIds = new ArrayList<String>();
        List<AdvertDto> tmpAdvertDtos = new ArrayList<>();
        for (AdvertDto advertDto : advertDtos) {
            if ("1000".equals(advertDto.getLocationTypeCd())) {
                communityIds.add(advertDto.getLocationObjId());
                tmpAdvertDtos.add(advertDto);
            }
        }
        if (communityIds.size() < 1) {
            return;
        }
        String[] tmpCommunityIds = communityIds.toArray(new String[communityIds.size()]);
        CommunityDto communityDto = new CommunityDto();
        communityDto.setCommunityIds(tmpCommunityIds);
        //根据 userId 查询用户信息
        List<CommunityDto> communityDtos = communityInnerServiceSMOImpl.queryCommunitys(communityDto);
        for (AdvertDto advertDto : tmpAdvertDtos) {
            for (CommunityDto tmpCommunityDto : communityDtos) {
                if (advertDto.getLocationObjId().equals(tmpCommunityDto.getCommunityId())) {
                    advertDto.setLocationObjName(tmpCommunityDto.getName());
                }
            }
        }
    }

    /**
     * 获取批量楼栋
     *
     * @param adverts 设备信息
     * @return 批量userIds 信息
     */
    private void refreshFloors(List<AdvertDto> adverts) {
        List<String> floorIds = new ArrayList<String>();
        List<AdvertDto> tmpAdvertDtos = new ArrayList<>();
        for (AdvertDto advertDto : adverts) {
            if ("4000".equals(advertDto.getLocationTypeCd())) {
                floorIds.add(advertDto.getLocationObjId());
                tmpAdvertDtos.add(advertDto);
            }
        }
        if (floorIds.size() < 1) {
            return;
        }
        for (AdvertDto advertDto : tmpAdvertDtos) {
            FloorDto floorDto = new FloorDto();
            floorDto.setFloorId(advertDto.getLocationObjId());
            floorDto.setCommunityId(advertDto.getCommunityId());
            List<FloorDto> floorDtos = floorInnerServiceSMOImpl.queryFloors(floorDto);
            if (floorDtos == null || floorDtos.size() < 1) {
                return;
            }
            if (advertDto.getLocationObjId().equals(floorDtos.get(0).getFloorId())) {
                advertDto.setLocationObjName(floorDtos.get(0).getFloorNum() + "栋");
            }
        }
    }

    /**
     * 获取批量单元
     *
     * @param adverts 设备信息
     * @return 批量userIds 信息
     */
    private void refreshUnits(List<AdvertDto> adverts) {
        List<String> unitIds = new ArrayList<String>();
        List<AdvertDto> tmpAdvertDtos = new ArrayList<>();
        for (AdvertDto advertDto : adverts) {
            if ("2000".equals(advertDto.getLocationTypeCd())) {
                unitIds.add(advertDto.getLocationObjId());
                tmpAdvertDtos.add(advertDto);
            }
        }
        if (unitIds.size() < 1) {
            return;
        }
        String[] tmpUnitIds = unitIds.toArray(new String[unitIds.size()]);
        FloorAndUnitDto floorAndUnitDto = new FloorAndUnitDto();
        floorAndUnitDto.setUnitIds(tmpUnitIds);
        //根据 userId 查询用户信息
        List<FloorAndUnitDto> unitDtos = unitInnerServiceSMOImpl.getFloorAndUnitInfo(floorAndUnitDto);
        for (AdvertDto advertDto : tmpAdvertDtos) {
            for (FloorAndUnitDto tmpUnitDto : unitDtos) {
                if (advertDto.getLocationObjId().equals(tmpUnitDto.getUnitId())) {
                    advertDto.setLocationObjName(tmpUnitDto.getFloorNum() + "栋" + tmpUnitDto.getUnitNum() + "单元");
                }
            }
        }
    }

    /**
     * 获取批量单元
     *
     * @param adverts 设备信息
     * @return 批量userIds 信息
     */
    private void refreshRooms(List<AdvertDto> adverts) {
        List<String> roomIds = new ArrayList<String>();
        List<AdvertDto> tmpAdvertDtos = new ArrayList<>();
        for (AdvertDto advertDto : adverts) {
            if ("3000".equals(advertDto.getLocationTypeCd())) {
                roomIds.add(advertDto.getLocationObjId());
                tmpAdvertDtos.add(advertDto);
            }
        }
        if (roomIds.size() < 1) {
            return;
        }
        String[] tmpRoomIds = roomIds.toArray(new String[roomIds.size()]);
        RoomDto roomDto = new RoomDto();
        roomDto.setRoomIds(tmpRoomIds);
        roomDto.setCommunityId(adverts.get(0).getCommunityId());
        //根据 userId 查询用户信息
        List<RoomDto> roomDtos = roomInnerServiceSMOImpl.queryRooms(roomDto);
        for (AdvertDto advertDto : tmpAdvertDtos) {
            for (RoomDto tmpRoomDto : roomDtos) {
                if (advertDto.getLocationObjId().equals(tmpRoomDto.getRoomId())) {
                    advertDto.setLocationObjName(tmpRoomDto.getFloorNum() + "栋" + tmpRoomDto.getUnitNum() + "单元" + tmpRoomDto.getRoomNum() + "室");
                }
            }
        }
    }

    public ICommunityInnerServiceSMO getCommunityInnerServiceSMOImpl() {
        return communityInnerServiceSMOImpl;
    }

    public void setCommunityInnerServiceSMOImpl(ICommunityInnerServiceSMO communityInnerServiceSMOImpl) {
        this.communityInnerServiceSMOImpl = communityInnerServiceSMOImpl;
    }

    public IFloorInnerServiceSMO getFloorInnerServiceSMOImpl() {
        return floorInnerServiceSMOImpl;
    }

    public void setFloorInnerServiceSMOImpl(IFloorInnerServiceSMO floorInnerServiceSMOImpl) {
        this.floorInnerServiceSMOImpl = floorInnerServiceSMOImpl;
    }

    public IUnitInnerServiceSMO getUnitInnerServiceSMOImpl() {
        return unitInnerServiceSMOImpl;
    }

    public void setUnitInnerServiceSMOImpl(IUnitInnerServiceSMO unitInnerServiceSMOImpl) {
        this.unitInnerServiceSMOImpl = unitInnerServiceSMOImpl;
    }

    public IRoomInnerServiceSMO getRoomInnerServiceSMOImpl() {
        return roomInnerServiceSMOImpl;
    }

    public void setRoomInnerServiceSMOImpl(IRoomInnerServiceSMO roomInnerServiceSMOImpl) {
        this.roomInnerServiceSMOImpl = roomInnerServiceSMOImpl;
    }
}


text:
<?php
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/repeated-sample-code.php';

/**
 * Tactician is meant to be very customizable, it makes no assumptions about
 * your code.
 *
 * For example, let's say you like to handle command X in one way and
 * command Y in another.
 *
 * We can write a custom middleware for that.
 */

use League\Tactician\CommandBus;
use League\Tactician\Middleware;

// External command
interface ExternalCommand
{
}

// We create some custom middleware that will forward any ExternalCommand to
// a separate CommandBus (or HTTP endpoint or queue).
final class ExternalCommandMiddleware implements Middleware
{
    private $commandBus;

    public function __construct(CommandBus $commandBus)
    {
        $this->commandBus = $commandBus;
    }

    public function execute($command, callable $next)
    {
        if ($command instanceof ExternalCommand) {
            return $this->commandBus->handle($command);
        }
        return $next($command);
    }
}

// and we'll create a custom command handler/middleware
final class ExternalCommandHandler implements Middleware
{
    public function execute($command, callable $next)
    {
        echo sprintf("Dispatched %s!\n", get_class($command));
    }
}

// and we'll create our example command
class MyExternalCommand implements ExternalCommand
{
}

// Now  let's instantiate our ExternalCommandHandler, CommandBus and ExternalCommandMiddleware
$externalCommandHandler = new ExternalCommandHandler();
$externalCommandBus = new CommandBus([$externalCommandHandler]);
$externalMiddleware = new ExternalCommandMiddleware($externalCommandBus);

// Time to create our main CommandBus
$commandBus = new CommandBus([$externalMiddleware, $handlerMiddleware]);

// Controller Code time!
$externalCommand = new MyExternalCommand();

$commandBus->handle($externalCommand);

$command = new RegisterUserCommand();
$command->emailAddress = 'alice@example.com';
$command->password = 'secret';

$commandBus->handle($command);

redpajama_set_name: RedPajamaGithub


text:
module MixpanelRubyBatch
  VERSION = '0.1'
end


text:
module.exports = function(RED) {

    function LogstashInputVarnishlogNode(config) {
        RED.nodes.createNode(this, config);
        var node = this;

        this.on("close", function() {
        });
    }
    RED.nodes.registerType("ls-in-varnishlog", LogstashInputVarnishlogNode);
};


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hannesdorfmann.mosby.mvp">

  <application/>

</manifest>


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

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="android:colorPrimaryDark">@color/dark</item>
        <item name="android:activatedBackgroundIndicator">@drawable/drawer_selector</item>
    </style>

    <style name="SelectionStyle"/>
</resources>


text:
namespace skia {
namespace textlayout {

class TextStyle;
class Paragraph;
class FontCollection : public SkRefCnt {
public:
    FontCollection();

    ~FontCollection() = default;

    size_t getFontManagersCount() const;

    void setAssetFontManager(sk_sp<SkFontMgr> fontManager);
    void setDynamicFontManager(sk_sp<SkFontMgr> fontManager);
    void setTestFontManager(sk_sp<SkFontMgr> fontManager);
    void setDefaultFontManager(sk_sp<SkFontMgr> fontManager);
    void setDefaultFontManager(sk_sp<SkFontMgr> fontManager, const char defaultFamilyName[]);

    sk_sp<SkFontMgr> getFallbackManager() const { return fDefaultFontManager; }

    std::vector<sk_sp<SkTypeface>> findTypefaces(const std::vector<SkString>& familyNames, SkFontStyle fontStyle);

    sk_sp<SkTypeface> defaultFallback(SkUnichar unicode, SkFontStyle fontStyle, const SkString& locale);
    sk_sp<SkTypeface> defaultFallback();

    void disableFontFallback();
    void enableFontFallback();
    bool fontFallbackEnabled() { return fEnableFontFallback; }

    ParagraphCache* getParagraphCache() { return &fParagraphCache; }

private:
    std::vector<sk_sp<SkFontMgr>> getFontManagerOrder() const;

    sk_sp<SkTypeface> matchTypeface(const SkString& familyName, SkFontStyle fontStyle);

    struct FamilyKey {
        FamilyKey(const std::vector<SkString>& familyNames, SkFontStyle style)
                : fFamilyNames(familyNames), fFontStyle(style) {}

        FamilyKey() {}

        std::vector<SkString> fFamilyNames;
        SkFontStyle fFontStyle;

        bool operator==(const FamilyKey& other) const;

        struct Hasher {
            size_t operator()(const FamilyKey& key) const;
        };
    };

    bool fEnableFontFallback;
    SkTHashMap<FamilyKey, std::vector<sk_sp<SkTypeface>>, FamilyKey::Hasher> fTypefaces;
    sk_sp<SkFontMgr> fDefaultFontManager;
    sk_sp<SkFontMgr> fAssetFontManager;
    sk_sp<SkFontMgr> fDynamicFontManager;
    sk_sp<SkFontMgr> fTestFontManager;

    SkString fDefaultFamilyName;
    ParagraphCache fParagraphCache;
};
}  // namespace textlayout
}  // namespace skia

#endif  // FontCollection_DEFINED


text:
#ifndef NODE_H
#define NODE_H
/**
 * Definições de função-membro que aparecem em Nodes.cpp
 */
#include <iostream>
#include <deque>
#include <iterator>
#include <algorithm> //reverse vector
#include <limits> //limites numéricos
#include <stdexcept> // for std::runtime_error
#include <vector>
#include <random>
#include <string>
#include <fstream>//manipulação de arquivos
#include <cmath>
#include <iostream>
#include <chrono>

using namespace std;

class Node
{
public:

    Node();
    ~Node();

    /**
     * Setters
     */
    void setEdgeNode(int);						//faz uma ligação
    void setDegree();							//aumenta o grau do nó
    void setWeight(int, double);				//atualiza peso de uma ligação
    void setDistanceNode(double);				//atribui distância entre dois nós
    void setDegreeCentrality(int);				//atribui o valor da centralidade de grau
    void setBetweenCentrality(double);			//atribui o valor da centralidade de intermediação
    void setClosenessCentrality(double);		//atribui o valor da centralidade de proximidade
    void setEfficientCentrality(double);		//atribui o valor da centralidade de eficiência
    void setRelativeDegreeCentrality(double);	//atribui o valor da centralidade relativa de grau
    void setEuclideanDistance(double);

    /**
     * Getters
     */
    int getDegree(); 					//retorna o grau do nó passado como parâmetro do método
    bool getEdgeNode(int); 				//verifica a existência de uma ligação entre dois vértices passados como parâmetros
    int getNumberOfPaths();				//número de caminhos mínimos
    int getNumberOfNodes();				//retorna o número de caminhos mínimos
    int getAdjacentNode(int);			//retorna nó adjacente na posição passada como parâmetro
    double getWeightEdge(int);			//retorna o peso da ligação
    void incrementPaths(int);			//incrementa o número de caminhos minimos
    int getDegreeCentrality();		    //centralidade do grau
    double getBetweenCentrality();		//centralidade de intermediação
    double getClosenessCentrality();	//centralidade de proximidade
    double getEfficientCentrality();	//centralidade de eficiência
    vector<int> getAdjacentsNodes();	//retorna vetor de nós adjacentes
    int getNumberOfNodesFromPath(int);	//número de nodos em um caminho minimo
    vector<double>  getEuclideanDistance();//retorna um vetor com as distâncias euclidianas de cada ligação

    void addNodePath(int);					//adiciona nodo ao caminho
    void removeNode(int);					//remove nodo da lista de adjacências
    int returnNode(int,int);				//retorna nodo das posições indicadas localizada na matriz de caminhos mínimos
    vector< vector<int> > returnPaths();	//retorna caminhos mínimos
    void printAdjacents();

private:

    int degree; 					     //número de links da topologia
    vector<int> adjacents;  		     //vetor de adjacências de um nó
    vector<double> weight;			     //vetor de peso de ligações entre nós adjacentes
    vector<double> distanceEuclidean;   //armazena a distância euclidiana de um par de nós adjacentes

    /**
     * Variáveis utilizadas para medidas de centralidade
     */
    int index;						//nodo origem
    int numberOfPaths;				//número de caminhos mínimos
    int degreeCentrality;			//centralidade do grau
    double relativeDegreeCentrality;//centralidade relativa de grau
    double betweenCentrality;		//centralidade de intermediação do nó
    double closenessCentrality;		//centralidade de proximidade
    double efficientCentrality;		//centralidade de eficiência
    vector< vector<int> > paths;	//matriz contendo todos caminhos minimos
};

#endif


text:
# vcharts

Reusable [Vega](http://vega.github.io/vega/) charts.

## Getting Started

### Installation with bower

```
bower install vcharts
```

Setup a scaffold `index.html` with the following contents:

```html
<html>
<head>
  <meta charset="UTF-8">
  <script src="bower_components/d3/d3.min.js"></script>
  <script src="bower_components/vega/vega.min.js"></script>
  <script src="bower_components/vcharts/vcharts.min.js"></script>
</head>
<body>
  <div id="vis"></div>
<script>
vcharts.chart('xy', {
  el: '#vis',
  series: [
    {
      name: 'series1',
      values: [
        {x: 0, y: 0},
        {x: 1, y: 1},
        {x: 2, y: 2},
        {x: 3, y: 3}
      ],
    }
  ]
});
</script>
</body>
```

### Installation with npm

```
npm install vcharts vega d3
```

Setup a scaffold `index.html` with the following contents:

```html
<html>
<head>
  <meta charset="UTF-8">
  <script src="node_modules/d3/d3.min.js"></script>
  <script src="node_modules/vega/vega.min.js"></script>
  <script src="node_modules/vcharts/vcharts.min.js"></script>
</head>
<body>
  <div id="vis"></div>
<script>
vcharts.chart('xy', {
  el: '#vis',
  series: [
    {
      name: 'series1',
      values: [
        {x: 0, y: 0},
        {x: 1, y: 1},
        {x: 2, y: 2},
        {x: 3, y: 3}
      ],
    }
  ]
});
</script>
</body>
```

### View your visualization

Start your favorite local web server:

```
python -m SimpleHTTPServer 8080 .
```

Visit [http://localhost:8080/index.html](http://localhost:8080/index.html).

## API

### vcharts.chart()

Initialize a chart with the call

```js
var chart = vcharts.chart(chartType, options);
```

where *chartType* is one of the supported chart types.

The *options* argument is an object specifying the chart's options.
The following options are available to all charts:

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| el        | DOM element or selector string | The container for the visualization. |
| renderer  | String | Whether to render in "svg" or "canvas" mode (default "canvas"). |
| width     | Number | Width of the chart in pixels. |
| height    | Number | Height of the chart in pixels. |

If *width* and/or *height* are not specified, they are computed based on
the width and height of the enclosing element *el*.

### chart.update()

Note that the *width* and *height* options are not
dynamically bound if left unset,
so if the width or height of *el* changes, or has just
been set programmatically, you may need to call `update` either in a
`setTimeout` or `window.resize` callback. The following
will set the *width* and *height* correctly after a DOM update:

```js
var div = $('#mydiv').css('width', '100px').css('height', '400px');

// Width and height will not be picked up yet since the DOM is not updated.
var chart = vcharts.chart(chartType, { el: div.get(0), /* more options */ });

// Refresh width and height here.
setTimeout(function () { chart.update(); }, 1);
```

The following will resize the chart when the window resizes:

```js
var chart = vcharts.chart(chartType, { el: '#mydiv', /* more options */ });

// Update size on window resize.
window.onresize = function () {
    chart.update();
};
```

### vcharts.chart('vega', options)

Generic Vega renderer. The following additional option is supported:

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| spec      | Object | The Vega spec to render. |

### vcharts.chart('xy', options)

Plots (x,y) coordinate pairs as points and/or lines. The following
additional options are supported:

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| series    | Array of [Series](#series) | The data series to render. |
| xAxis     | [Axis](#axis) | An object describing the *x* axis. |
| yAxis     | [Axis](#axis) | An object describing the *y* axis. |
| tooltip   | String | Mustache-style string template where `d` is the hovered data element, e.g. `'{{d.x}} -- {{d.y}}'`. |

### Series

A series describes the data and visual mappings for a list of x,y coordinates.
Series objects have the following options:

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| name      | String | The name of the series to show in the legend. |
| values    | Array  | The array of items in the series. |
| x         | String | X position field. |
| y         | String | Y position field. |
| color     | String | Color as any CSS-compatible color string representation (e.g. `'blue'`, `'#ffffff'`). |
| line      | Boolean | Connect the series with a line (default *true*). |
| point     | Boolean | Render points (default *false*). |
| pointSize | Number | The size of points in square pixels. |
| lineWidth | Number | The width of the line in pixels. |

### Axis

An axis describes how to scale and display an axis. Axis objects have the
following options:

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| title     | String | The axis title. |
| type      | String | The mode for axis scale, either `'linear'` (default) or `'time'`. |
| domain    | Array  | Two-element domain for the axis range of the form [*min*, *max*]. Defaults to the range of the data. |
| grid      | Boolean | Show gridlines (default *false*). |
| pan       | Boolean | Allow panning this axis with mouse drags (default *true*). |
| zoom      | Boolean | Allow zooming this axis with mouse wheel or swipe (default *true*). |
| ticks     | Array   | Specific values for tick marks on the axis. |

### vcharts.chart('bullet', options)

Bullet graphs based on the [description by Perceptual Edge](http://www.perceptualedge.com/articles/misc/Bullet_Graph_Design_Spec.pdf).
The following additional options are supported:

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| value     | Number | The value to display as a solid bar. |
| title     | String | Title to display to the left. |
| subtitle  | String | Subtitle to display below the title. |
| markers   | Array  | Comparative markers to display with the form {value: *Number*}, displayed as a vertical line. |
| ranges    | Array of [Range](#range) | Background ranges to display under the chart. |
| axisFontSize | Number | Font size for axis labels. |
| labelFontSize | Number | Font size for value label. |
| titleFontSize | Number | Font size for title. |
| subtitleFontSize | Number | Font size for subtitle. |

#### Example

```js
vcharts.chart('bullet', {
  el: '#vis',
  value: 0.8,
  title: 'Error',
  subtitle: '% deviation from ground truth',
  markers: [{value: 0.05}],
  ranges: [
    {min: 0, max: 0.1, background: '#eeeeee'},
    {min: 0.1, max: 0.75, background: '#aaaaaa'},
    {min: 0.75, max: 1, background: '#888888'}
  ]
});
```

### Range

A range represents a visual range of an axis with background and foreground colors. Options available are:

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| min       | Number | The minimum value of the range. |
| max       | Number | The maximum value of the range. |
| background | String | The background color of the range. |
| foreground | String | The color of values and markers that fall in this range (default: `'black'`). |

### vcharts.chart('bar', options)

Plots a bar chart. The following additional options are supported:

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| values    | Array  | The array of items in the series. |
| x         | String | Field used to set the bar x position. |
| y         | String | Field used to set bar height. |
| fill      | String | Fill color for the bars. |
| hover     | String | Fill color when bar is hovered. |
| xAxis     | [Axis](#axis) | An object describing the *x* axis. |
| yAxis     | [Axis](#axis) | An object describing the *y* axis. |
| tooltip   | String | Mustache-style string template where `d` is the hovered data element, e.g. `'{{d.x}} -- {{d.y}}'`. |

### vcharts.chart('histogram', options)

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| values    | Array  | The array of items in the series. |
| bin       | String | Field to use for bin values. |
| discrete  | Boolean | If true, treats values as discrete and makes bins for each unique value. If false, treats values as continuous and makes bins that span the range of the data. |
| maxBins   | Number | The maximum number of bins to use. Unused if discrete is *true*. |
| fill      | String | Fill color for the bars. |
| hover     | String | Fill color when bar is hovered. |
| xAxis     | [Axis](#axis) | An object describing the *x* axis. |
| yAxis     | [Axis](#axis) | An object describing the *y* axis. |
| tooltip   | String | Mustache-style string template where *d* is the hovered bin with the fields *bin* and *count*, e.g. `'Count: {{d.count}}'`. |

### vcharts.chart('xymatrix', options)

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| values    | Array  | The array of items in the series. |
| fields    | Array  | The list of fields to use in the matrix of scatterplots. |
| color.field | String | If set, colors by this field. |
| color.type  | String | If *color.field* is set, specifies the type of scale (e.g. `"ordinal"` or `"linear"`). |
| color.value | String | If set, colors by this constant color. |

### vcharts.chart('box', options)

Statistical box plot based on work by [Jeffrey Heer and Randy Zwitch](https://groups.google.com/forum/#!topic/vega-js/Y1vLxaw9nuA).

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| values    | Array  | The array of items in the series. |
| fields    | Array  | The fields containing the values to summarize in the box plot. |
| group     | String | The field to group by for multiple boxes per field (optional). |
| fill      | String | The fill color for the box. |
| orient    | String | The orientation of the boxes, either `horizontal` or `vertical`. |
| boxSize   | Number | A number from 0 to 1 to specify box size, where a value of 1 makes box widths touch each other, and lower numbers produce spacing between boxes. |
| capSize   | Number | A number from 0 to 1 to specify end cap size, where a value of 1 makes caps widths touch each other, and lower numbers produce spacing between caps. |

### vcharts.chart('gantt', options)

Gantt chart.

| Option    | Type   | Description  |
| :-------- | :----- | :----------- |
| values    | Array  | The array of items in the Gantt chart. Each object should have the fields *label* (the name of the item), *level* (either 1 for top-level or 2 for secondary), *enter* (the start value), and *leave* (the end value). Each item will be represented by a horizontal bar from *enter* to *leave*. |
| xAxis     | [Axis](#axis) | Attributes for the x (time) axis. |

## Development Build

Clone the repository:

```
git clone https://github.com/XDATA-Year-3/vcharts.git
cd vcharts
```

Build the library:

```
npm run build
```

Run the tests:

```
npm run test
```

## Release Instructions

To release a new verison *x.y.z*, first release to npm:

```bash
export VERSION=x.y.z
npm run test && npm run lint && npm run build # Should run without errors
git checkout -b version-$VERSION
```

Edit `package.json` to set the version to *x.y.z*, then:

```bash
git commit -am "Version bump to $VERSION"
git push -u origin version-$VERSION
```

Create PR on GitHub and merge to master, then:

```bash
git checkout master
git pull
npm run test && npm run lint && npm run build # This should again run without errors.
npm publish
```

Next, release to Bower, which amounts to creating a tag with the appropriate name
that contains the built library, which is normally gitignored.

```bash
git checkout -b bower-$VERSION
git add -f vcharts*
git commit -am "Bower $VERSION release"
git tag $VERSION
git push origin $VERSION
```

Go to GitHub releases page and edit the tag to make it a real GitHub release.

To make a new version of the website:

```bash
git checkout master
npm run build
git branch -D gh-pages
git checkout -b gh-pages
git add -f vcharts*
git add -f node_modules/d3/d3.*
git add -f node_modules/vega/vega.*
git commit -m "Updating website for $VERSION"
git push -f -u origin gh-pages
git checkout master
rm -rf node_modules/
npm install
npm run build
```


text:
var imdb = require('imdb-api');

var movie;
imdb.getReq({ name: 'Pulp Fiction' }, function(error, results) {
    if (error) {
        console.log(error);
    } else if(results) {
        console.log(results);
    }
})


text:
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class Model_EstadoEtapa_FE extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    /*añadir funcion*/
    public function GetEstadoEtapa_FE($flat, $id_estado, $txt_IdEtapa_Estudio_FE)
    {
        //  $EstadoCicloInversion = $this->db->query("execute get");
        $EstadoEtapa = $this->db->query("execute sp_Gestionar_Estado_Etapa'"
            . $flat . "','"
            . $id_estado . "', '"
            . $txt_IdEtapa_Estudio_FE . "' ");
        if ($EstadoEtapa->num_rows() > 0) {
            return $EstadoEtapa->result();
        } else {
            return false;
        }
    }
    public function AddEstadoEtapa_FE($flat, $Cbx_EstadoFE, $txt_IdEtapa_Estudio_FE)
    {
        //  $EstadoCicloInversion = $this->db->query("execute get");
        $EstadoEtapa = $this->db->query("execute sp_Gestionar_Estado_Etapa'"
            . $flat . "','"
            . $Cbx_EstadoFE . "', '"
            . $txt_IdEtapa_Estudio_FE . "' ");
        if ($EstadoEtapa->num_rows() > 0) {
            return $EstadoEtapa->result();
        } else {
            return false;
        }
    }

}


text:
<?php

namespace Tests;

use Google\Cloud\Vision\Annotation;
use MarcoTisi\Sight\Sight;
use PHPUnit\Framework\TestCase as PHPUnitTestCase;

class TestCase extends PHPUnitTestCase
{
    /**
     * Returns an absolute path for a test resource.
     *
     * @param string $resource
     * @return string
     */
    protected function getResourcePath($resource)
    {
        return __DIR__.'/data/'.$resource;
    }
}

class SightTest extends Sight
{
    public function __construct($image, $response = null)
    {
        parent::__construct($image);

        $this->setResponse($response);
    }

    public static function create($image, $response = null)
    {
        $instance = parent::create($image);
        $instance->setResponse($response);

        return $instance;
    }

    public function setResponse($response)
    {
        if ($response) {
            $response = file_get_contents(__DIR__.'/data/responses/'.$response);
            $this->response = new Annotation(json_decode($response, true));
        }
    }
}


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

    <item android:state_pressed="true">
        <ripple android:color="@color/divider"/>
    </item>

    <item android:state_activated="true"
        android:drawable="@drawable/background_card_selected" />

    <item android:drawable="@drawable/background_card" />
</selector>


text:
module Course::VirtualClassroom::StubbedBraincertApiService
  def initialize(virtual_classroom, _settings)
    @virtual_classroom = virtual_classroom
  end

  def fetch_recorded_videos
    [{ name: 'Video 1', id: 1 },
     { name: 'Video 2', id: 2 }]
  end

  def fetch_recorded_video_link(record_id)
    ["https://api.example.com/video/#{record_id}", nil]
  end

  private

  def create_classroom
    @virtual_classroom.update! classroom_id: 1
  end

  def generate_classroom_link(_user, is_instructor)
    link = "https://virtual_classroom_link_#{@virtual_classroom.id}.com"
    @virtual_classroom.update! instructor_classroom_link: link if is_instructor
    [link, nil]
  end
end

Course::VirtualClassroom::BraincertApiService.class_eval do
  prepend Course::VirtualClassroom::StubbedBraincertApiService
end


text:
package org.caffinitas.ohc.linked;

import org.caffinitas.ohc.HashAlgorithm;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import java.nio.ByteBuffer;

import static org.testng.Assert.*;

public class HashEntriesTest
{
    @AfterMethod(alwaysRun = true)
    public void deinit()
    {
        Uns.clearUnsDebugForTest();
    }

    static final long MIN_ALLOC_LEN = 128;

    @Test
    public void testInit() throws Exception
    {
        long adr = Uns.allocate(MIN_ALLOC_LEN);
        boolean ok = false;
        try
        {
            HashEntries.init(0x98765432abcddeafL, 5, 10, adr, 0, 0L);

            assertEquals(Uns.getLong(adr, Util.ENTRY_OFF_HASH), 0x98765432abcddeafL);
            assertEquals(Uns.getInt(adr, Util.ENTRY_OFF_KEY_LENGTH), 5L);
            assertEquals(Uns.getInt(adr, Util.ENTRY_OFF_VALUE_LENGTH), 10L);

            assertEquals(HashEntries.getHash(adr), 0x98765432abcddeafL);
            assertEquals(HashEntries.getKeyLen(adr), 5L);
            assertEquals(HashEntries.getValueLen(adr), 10L);
            assertTrue(HashEntries.dereference(adr));
            ok = true;
        }
        finally
        {
            if (!ok)
                Uns.free(adr);
        }
    }

    @Test
    public void testCompareKey() throws Exception
    {
        long adr = Uns.allocate(MIN_ALLOC_LEN);
        KeyBuffer key = new KeyBuffer(11);
        try
        {
            HashEntries.init(0L, 11, 0, adr, Util.SENTINEL_NOT_PRESENT, 0L);

            ByteBuffer keyBuffer = key.byteBuffer();
            keyBuffer.putInt(0x98765432);
            keyBuffer.putInt(0xabcdabba);
            keyBuffer.put((byte)(0x44 & 0xff));
            keyBuffer.put((byte)(0x55 & 0xff));
            keyBuffer.put((byte)(0x88 & 0xff));
            key.finish(Hasher.create(HashAlgorithm.MURMUR3));

            Uns.setMemory(adr, Util.ENTRY_OFF_DATA, 11, (byte) 0);

            assertFalse(key.sameKey(adr));

            Uns.copyMemory(key.buffer, 0, adr, Util.ENTRY_OFF_DATA, 11);
            HashEntries.init(key.hash(), 11, 0, adr, Util.SENTINEL_NOT_PRESENT, 0L);

            assertTrue(key.sameKey(adr));
        }
        finally
        {
            Uns.free(adr);
        }
    }

    @Test
    public void testGetSetLRUNext() throws Exception
    {
        long adr = Uns.allocate(MIN_ALLOC_LEN);
        try
        {
            Uns.setMemory(adr, 0, MIN_ALLOC_LEN, (byte) 0);
            HashEntries.init(0x98765432abcddeafL, 5, 10, adr, 0, 0L);

            Uns.putLong(adr, Util.ENTRY_OFF_LRU_NEXT, 0x98765432abdffeedL);
            assertEquals(HashEntries.getLRUNext(adr), 0x98765432abdffeedL);

            HashEntries.setLRUNext(adr, 0xfafefcfb23242526L);
            assertEquals(Uns.getLong(adr, Util.ENTRY_OFF_LRU_NEXT), 0xfafefcfb23242526L);
        }
        finally
        {
            Uns.free(adr);
        }
    }

    @Test
    public void testGetSetLRUPrev() throws Exception
    {
        long adr = Uns.allocate(MIN_ALLOC_LEN);
        try
        {
            Uns.setMemory(adr, 0, MIN_ALLOC_LEN, (byte) 0);
            HashEntries.init(0x98765432abcddeafL, 5, 10, adr, 0, 0L);

            Uns.putLong(adr, Util.ENTRY_OFF_LRU_PREV, 0x98765432abdffeedL);
            assertEquals(HashEntries.getLRUPrev(adr), 0x98765432abdffeedL);

            HashEntries.setLRUPrev(adr, 0xfafefcfb23242526L);
            assertEquals(Uns.getLong(adr, Util.ENTRY_OFF_LRU_PREV), 0xfafefcfb23242526L);
        }
        finally
        {
            Uns.free(adr);
        }
    }

    @Test
    public void testGetHash() throws Exception
    {
        long adr = Uns.allocate(MIN_ALLOC_LEN);
        try
        {
            Uns.setMemory(adr, 0, MIN_ALLOC_LEN, (byte) 0);
            HashEntries.init(0x98765432abcddeafL, 5, 10, adr, 0, 0L);

            assertEquals(HashEntries.getHash(adr), 0x98765432abcddeafL);

            assertEquals(Uns.getLong(adr, Util.ENTRY_OFF_HASH), 0x98765432abcddeafL);
        }
        finally
        {
            Uns.free(adr);
        }
    }

    @Test
    public void testGetSetNext() throws Exception
    {
        long adr = Uns.allocate(MIN_ALLOC_LEN);
        try
        {
            Uns.setMemory(adr, 0, MIN_ALLOC_LEN, (byte) 0);
            HashEntries.init(0x98765432abcddeafL, 5, 10, adr, 0, 0L);

            Uns.putLong(adr, Util.ENTRY_OFF_NEXT, 0x98765432abdffeedL);
            assertEquals(HashEntries.getNext(adr), 0x98765432abdffeedL);

            HashEntries.setNext(adr, 0xfafefcfb23242526L);
            assertEquals(Uns.getLong(adr, Util.ENTRY_OFF_NEXT), 0xfafefcfb23242526L);
        }
        finally
        {
            Uns.free(adr);
        }
    }

    @Test
    public void testGetAllocLen() throws Exception
    {
        long adr = Uns.allocate(MIN_ALLOC_LEN);
        try
        {

            HashEntries.init(0x98765432abcddeafL, 0, 10, adr, 0, 0L);
            assertEquals(HashEntries.getAllocLen(adr), Util.ENTRY_OFF_DATA + 10L);

            HashEntries.init(0x98765432abcddeafL, 5, 10, adr, 0, 0L);
            assertEquals(HashEntries.getAllocLen(adr), Util.ENTRY_OFF_DATA + 8L + 10L);

            HashEntries.init(0x98765432abcddeafL, 8, 10, adr, 0, 0L);
            assertEquals(HashEntries.getAllocLen(adr), Util.ENTRY_OFF_DATA + 8L + 10L);

            HashEntries.init(0x98765432abcddeafL, 9, 10, adr, 0, 0L);
            assertEquals(HashEntries.getAllocLen(adr), Util.ENTRY_OFF_DATA + 16L + 10L);

            HashEntries.init(0x98765432abcddeafL, 15, 10, adr, 0, 0L);
            assertEquals(HashEntries.getAllocLen(adr), Util.ENTRY_OFF_DATA + 16L + 10L);

            HashEntries.init(0x98765432abcddeafL, 16, 10, adr, 0, 0L);
            assertEquals(HashEntries.getAllocLen(adr), Util.ENTRY_OFF_DATA + 16L + 10L);
        }
        finally
        {
            Uns.free(adr);
        }
    }

    @Test
    public void testReferenceDereference() throws Exception
    {
        long adr = Uns.allocate(MIN_ALLOC_LEN);
        boolean ok = false;
        try
        {
            HashEntries.init(0x98765432abcddeafL, 0, 10, adr, 0, 0L);

            HashEntries.reference(adr); // to 2
            HashEntries.reference(adr); // to 3
            HashEntries.reference(adr); // to 4
            assertEquals(Uns.getInt(adr, Util.ENTRY_OFF_REFCOUNT), 4);
            assertFalse(HashEntries.dereference(adr)); // to 3
            assertFalse(HashEntries.dereference(adr)); // to 2
            assertFalse(HashEntries.dereference(adr)); // to 1
            assertTrue(HashEntries.dereference(adr)); // to 0
            ok = true;
        }
        finally
        {
            if (!ok)
                Uns.free(adr);
        }
    }

    @Test
    public void testDereferenceFail() throws Exception
    {
        long adr = Uns.allocate(MIN_ALLOC_LEN);
        boolean ok = false;
        try
        {
            HashEntries.init(0x98765432abcddeafL, 0, 10, adr, Util.SENTINEL_NOT_PRESENT, 0L);

            assertTrue(HashEntries.dereference(adr)); // to 0
            ok = true;

            // must NOT dereference another time - memory has been free()'d !!!!
            //HashEntries.dereference(adr);
        }
        finally
        {
            if (!ok)
                Uns.free(adr);
        }
    }
}


text:
/*
 * @(#)URLTool.java 5.1
 *
 */

package CH.ifa.draw.figures;

import java.awt.*;
import java.awt.event.*;
import java.net.URLEncoder;
import CH.ifa.draw.framework.*;
import CH.ifa.draw.standard.*;
import CH.ifa.draw.util.FloatingTextField;

/**
 * Tool to create new or edit existing text figures.
 * The editing behavior is implemented by overlaying the
 * Figure providing the text with a FloatingTextField.<p>
 * A tool interaction is done once a Figure that is not
 * a TextHolder is clicked.
 *
 * @see TextHolder
 * @see FloatingTextField
 */
public class URLTool extends CreationTool {

    private FloatingTextField   fTextField;
    private Figure  fTypingTarget;
    private static Font dialogFont = Font.decode("dialog-PLAIN-12");

    public URLTool(DrawingView view, Figure prototype) {
        super(view, prototype);
    }

    /**
     * If the pressed figure is a TextHolder it can be edited otherwise
     * a new text figure is created.
     */
    public void mouseDown(MouseEvent e, int x, int y)
    {
	Figure pressedFigure;

	pressedFigure = drawing().findFigureInside(x, y);
	if (pressedFigure != null) {
	    beginEdit(pressedFigure);
	} else if (fTypingTarget != null) {
	    editor().toolDone();
	    endEdit();
	}
    }

    public void mouseDrag(MouseEvent e, int x, int y) {
    }

    public void mouseUp(MouseEvent e, int x, int y) {
    }

    /**
     * Terminates the editing of a text figure.
     */
    public void deactivate() {
        super.deactivate();
        endEdit();
    }

    /**
     * Sets the text cursor.
     */
    public void activate() {
        super.activate();
        view().clearSelection();
        // JDK1.1 TEXT_CURSOR has an incorrect hot spot
        //view.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
    }

    protected void beginEdit(Figure figure) {
        if (fTextField == null)
            fTextField = new FloatingTextField();

	if (figure != fTypingTarget && fTypingTarget != null)
	    endEdit();

        fTextField.createOverlay((Container)view(), dialogFont);
	fTextField.setBounds(fieldBounds(figure),
			     (String)figure.getAttribute("Sensitive"));
	fTypingTarget = figure;
    }

    protected void endEdit() {
	if (fTypingTarget != null) {
	    String s = URLEncoder.encode(fTextField.getText());
	    fTypingTarget.setAttribute("Sensitive", s);
	    fTypingTarget = null;
	    fTextField.endOverlay();
	    view().checkDamage();
	}
    }

    private Rectangle fieldBounds(Figure figure) {
    	Rectangle box = figure.displayBox();
        Dimension d = fTextField.getPreferredSize(1, 20);
        return new Rectangle(box.x, box.y, d.width, d.height);
    }
}


text:
{% extends base_template %}
{% block title %}Form Data Groups{% endblock %}
{% block content %}

All Form Groups

new group

{% include "xformmanager/partials/form_data_group_list_table.html" %}
{% endblock %}


text:
{% assign content_item = false %}
{% if post %}
{% assign content_item = post %}
{% else %}
{% assign content_item = page %}
{% endif %}

{% if content_item.newsletter.highlights %}
{% if content_item.newsletter.highlights.size == 1 %}

    {{ content_item.newsletter.highlights }}

{% else %}

    Highlights from this week:

{% for highlight in content_item.newsletter.highlights %}

{{ highlight }}

{% endfor %}

{% endif %}
{% endif %}


text:
namespace MarginTrading.Backend.Services.AssetPairs
{
    public interface IAssetPairDayOffService
    {
        /// <summary>
        /// Checks if now is day off for asset pair
        /// </summary>
        bool IsDayOff(string assetPairId);

        /// <summary>
        /// Checks if now creating new and executing existing pending orders with asset pair is disabled
        /// </summary>
        bool ArePendingOrdersDisabled(string assetPairId);
    }
}


text:
import java.util.*;

// https://www.hackerrank.com/challenges/java-stack/problem
class Solution2 {
    public static boolean isOpeningParanthesis(char paranthesis) {
        if (paranthesis == '(' || paranthesis == '[' || paranthesis == '{') {
            return true;
        }

        return false;
    }

    public static char complementaryParanthesis(char paranthesis) {
        switch (paranthesis) {
            case ')':
                return '(';
            case ']':
                return '[';
            case '}':
                return '{';
            default:
                return 0;
        }
    }

    public static boolean queryIsBalanced(String query) {
        Stack<Character> stack = new Stack<>();

        for (char ch : query.toCharArray()) {
            if (isOpeningParanthesis(ch)) {
                stack.push(ch);
            } else if (!stack.isEmpty() && stack.peek() == complementaryParanthesis(ch)) {
                stack.pop();
            } else {
                return false;
            }
        }

        return stack.isEmpty();
    }

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);

		while (scan.hasNext()) {
			String query = scan.next();
            if (queryIsBalanced(query)) {
                System.out.println("true");
            } else {
                System.out.println("false");
            }
		}

        scan.close();
	}
}


text:
<?php

/**
 * Represents an echo construct.
 *
 * @package Template
 * @version 1.4.2
 * @access private
 */
class ezcTemplateEchoAstNode extends ezcTemplateStatementAstNode
{
    /**
     * List of code elements which are going to be evaluated and output.
     * @var array(ezcTemplateAstNode)
     */
    public $outputList;

    /**
     * Constructs a new ezcTemplateEchoAstNode
     *
     * @param array(ezcTemplateAstNode) $outputList
     */
    public function __construct( Array $outputList = null )
    {
        parent::__construct();
        $this->outputList = array();

        if ( $outputList !== null )
        {
            foreach ( $outputList as $output )
            {
                $this->appendOutput( $output );
            }
        }
    }

    /**
     * Append a new output element to the current list.
     *
     * @param ezcTemplateAstNode $output
     * @return void
     */
    public function appendOutput( ezcTemplateAstNode $output )
    {
        $this->outputList[] = $output;
    }

    /**
     * Returns the current list of output elements.
     * @return array(ezcTemplateAstNode)
     */
    public function getOutputList()
    {
        return $this->outputList;
    }

    /**
     * Validates the output parameters against their constraints.
     *
     * @throws ezcTemplateInternalException if the constraints are not met.
     * @return void
     */
    public function validate()
    {
        if ( count( $this->outputList ) == 0 )
        {
            throw new ezcTemplateInternalException( "Too few output parameters for class <" . get_class( $this ) . ">, needs at least 1 but got 0." );
        }
    }
}
?>


text:
package de.jcup.egradle.eclipse.ui;

import org.eclipse.core.runtime.Assert;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.layout.PixelConverter;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.ViewForm;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Layout;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.dialogs.PreferencesUtil;
import org.eclipse.ui.forms.widgets.ExpandableComposite;

import de.jcup.egradle.eclipse.util.EclipseUtil;

/**
 * Factory class to create some SWT resources.
 */
public class SWTFactory {

    /**
     * Returns a width hint for a button control.
     *
     * @param button
     * @return width
     */
    public static int getButtonWidthHint(Button button) {
        /* button.setFont(JFaceResources.getDialogFont()); */
        PixelConverter converter = new PixelConverter(button);
        int widthHint = converter.convertHorizontalDLUsToPixels(IDialogConstants.BUTTON_WIDTH);
        return Math.max(widthHint, button.computeSize(SWT.DEFAULT, SWT.DEFAULT, true).x);
    }

    /**
     * Sets width and height hint for the button control. Note: This is a NOP
     * if the button's layout data is not an instance of GridData.
     *
     * @param button button for which to set the dimension hint
     */
    public static void setButtonDimensionHint(Button button) {
        Assert.isNotNull(button);
        Object gd = button.getLayoutData();
        if (gd instanceof GridData) {
            ((GridData) gd).widthHint = getButtonWidthHint(button);
            ((GridData) gd).horizontalAlignment = GridData.FILL;
        }
    }

    /**
     * Creates a check box button using the parents' font
     *
     * @param parent  the parent to add the button to
     * @param label   the label for the button
     * @param image   the image for the button
     * @param checked the initial checked state of the button
     * @param hspan   the horizontal span to take up in the parent composite
     * @return a new checked button set to the initial checked state
     */
    public static Button createCheckButton(Composite parent, String label, Image image, boolean checked, int hspan) {
        Button button = new Button(parent, SWT.CHECK);
        button.setFont(parent.getFont());
        button.setSelection(checked);
        if (image != null) {
            button.setImage(image);
        }
        if (label != null) {
            button.setText(label);
        }
        GridData gd = new GridData();
        gd.horizontalSpan = hspan;
        button.setLayoutData(gd);
        setButtonDimensionHint(button);
        return button;
    }

    /**
     * Creates and returns a new push button with the given label and/or image.
     *
     * @param parent parent control
     * @param label  button label or null
     * @param image  image of null
     *
     * @return a new push button
     */
    public static Button createPushButton(Composite parent, String label, Image image) {
        Button button = new Button(parent, SWT.PUSH);
        button.setFont(parent.getFont());
        if (image != null) {
            button.setImage(image);
        }
        if (label != null) {
            button.setText(label);
        }
        GridData gd = new GridData();
        button.setLayoutData(gd);
        setButtonDimensionHint(button);
        return button;
    }

    /**
     * Creates and returns a new push button with the given label and/or image.
     *
     * @param parent parent control
     * @param label  button label or null
     * @param image  image of null
     * @param fill   the alignment for the new button
     *
     * @return a new push button
     */
    public static Button createPushButton(Composite parent, String label, Image image, int fill) {
        Button button = new Button(parent, SWT.PUSH);
        button.setFont(parent.getFont());
        if (image != null) {
            button.setImage(image);
        }
        if (label != null) {
            button.setText(label);
        }
        GridData gd = new GridData(fill);
        button.setLayoutData(gd);
        setButtonDimensionHint(button);
        return button;
    }

    /**
     * Creates and returns a new push button with the given label, tooltip and/or
     * image.
     *
     * @param parent  parent control
     * @param label   button label or null
     * @param tooltip the tooltip text for the button or null
     * @param image   image of null
     *
     * @return a new push button
     */
    public static Button createPushButton(Composite parent, String label, String tooltip, Image image) {
        Button button = createPushButton(parent, label, image);
        button.setToolTipText(tooltip);
        return button;
    }

    /**
     * Creates and returns a new radio button with the given label.
     *
     * @param parent parent control
     * @param label  button label or null
     *
     * @return a new radio button
     */
    public static Button createRadioButton(Composite parent, String label) {
        Button button = new Button(parent, SWT.RADIO);
        button.setFont(parent.getFont());
        if (label != null) {
            button.setText(label);
        }
        GridData gd = new GridData();
        button.setLayoutData(gd);
        setButtonDimensionHint(button);
        return button;
    }

    /**
     * Creates and returns a new radio button with the given label.
     *
     * @param parent parent control
     * @param label  button label or null
     * @param hspan  the number of columns to span in the parent composite
     *
     * @return a new radio button
     */
    public static Button createRadioButton(Composite parent, String label, int hspan) {
        Button button = new Button(parent, SWT.RADIO);
        button.setFont(parent.getFont());
        if (label != null) {
            button.setText(label);
        }
        GridData gd = new GridData(GridData.BEGINNING);
        gd.horizontalSpan = hspan;
        button.setLayoutData(gd);
        setButtonDimensionHint(button);
        return button;
    }

    /**
     * Creates a new label widget
     *
     * @param parent the parent composite to add this label widget to
     * @param text   the text for the label
     * @param hspan  the horizontal span to take up in the parent composite
     * @return the new label
     *
     */
    public static Label createLabel(Composite parent, String text, int hspan) {
        Label l = new Label(parent, SWT.NONE);
        l.setFont(parent.getFont());
        l.setText(text);
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = hspan;
        gd.grabExcessHorizontalSpace = false;
        l.setLayoutData(gd);
        return l;
    }

    /**
     * Creates a new label widget
     *
     * @param parent the parent composite to add this label widget to
     * @param text   the text for the label
     * @param font   the font for the label
     * @param hspan  the horizontal span to take up in the parent composite
     * @return the new label
     */
    public static Label createLabel(Composite parent, String text, Font font, int hspan) {
        Label l = new Label(parent, SWT.NONE);
        l.setFont(font);
        l.setText(text);
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = hspan;
        l.setLayoutData(gd);
        return l;
    }

    /**
     * Creates a wrapping label
     *
     * @param parent    the parent composite to add this label to
     * @param text      the text to be displayed in the label
     * @param hspan     the horizontal span that label should take up in the parent
     *                  composite
     * @param wrapwidth the width hint that the label should wrap at
     * @return a new label that wraps at a specified width
     */
    public static Label createWrapLabel(Composite parent, String text, int hspan, int wrapwidth) {
        Label l = new Label(parent, SWT.NONE | SWT.WRAP);
        l.setFont(parent.getFont());
        l.setText(text);
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = hspan;
        gd.widthHint = wrapwidth;
        l.setLayoutData(gd);
        return l;
    }

    /**
     * Creates a new CLabel that will wrap at the specified width and
     * has the specified image
     *
     * @param parent    the parent to add this label to
     * @param text      the text for the label
     * @param image     the image for the label
     * @param hspan     the h span to take up in the parent
     * @param wrapwidth the with to wrap at
     * @return a new CLabel
     */
    public static CLabel createWrapCLabel(Composite parent, String text, Image image, int hspan, int wrapwidth) {
        CLabel label = new CLabel(parent, SWT.NONE | SWT.WRAP);
        label.setFont(parent.getFont());
        if (text != null) {
            label.setText(text);
        }
        if (image != null) {
            label.setImage(image);
        }
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = hspan;
        gd.widthHint = wrapwidth;
        label.setLayoutData(gd);
        return label;
    }

    /**
     * Creates a wrapping label
     *
     * @param parent the parent composite to add this label to
     * @param text   the text to be displayed in the label
     * @param hspan  the horizontal span that label should take up in the parent
     *               composite
     * @return a new label that wraps at a specified width
     */
    public static Label createWrapLabel(Composite parent, String text, int hspan) {
        Label l = new Label(parent, SWT.NONE | SWT.WRAP);
        l.setFont(parent.getFont());
        l.setText(text);
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = hspan;
        l.setLayoutData(gd);
        return l;
    }

    /**
     * Creates a new text widget
     *
     * @param parent the parent composite to add this text widget to
     * @param hspan  the horizontal span to take up on the parent composite
     * @return the new text widget
     *
     */
    public static Text createSingleText(Composite parent, int hspan) {
        Text t = new Text(parent, SWT.SINGLE | SWT.BORDER);
        t.setFont(parent.getFont());
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = hspan;
        t.setLayoutData(gd);
        return t;
    }

    /**
     * Creates a new text widget
     *
     * @param parent the parent composite to add this text widget to
     * @param style  the style bits for the text widget
     * @param hspan  the horizontal span to take up on the parent composite
     * @param fill   the fill for the grid layout
     * @return the new text widget
     */
    public static Text createText(Composite parent, int style, int hspan, int fill) {
        Text t = new Text(parent, style);
        t.setFont(parent.getFont());
        GridData gd = new GridData(fill);
        gd.horizontalSpan = hspan;
        t.setLayoutData(gd);
        return t;
    }

    /**
     * Creates a new text widget
     *
     * @param parent the parent composite to add this text widget to
     * @param style  the style bits for the text widget
     * @param hspan  the horizontal span to take up on the parent composite
     * @return the new text widget
     */
    public static Text createText(Composite parent, int style, int hspan) {
        Text t = new Text(parent, style);
        t.setFont(parent.getFont());
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = hspan;
        t.setLayoutData(gd);
        return t;
    }

    /**
     * Creates a new text widget
     *
     * @param parent the parent composite to add this text widget to
     * @param style  the style bits for the text widget
     * @param hspan  the horizontal span to take up on the parent composite
     * @param width  the desired width of the text widget
     * @param height the desired height of the text widget
     * @param fill   the fill style for the widget
     * @return the new text widget
     */
    public static Text createText(Composite parent, int style, int hspan, int width, int height, int fill) {
        Text t = new Text(parent, style);
        t.setFont(parent.getFont());
        GridData gd = new GridData(fill);
        gd.horizontalSpan = hspan;
        gd.widthHint = width;
        gd.heightHint = height;
        t.setLayoutData(gd);
        return t;
    }

    /**
     * Creates a new styled text widget
     *
     * @param parent the parent composite to add this styled text widget to
     * @param style  the style bits for the styled text widget
     * @param hspan  the horizontal span to take up on the parent composite
     * @param width  the desired width of the styled text widget
     * @param height the desired height of the styled text widget
     * @param fill   the fill style for the widget
     * @return the new styled text widget
     */
    public static StyledText createStyledText(Composite parent, int style, int hspan, int width, int height, int fill) {
        StyledText t = new StyledText(parent, style);
        t.setFont(parent.getFont());
        GridData gd = new GridData(fill);
        gd.horizontalSpan = hspan;
        gd.widthHint = width;
        gd.heightHint = height;
        t.setLayoutData(gd);
        return t;
    }

    /**
     * Creates a new text widget
     *
     * @param parent the parent composite to add this text widget to
     * @param style  the style bits for the text widget
     * @param hspan  the horizontal span to take up on the parent composite
     * @param text   the initial text, not null
     * @return the new text widget
     */
    public static Text createText(Composite parent, int style, int hspan, String text) {
        Text t = new Text(parent, style);
        t.setFont(parent.getFont());
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = hspan;
        t.setLayoutData(gd);
        t.setText(text);
        return t;
    }

    /**
     * Creates a Group widget
     *
     * @param parent  the parent composite to add this group to
     * @param text    the text for the heading of the group
     * @param columns the number of columns within the group
     * @param hspan   the horizontal span the group should take up on the parent
     * @param fill    the style for how this composite should fill into its parent
     * @return the new group
     *
     */
    public static Group createGroup(Composite parent, String text, int columns, int hspan, int fill) {
        Group g = new Group(parent, SWT.NONE);
        g.setLayout(new GridLayout(columns, false));
        g.setText(text);
        g.setFont(parent.getFont());
        GridData gd = new GridData(fill);
        gd.horizontalSpan = hspan;
        g.setLayoutData(gd);
        return g;
    }

    /**
     * Creates a Composite widget
     *
     * @param parent  the parent composite to add this composite to
     * @param font    the font to set on the control
     * @param columns the number of columns within the composite
     * @param hspan   the horizontal span the composite should take up on the parent
     * @param fill    the style for how this composite should fill into its parent
     * @return the new group
     */
    public static Composite createComposite(Composite parent, Font font, int columns, int hspan, int fill) {
        Composite g = new Composite(parent, SWT.NONE);
        g.setLayout(new GridLayout(columns, false));
        g.setFont(font);
        GridData gd = new GridData(fill);
        gd.horizontalSpan = hspan;
        g.setLayoutData(gd);
        return g;
    }

    /**
     * Creates an ExpandibleComposite widget
     *
     * @param parent the parent to add this widget to
     * @param style  the style for ExpandibleComposite expanding handle, and layout
     * @param label  the label for the widget
     * @param hspan  how many columns to span in the parent
     * @param fill   the fill style for the widget Can be one of
     *               GridData.FILL_HORIZONAL,
     *               GridData.FILL_BOTH or
     *               GridData.FILL_VERTICAL
     * @return a new ExpandibleComposite widget
     */
    public static ExpandableComposite createExpandibleComposite(Composite parent, int style, String label, int hspan, int fill) {
        ExpandableComposite ex = new ExpandableComposite(parent, SWT.NONE, style);
        ex.setText(label);
        ex.setFont(JFaceResources.getFontRegistry().getBold(JFaceResources.DIALOG_FONT));
        GridData gd = new GridData(fill);
        gd.horizontalSpan = hspan;
        ex.setLayoutData(gd);
        return ex;
    }

    /**
     * Creates a composite that uses the parent's font and has a grid layout
     *
     * @param parent  the parent to add the composite to
     * @param columns the number of columns the composite should have
     * @param hspan   the horizontal span the new composite should take up in the
     *                parent
     * @param fill    the fill style of the composite {@link GridData}
     * @return a new composite with a grid layout
     *
     */
    public static Composite createComposite(Composite parent, int columns, int hspan, int fill) {
        Composite g = new Composite(parent, SWT.NONE);
        g.setLayout(new GridLayout(columns, false));
        g.setFont(parent.getFont());
        GridData gd = new GridData(fill);
        gd.horizontalSpan = hspan;
        g.setLayoutData(gd);
        return g;
    }

    /**
     * Creates a vertical spacer for separating components. If applied to a
     * GridLayout, this method will automatically span all of the
     * columns of the parent to make vertical space
     *
     * @param parent   the parent composite to add this spacer to
     * @param numlines the number of vertical lines to make as space
     */
    public static void createVerticalSpacer(Composite parent, int numlines) {
        Label lbl = new Label(parent, SWT.NONE);
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        Layout layout = parent.getLayout();
        if (layout instanceof GridLayout) {
            gd.horizontalSpan = ((GridLayout) parent.getLayout()).numColumns;
        }
        gd.heightHint = numlines;
        lbl.setLayoutData(gd);
    }

    /**
     * creates a horizontal spacer for separating components
     *
     * @param comp
     * @param numlines
     */
    public static void createHorizontalSpacer(Composite comp, int numlines) {
        Label lbl = new Label(comp, SWT.NONE);
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = numlines;
        lbl.setLayoutData(gd);
    }

    /**
     * Creates a Composite widget
     *
     * @param parent       the parent composite to add this composite to
     * @param font         the font to set on the control
     * @param columns      the number of columns within the composite
     * @param hspan        the horizontal span the composite should take up on the
     *                     parent
     * @param fill         the style for how this composite should fill into its
     *                     parent
     * @param marginwidth  the width of the margin to place on the sides of the
     *                     composite (default is 5, specified by GridLayout)
     * @param marginheight the height of the margin to place o the top and bottom of
     *                     the composite
     * @return the new composite
     */
    public static Composite createComposite(Composite parent, Font font, int columns, int hspan, int fill, int marginwidth, int marginheight) {
        Composite g = new Composite(parent, SWT.NONE);
        GridLayout layout = new GridLayout(columns, false);
        layout.marginWidth = marginwidth;
        layout.marginHeight = marginheight;
        g.setLayout(layout);
        g.setFont(font);
        GridData gd = new GridData(fill);
        gd.horizontalSpan = hspan;
        g.setLayoutData(gd);
        return g;
    }

    /**
     * Creates a {@link ViewForm}
     *
     * @param parent
     * @param style
     * @param cols
     * @param span
     * @param fill
     * @param marginwidth
     * @param marginheight
     * @return a new {@link ViewForm}
     */
    public static ViewForm createViewform(Composite parent, int style, int cols, int span, int fill, int marginwidth, int marginheight) {
        ViewForm form = new ViewForm(parent, style);
        form.setFont(parent.getFont());
        GridLayout layout = new GridLayout(cols, false);
        layout.marginWidth = marginwidth;
        layout.marginHeight = marginheight;
        form.setLayout(layout);
        GridData gd = new GridData(fill);
        gd.horizontalSpan = span;
        form.setLayoutData(gd);
        return form;
    }

    /**
     * Creates a Composite widget
     *
     * @param parent       the parent composite to add this composite to
     * @param font         the font to set on the control
     * @param style        the style bits for the composite. See {@link Composite}
     *                     for details on supported style bits
     * @param columns      the number of columns within the composite
     * @param hspan        the horizontal span the composite should take up on the
     *                     parent
     * @param fill         the style for how this composite should fill into its
     *                     parent
     * @param marginwidth  the width of the margin to place on the sides of the
     *                     composite (default is 5, specified by GridLayout)
     * @param marginheight the height of the margin to place o the top and bottom of
     *                     the composite
     * @return the new composite
     */
    public static Composite createComposite(Composite parent, Font font, int style, int columns, int hspan, int fill, int marginwidth, int marginheight) {
        Composite g = new Composite(parent, style);
        GridLayout layout = new GridLayout(columns, false);
        layout.marginWidth = marginwidth;
        layout.marginHeight = marginheight;
        g.setLayout(layout);
        g.setFont(font);
        GridData gd = new GridData(fill);
        gd.horizontalSpan = hspan;
        g.setLayoutData(gd);
        return g;
    }

    /**
     * This method is used to make a combo box
     *
     * @param parent the parent composite to add the new combo to
     * @param style  the style for the Combo
     * @param hspan  the horizontal span to take up on the parent composite
     * @param fill   how the combo will fill into the composite Can be one of
     *               GridData.FILL_HORIZONAL,
     *               GridData.FILL_BOTH or
     *               GridData.FILL_VERTICAL
     * @param items  the item to put into the combo
     * @return a new Combo instance
     */
    public static Combo createCombo(Composite parent, int style, int hspan, int fill, String[] items) {
        Combo c = new Combo(parent, style);
        c.setFont(parent.getFont());
        GridData gd = new GridData(fill);
        gd.horizontalSpan = hspan;
        c.setLayoutData(gd);
        if (items != null) {
            c.setItems(items);
        }
        c.setVisibleItemCount(30);
        c.select(0);
        return c;
    }

    /**
     * This method is used to make a combo box with a default fill style of
     * GridData.FILL_HORIZONTAL
     *
     * @param parent the parent composite to add the new combo to
     * @param style  the style for the Combo
     * @param hspan  the horizontal span to take up on the parent composite
     * @param items  the item to put into the combo
     * @return a new Combo instance
     */
    public static Combo createCombo(Composite parent, int style, int hspan, String[] items) {
        Combo c = new Combo(parent, style);
        c.setFont(parent.getFont());
        GridData gd = new GridData(GridData.FILL_HORIZONTAL);
        gd.horizontalSpan = hspan;
        c.setLayoutData(gd);
        if (items != null) {
            c.setItems(items);
        }
        c.setVisibleItemCount(30);
        c.select(0);
        return c;
    }

    /**
     * This method allows us to open the preference dialog on the specific page, in
     * this case the perspective page
     *
     * @param id the id of preference page to show
     */
    public static void showPreferencePage(String id) {
        PreferencesUtil.createPreferenceDialogOn(EclipseUtil.getActiveWorkbenchShell(), id, new String[] { id }, null).open();
    }

    /**
     * This method allows users to open a specific preference page and supply a
     * custom set of page filter items.
     *
     * This alternative to showPreferencePage(String) allows other
     * related pref pages to be shown at the same time at the developers/context
     * discretion. All pages can be shown if null is passed.
     *
     * @param page_id      the id for the page to open
     * @param page_filters the listing of pages to be shown in the dialog
     */
    public static void showPreferencePage(String page_id, String[] page_filters) {
        PreferencesUtil.createPreferenceDialogOn(EclipseUtil.getActiveWorkbenchShell(), page_id, page_filters, null).open();
    }
}


text:
layout: text/textblock
---

- Check if your content is findable by external and internal search.
- Decide if you need to update your keyword strategy.
- Could you improve on the call-to-action in your metadata?

See [Writing for SEO](https://guides.service.gov.au/content-guide/search-engines/)


text:
layout: page
title: About
permalink: about/
lang: fr
---

  Polyglot est un plugin open source d'internationalisation pour les blogs construits avec Jekyll. Polyglot est facile à installer et à utiliser pour tout projet, et il évolue avec les langues que vous souhaitez supporter. Avec solution de repli pour le contenu manquant, relativisation automatique d'URL, et de puissantes recettes de SEO, Polyglot permet un blog multi-langue pour se concentrer sur le contenu uniquement.

[**Polyglot Github Page**](https://github.com/untra/polyglot)

**Install**
{% highlight bash %}
gem install jekyll-polyglot
{% endhighlight %}


text:
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<title>Pixi Flash Example - Flash Color Effects/CreateJS ColorFilter</title>
		<meta name="description" content="">
		<meta name='viewport' content='width=device-width, initial-scale=1.0'>

		<!-- Example (not required) dependencies -->
		<script src="../libs/jquery.min.js"></script>

		<!-- Required dependencies -->
		<script src="../libs/tweenjs-NEXT.min.js"></script>
		<script src="../libs/pixi.min.js"></script>

		<!-- PIXI Flash dependencies -->
		<script src="../../dist/pixi-flash.js"></script>

		<!-- The Flash exported animation -->
		<script src="ColorEffects.js"></script>

	</head>
	<body>
		<div id="content" class="canvas">
			<canvas id="stage" width="800" height="500"></canvas>
<script>

var renderer = new PIXI.autoDetectRenderer(500, 720, {
	view: document.getElementById("stage"),
	backgroundColor: 0xffffff
});

// Don't prevent default
renderer.plugins.interaction.autoPreventDefault = false;

// Root display object
var stage = new PIXI.Container();

// Load the spritesheet data
$.getJSON("ColorEffects_atlas_.json", function(data)
{
    // Load the atlas for the character
	pixiflash.SpriteSheet.fromData(data, function()
	{
		// Create art & Add to stage
		stage.addChild(new pixiflash_lib.ColorEffects());
	});
});

update();
function update()
{
    requestAnimationFrame(update);
    renderer.render(stage);
}

</script>
		</div>
	</body>
</html>


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>SPService</title>
<meta name="date" content="2012-06-19">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

BESA.Kernel.Social.ServiceProvider.agent

Class SPService

java.lang.Object

BESA.Kernel.Social.ServiceProvider.agent.SPService

public abstract class SPService
extends java.lang.Object

This class represents

Since:

JDK1.0

Constructor Summary

Constructors

Constructor and Description

SPService()

Method Summary

Methods

Modifier and Type
Method and Description

abstract DataBESA
executeService(SPServiceDataRequest data,
              AdapterBESA adapter)

java.lang.String
getName()

void
setName(java.lang.String name)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

SPService

public SPService()

Method Detail

setName

public void setName(java.lang.String name)

Parameters:

name - the name to set

getName

public java.lang.String getName()

Returns:

the name

executeService

public abstract DataBESA executeService(SPServiceDataRequest data,
                      AdapterBESA adapter)

Parameters:

adapter - TODO

SPServiceDataMoveRobot - data    los datos necesarios para ejecutar el servicio

Returns:

SPServiceDataRequest    los datos posteriores a haber ejecutado el servicio

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php declare(strict_types=1);

namespace Darvin\MenuBundle\Form\Type\Admin;

use Darvin\MenuBundle\Provider\Registry\MenuProviderRegistryInterface;
use Darvin\MenuBundle\Switcher\MenuSwitcherInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;

/**
 * Menu switcher admin form type
 */
class MenuSwitcherType extends AbstractType
{
    /**
     * @var \Darvin\MenuBundle\Provider\Registry\MenuProviderRegistryInterface
     */
    private $menuProvider;

    /**
     * @var \Darvin\MenuBundle\Switcher\MenuSwitcherInterface
     */
    private $menuSwitcher;

    /**
     * @param \Darvin\MenuBundle\Provider\Registry\MenuProviderRegistryInterface $menuProvider Menu provider
     * @param \Darvin\MenuBundle\Switcher\MenuSwitcherInterface                  $menuSwitcher Menu switcher
     */
    public function __construct(MenuProviderRegistryInterface $menuProvider, MenuSwitcherInterface $menuSwitcher)
    {
        $this->menuProvider = $menuProvider;
        $this->menuSwitcher = $menuSwitcher;
    }

    /**
     * {@inheritDoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $menuProvider = $this->menuProvider;
        $menuSwitcher = $this->menuSwitcher;

        $builder
            ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($menuProvider, $menuSwitcher): void {
                $parentForm = $event->getForm()->getParent();

                $menuCollection = $menuProvider->getMenuCollection();

                if (empty($menuCollection)) {
                    $parentForm->remove($event->getForm()->getName());

                    return;
                }

                $entity = $parentForm->getData();

                $defaultMenuNames = 'new' === $parentForm->getConfig()->getOption('action_type')
                    ? $menuSwitcher->getDefaultMenus($entity)
                    : [];

                foreach ($menuCollection as $menu) {
                    $attr = [];

                    if (in_array($menu->getName(), $defaultMenuNames)) {
                        $attr['data-default'] = 1;
                    }

                    $event->getForm()->add($menu->getName(), CheckboxType::class, [
                        'label' => $menu->getTitle(),
                        'attr'  => $attr,
                    ]);
                }

                $data = [];

                foreach ($menuCollection as $menu) {
                    if ($menuSwitcher->isMenuEnabled($entity, $menu->getName())
                        || in_array($menu->getName(), $defaultMenuNames)
                    ) {
                        $data[$menu->getName()] = true;
                    }
                }

                $event->setData($data);
            })
            ->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($menuProvider, $menuSwitcher): void {
                $data   = $event->getData();
                $entity = $event->getForm()->getParent()->getData();

                foreach ($menuProvider->getMenuCollection() as $menu) {
                    $menuSwitcher->toggleMenu($entity, $menu->getName(), $data[$menu->getName()]);
                }
            });
    }

    /**
     * {@inheritDoc}
     */
    public function finishView(FormView $view, FormInterface $form, array $options): void
    {
        $view->vars['parent_selector'] = $options['parent_selector'];
    }

    /**
     * {@inheritDoc}
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setDefaults([
                'label'           => 'menu_switcher.title',
                'mapped'          => false,
                'required'        => false,
                'parent_selector' => '.parent',
            ])
            ->setAllowedTypes('parent_selector', 'string');
    }

    /**
     * {@inheritDoc}
     */
    public function getBlockPrefix(): string
    {
        return 'darvin_menu_switcher';
    }
}


text:
'use strict';

var request = require('supertest')
	, should = require('should')
	, mongojs = require('mongojs')
	, db = require('../../lib/db')
	, redisService = require('../../lib/redis')
	, app = require('../../spa.acl.server.5002').app;

var url = 'http://localhost:5002'

describe('Test vehicle api\n', function() {

	var api_url = '/api/vehicles';
	var mileage_api_url = '/api/mileages'
	var login_url = '/public/login';
	var logout_url = '/api/logout';

	// Login
	var token_id;
	before(function(done){
		var credentials = {
				username: 'mary@demo.org',
				password: 'passwd'
			}
		request(app)
		.post(login_url)
		.send(credentials)
		.expect('Content-Type', /json/)
		.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
		.expect(200)
		.end(function(err,res){
			should.not.exist(err);
			//console.log('return from login %j', res.body);
			token_id = res.body.tokenid;
			token_id.length.should.equal(40);
			done();
		});
	});

	after(function(done){
		request(app)
		.get(logout_url + '?tid=' + token_id)
		.expect('Content-Type', /json/)
		.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
		.expect(200)
		.end(function(err,res){
			should.not.exist(err);
			//console.log('return from login %j', res.body);
			done();
		});
	});

	/**
	 * Add vehicle requires
	 * 1) logged in
	 * 2) get user id via token id
	 */
	describe('Test add vehicle: http.post(' + api_url + ')', function() {

		// console.log('in client tokenid=' + token_id);
		it('should be able to add vehicle ', function(done) {

			var vehicle = {
				'name' : 'mini copper'
			}

			request(app)
			.post(api_url + '?tid=' + token_id)
			.send(vehicle)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);
				//console.log('return from save vehicle= %j', res.body);
				res.body.should.have.property('email', 'mary@demo.org');
				if (err) return done(err);
				db.remove('vehicle', {'name': "mini copper"}, true, function(err, numberOfRemovedDocs) {
					should.not.exist(err);
					// console.log('delete %j user', numberOfRemovedDocs);
					done();
				});
			});
		});
	});

	describe('Test show vehicles: http.get(' + api_url + ')', function() {
		it('should return 2 vehicles for url ', function(done) {
			request(app)
			.get(api_url + '?tid=' + token_id)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);
				res.body.should.have.lengthOf(2);
				res.body[0].should.have.property('name', 'Corolla');
				if (err) return done(err);
				done();
			});
		});
	});

	describe('Test add vehicle mileages', function() {
		var vid = null;
		//
		before(function(done) {

			db.findOne('vehicle', {'email': 'mary@demo.org'}, {'_id': 1}, function(err, vehicle){
				if (!err) {
					vid = vehicle._id.toString();
					//console.log('before add mileage with vid=' + vid);

					done();
				} else {
					console.log(err);
					return done(err);
				}
			});
		});

		after(function(done){
			//console.log('after add mileage with vid=' + vid);
			db.remove('mileage', {'vid': vid }, false, function(err, numberOfRemovedDocs) {
				should.not.exist(err);
				//console.log('delete %j mileage', numberOfRemovedDocs);
				done();
			});
		});

		var mileage = {
				//'vid': vid,
				'start': 1035093,
				'end': 1035112,
				'date': new Date('2014/3/3'),
				'type': 'private',
				'note': 'custom'
			};

		it('should be able to add vehicle mileages', function(done) {
			request(app)
			.post(mileage_api_url + '/'+ vid + '?tid=' + token_id)
			.send(mileage)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);
				//console.log('return from save mileages= %j', res.body);
				res.body.should.have.property('end', 1035112);
				if (err) return done(err);
				done();
			});
		});

	});

	describe('Test list vehicle mileage: http.get(' + mileage_api_url + '/:vid)', function() {
		// console.log('in client tokenid=' + token_id);
		var vid = null;
		//
		beforeEach(function(done) {

			db.findOne('vehicle', {'email': 'mary@demo.org'}, {'_id': 1}, function(err, vehicle){
				if (!err) {
					vid = vehicle._id.toString();
					//console.log('getting vehicle id=' + vid);
					var mileages = [{
						'vid': vid,
						'start': 1035002,
						'end': 1035042,
						'date': new Date('2014/3/1'),
						'type': 'private',
						'note': 'home to walmart'
					},{
						'vid': vid,
						'start':1035042,
						'end': 1035093,
						'date': new Date('2014/3/2'),
						'type': 'business',
						'note': 'home to toronto live'
					}];

					db.insert('mileage', mileages, function(err, insertedDocs){
						if (err) return done(err);
						//console.log('before list mileage with vid=' + vid);
						done();
					});
				} else {
					console.log(err);
					return done(err);
				}
			});
		});

		afterEach(function(done){
			//console.log('after list mileage with vid=' + vid);
			db.remove('mileage', {'vid': vid}, false, function(err, numberOfRemovedDocs) {
				should.not.exist(err);
				// console.log('delete %j user', numberOfRemovedDocs);
				done();
			});
		});

		it('should be able to list mileage by vehicle id', function(done) {
			request(app)
			.get(mileage_api_url + '/'+ vid +'?tid=' + token_id)
			.expect('Content-Type', /json/)
			.expect('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With')
			.expect(200)
			.end(function(err,res){
				should.not.exist(err);
				//console.log('return from save vehicle= %j', res.body);
				//res.body.should.have.property('email', 'mary@demo.org');
				res.body.should.have.lengthOf(2);
				if (err) return done(err);
				done();
			});
		});
	});
});


text:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class Client {
    public static void main(String[] args) throws IOException {
        Socket client = new Socket("127.0.0.1", 1234);
        client.setSoTimeout(10000);
        //获取Socket的输出流,用来发送数据到服务端
        PrintStream out = new PrintStream(client.getOutputStream());
        //获取Socket的输入流,用来接收从服务端发送过来的数据
        BufferedReader buf =  new BufferedReader(new InputStreamReader(client.getInputStream()));
        // while(true){
            //发送数据到服务端
            String newLine = System.getProperty("line.separator").toString();
            String jsonObj = "{\"method\": \"User.GetUser\", \"params\": [\"xxx\"], \"id\": 1}"+newLine;

            out.println(jsonObj);
            try{
                //从服务器端接收数据有个时间限制(系统自设,也可以自己设置),超过了这个时间,便会抛出该异常
                String echo = buf.readLine();
                System.out.println(echo);
            }catch(SocketTimeoutException e){
                System.out.println("Time out, No response");
            }
        // }
    }
}


text:
namespace util {
    // return the minium of 2 values
    template <class X>
    inline const X& min(const X &a, const X &b) {
        return (b<a) ? b : a;
    }

    // return the minium of 2 values
    template <class X>
    inline const X& max(const X &a, const X &b) {
        return (b>a) ? b : a;
    }

    // swap the values or 2 variables
    template <class X>
    inline void swap(X &a, X &b) {
        X temp = a;
        a = b;
        b = temp;
    }
    // convert a printable data type into a string
    template<typename T>
    inline std::string stringify (const T& x) {
        std::ostringstream out;
        if (!(out << x))
        return "";
        return out.str();
    }

    // triplet container class
    template<typename T1, typename T2, typename T3> class triplet {
    public:
        typedef T1 first_type;
        typedef T2 second_type;
        typedef T3 third_type;

        triplet (const T1 &a, const T2 &b, const T3 &c) : first (a), second (b), third (c) {}

        triplet () : first (T1 ()), second (T2 ()), third (T3 ()) {}

        template<typename U1, typename U2, typename U3> triplet (const triplet<U1, U2, U3> &t)
        : first (t.first), second (t.second), third (t.third) {}

    public:
        T1 first;
        T2 second;
        T3 third;
    };

    // dummy class
    class empty {};

    // vector class
    template<class T>
    class vector { // lightweight vector similar to std::vector
        public: typedef T value_type;
        private: value_type *data;
        private: unsigned int data_size;
        private: unsigned int index_end;
        public: vector() { data = NULL; data_size = 0; index_end = 0; }
        public: vector(const vector<T> &r) { // copy constructor
            copy(r);
        }
        public: vector& operator=(const vector<T>& r) { // assign operator
            if (this != &r) {
                this->free();
                copy(r);
            }
            return *this;
        }
        protected: inline void copy(const vector<T> &r) {
            if (r.data_size != 0) {
                index_end = r.index_end;
                data_size = r.data_size;
                data = new value_type[data_size];
                memcpy(data, r.data, data_size * sizeof(value_type));
            }
        }
        public: ~vector() { free(); }
        private: inline void free() { if (data != NULL) delete [] data; }
        public: inline void set_min_size(const unsigned int s) {
            if (data_size < s) {
                free();
                data_size = s;
                data = new value_type[data_size];
            }
            index_end = 0;
        }
        public: inline void push_back(const value_type &item) { data[index_end++] = item; }
        public: inline value_type &operator[](const unsigned int i) { return data[i]; }
        public: inline unsigned int size() { return index_end; }
        public: inline bool empty() { return index_end == 0; }
        public: inline void clear() { index_end = 0; }
    };

    // split FIFO queue - allows to insert at the end or at a fixed point in the middle
    template<typename T>
    class splitqueue {
        protected: std::queue<T> a,b;
        protected: size_t a_max;
        public: splitqueue() { a_max = 0; }
        public: splitqueue(size_t &p) : a_max(p) {}
        public: inline size_t size() {
            return a.size() + b.size();
        }
        public: inline void set_split(std::size_t p) {
            a_max = p;
        }
        public: inline T& front() {
            if (!a.empty()) return a.front();
            return b.front();
        }
        public: inline void push(const T v) {
            if (a.size() < a_max) {
                a.push(v);
            } else {
                b.push(v);
            }
        }
        public: inline void push_middle(const T v) {
            a.push(v);
        }
        public: inline void pop() {
            if (a.empty()) {
                if (b.empty()) return;
                b.pop();
            } else {
                a.pop();
                if (a.size() < a_max) {
                    if (b.empty()) return;
                    a.push(b.front());
                    b.pop();
                }
            }
        }
    };

    class lookup {
        protected: boost::dynamic_bitset<> tab;
        protected: std::vector<unsigned int> vals;
        public: inline void set_min_size(std::size_t s) {
            clear();
            if (tab.size() < s) {
                tab.resize(s);
                vals.reserve(s);
            }
        }
        public: inline void clear() {
            for (unsigned int i=0,iEE=vals.size(); i<iEE; ++i) {
                tab[vals[i]] = 0;
            }
            vals.clear();
        }
        public: inline void add(const unsigned int v) {
            if (tab[v] == 0) {
                tab[v] = 1;
                vals.push_back(v);
            }
        }
        public: inline bool exist(const unsigned int v) {
            return (tab[v] != 0);
        }
        public: inline std::size_t item_size() {
            return vals.size();
        }
    };

	    // trim str and store it into value
    template<class T>
    bool convert(std::string str, T &value) {
        // trim leading whitespace
        std::string str2 = str;
        char const delims[] = " \t\r\n\f";
        std::string::size_type notwhite = str2.find_first_not_of(delims);
        str2.erase(0, notwhite);

        // trim trailing whitespace
        notwhite = str2.find_last_not_of(delims);
        str2.erase(notwhite+1);

        // convert to value
        std::istringstream ss(str2);
        ss >> value;
        if (ss.fail()) return false;

        // look for junk after the value
        std::string junk;
        ss >> junk;
        if (junk.size() != 0) return false;
        return true;
    }

    //convert seconds into days, hours, minutes, and seconds format: Added by Ruchi
    inline void convertTime(int input_seconds,int &d, int &h, int &m, int &s){
        const int HOURS_IN_DAY = 24;
        const int MINS_IN_HOUR = 60;
        const int SECS_IN_MIN = 60;

        s = input_seconds % SECS_IN_MIN;
        m = (input_seconds/SECS_IN_MIN) % MINS_IN_HOUR;
        h =  ((input_seconds/SECS_IN_MIN)/MINS_IN_HOUR) % HOURS_IN_DAY;
        d = ((input_seconds/SECS_IN_MIN)/MINS_IN_HOUR)/HOURS_IN_DAY;

        return;
    }

    // extract RGB from a string of the format "#rrggbb"
    inline bool extractRGB(const std::string &str, unsigned int &r, unsigned int &g, unsigned int &b) {
        // trim leading whitespace
        std::string str2 = str;
        char const delims[] = " \t\r\n\f";
        std::string::size_type notwhite = str2.find_first_not_of(delims);
        str2.erase(0, notwhite);

        // trim trailing whitespace
        notwhite = str2.find_last_not_of(delims);
        str2.erase(notwhite+1);

        {
            std::string str = std::string("0x") + str2.substr(1,2);
            std::stringstream ss;
            ss << std::hex << str;
            ss >> r;
            if (ss.fail()) return false;
        }
        {
            std::string str = std::string("0x") + str2.substr(3,2);
            std::stringstream ss;
            ss << std::hex << str;
            ss >> g;
            if (ss.fail()) return false;
        }
        {
            std::string str = std::string("0x") + str2.substr(5,2);
            std::stringstream ss;
            ss << std::hex << str;
            ss >> b;
            if (ss.fail()) return false;
        }
        return true;
    }
    // concatenate 2 strings and places a delimiter if needed
    inline std::string concatenateWithDelimiter(const std::string &l_str, const std::string &delim, const std::string &r_str) {
        if (l_str.empty()) return r_str;
        if (r_str.empty()) return l_str;
        return l_str + delim + r_str;
    }

}

#endif //#ifndef UTIL_HH