text:
package com.lloydtorres.stately.census;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.lloydtorres.stately.R;
import com.lloydtorres.stately.core.SlidrActivity;
import com.lloydtorres.stately.dto.CensusHistory;
import com.lloydtorres.stately.dto.CensusHistoryPoint;
import com.lloydtorres.stately.dto.CensusNationRankData;
import com.lloydtorres.stately.dto.CensusNationRankList;
import com.lloydtorres.stately.dto.CensusScale;
import com.lloydtorres.stately.helpers.RaraHelper;
import com.lloydtorres.stately.helpers.SparkleHelper;
import com.lloydtorres.stately.helpers.network.DashHelper;
import com.lloydtorres.stately.helpers.network.NSStringRequest;
import com.lloydtorres.stately.zombie.NightmareHelper;
import com.omadahealth.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.omadahealth.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;

import org.simpleframework.xml.core.Persister;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Locale;

/**
 * Created by Lloyd on 2016-04-10.
 * This activity downloads and graphs the history of a given dataset.
 * Users can also switch between different datasets.
 */
public class TrendsActivity extends SlidrActivity {
    // Keys for intent/saved instance data
    public static final String TREND_DATA_TARGET = "trendTarget";
    public static final String TREND_DATA_ID = "trendId";
    public static final String TREND_DATA_START = "trendStart";
    public static final String TREND_DATA_MODE = "trendMode";
    public static final String TREND_DATA_DATASET = "trendDataset";

    public static final int TREND_NATION = 0;
    public static final int TREND_REGION = 1;
    public static final int TREND_WORLD = 2;

    public static final int CENSUS_CIVIL_RIGHTS = 0;
    public static final int CENSUS_ECONOMY = 1;
    public static final int CENSUS_POLITICAL_FREEDOM = 2;
    public static final int CENSUS_GOVERNMENT_SIZE = 27;
    public static final int CENSUS_TAXATION = 49;
    public static final int CENSUS_INFLUENCE = 65;
    public static final int CENSUS_AVERAGE_INCOME = 72;
    public static final int CENSUS_AVERAGE_INCOME_RICH = 74;
    public static final int CENSUS_ECONOMIC_OUTPUT = 76;
    public static final int CENSUS_CRIME = 77;
    public static final int CENSUS_ZDAY_SURVIVORS = 81;
    public static final int CENSUS_ZDAY_ZOMBIES = 82;
    public static final int CENSUS_ZDAY_ZOMBIFICATION = 84;

    // Unix time for midnight on 9 September 2020 (Eastern Time)
    private static final long AVERAGE_RICH_SCALE_CUTOFF = 1599624000L;

    private String target;
    private int id;
    private int mode;
    private int start = 1;
    private CensusHistory dataset;

    private LinkedHashMap<Integer, CensusScale> censusScales;

    private View view;
    private SwipyRefreshLayout mSwipeRefreshLayout;
    private RecyclerView mRecyclerView;
    private RecyclerView.LayoutManager mLayoutManager;
    private RecyclerView.Adapter mRecyclerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trends);

        if (getIntent() != null) {
            target = getIntent().getStringExtra(TREND_DATA_TARGET);
            id = getIntent().getIntExtra(TREND_DATA_ID, 0);
            mode = getIntent().getIntExtra(TREND_DATA_MODE, TREND_NATION);
        }

        // Setup list of census datasets
        String[] WORLD_CENSUS_ITEMS = getResources().getStringArray(R.array.census);
        censusScales = SparkleHelper.getCensusScales(WORLD_CENSUS_ITEMS);
        // Only show Z-Day related datasets if it's actually Z-Day
        // and we're showing regional or world rankings
        if (!(NightmareHelper.getIsZDayActive(this) &&
                (mode == TREND_REGION || mode == TREND_WORLD))) {
            censusScales = NightmareHelper.trimZDayCensusDatasets(censusScales);
        }

        Toolbar toolbar = findViewById(R.id.trends_toolbar);
        setToolbar(toolbar);

        view = findViewById(R.id.trends_main);

        mSwipeRefreshLayout = findViewById(R.id.trends_refresher);
        mSwipeRefreshLayout.setColorSchemeResources(RaraHelper.getThemeRefreshColours(this));
        mSwipeRefreshLayout.setEnabled(false);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(SwipyRefreshLayoutDirection direction) {
                if (direction.equals(SwipyRefreshLayoutDirection.BOTTOM)) {
                    queryNextRankData();
                }
            }
        });

        mRecyclerView = findViewById(R.id.trends_recycler);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);

        if (dataset == null) {
            startQueryDataset();
        } else {
            processDataset(dataset);
        }
    }

    private void setToolbar(Toolbar t) {
        setSupportActionBar(t);
        getSupportActionBar().setElevation(0);
        setToolbarTitle(getString(R.string.trends_title_generic));

        // Need to be able to get back to previous activity
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    /**
     * Convenience function to change toolbar title.
     * @param t New title
     */
    private void setToolbarTitle(String t) {
        getSupportActionBar().setTitle(t);
    }

    /**
     * Convenience class to show refresh animation on dataset query.
     */
    private void startQueryDataset() {
        mSwipeRefreshLayout.setEnabled(false);
        mSwipeRefreshLayout.setDirection(SwipyRefreshLayoutDirection.TOP);
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
                queryDataset();
            }
        });
    }

    /**
     * Public function for DatasetDialog; allows it to scan for a new dataset.
     * @param i Census ID
     */
    public void queryNewDataset(int i) {
        id = i;
        startQueryDataset();
    }

    /**
     * Queries NS for the history of a given dataset.
     * Gets data from 60 days ago up to the present.
     */
    private void queryDataset() {
        start = 1;

        String targetURL = "";
        String queryTarget = "";
        long curTime = System.currentTimeMillis() / 1000L;
        long twoYearsAgo = curTime - CensusHistory.CENSUS_TRENDS_RANGE_IN_SECONDS;

        switch (mode) {
            case TREND_NATION:
                queryTarget = String.format(Locale.US, CensusHistory.NATION_HISTORY,
                        SparkleHelper.getIdFromName(target));
                targetURL = String.format(Locale.US, CensusHistory.QUERY_NATION, queryTarget, id,
                        twoYearsAgo, curTime);
                break;
            case TREND_REGION:
                queryTarget = String.format(Locale.US, CensusHistory.REGION_HISTORY,
                        SparkleHelper.getIdFromName(target));
                targetURL = String.format(Locale.US, CensusHistory.QUERY_RANKED, queryTarget, id,
                        twoYearsAgo, curTime, start);
                break;
            case TREND_WORLD:
                targetURL = String.format(Locale.US, CensusHistory.QUERY_RANKED, queryTarget, id,
                        twoYearsAgo, curTime, start);
        }

        NSStringRequest stringRequest = new NSStringRequest(getApplicationContext(),
                Request.Method.GET, targetURL,
                new Response.Listener<String>() {
                    CensusHistory censusResponse = null;

                    @Override
                    public void onResponse(String response) {
                        Persister serializer = new Persister();
                        try {
                            censusResponse = serializer.read(CensusHistory.class, response);

                            // Set titles
                            String newTitle;
                            if (mode != TREND_WORLD && censusResponse.name != null) {
                                newTitle = censusResponse.name;
                            } else {
                                newTitle = getString(R.string.trends_title_world);
                            }
                            setToolbarTitle(String.format(Locale.US,
                                    getString(R.string.trends_title), newTitle));

                            if (censusResponse.scale.points != null) {
                                processDataset(censusResponse);
                            } else {
                                SparkleHelper.makeSnackbar(view, getString(R.string.trends_empty));
                                stopRefreshing();
                            }
                        } catch (Exception e) {
                            SparkleHelper.logError(e.toString());
                            SparkleHelper.makeSnackbar(view,
                                    getString(R.string.login_error_parsing));
                            stopRefreshing();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                SparkleHelper.logError(error.toString());
                stopRefreshing();
                if (error instanceof TimeoutError || error instanceof NoConnectionError || error instanceof NetworkError) {
                    SparkleHelper.makeSnackbar(view, getString(R.string.login_error_no_internet));
                } else {
                    SparkleHelper.makeSnackbar(view, getString(R.string.login_error_generic));
                }
            }
        });

        if (!DashHelper.getInstance(this).addRequest(stringRequest)) {
            stopRefreshing();
            SparkleHelper.makeSnackbar(view, getString(R.string.rate_limit_error));
        }
    }

    /**
     * Sets the given dataset as the global dataset and then displays the data to the user.
     * @param data
     */
    private void processDataset(CensusHistory data) {
        dataset = data;
        updateStartCounter(dataset.ranks);

        // Census history was cut by a factor of 100 after 9 September 2020
        // Multiply that scale by 100 for all data points after that date
        if (id == CENSUS_AVERAGE_INCOME_RICH) {
            for (CensusHistoryPoint point : dataset.scale.points) {
                if (point.timestamp > AVERAGE_RICH_SCALE_CUTOFF) {
                    point.score = point.score * 100f;
                }
            }
        }

        CensusScale censusType = SparkleHelper.getCensusScale(censusScales, id);

        mRecyclerAdapter = new TrendsRecyclerAdapter(this, mode, id, censusType.name,
                censusType.unit, dataset);
        mRecyclerView.setAdapter(mRecyclerAdapter);
        stopRefreshing();
    }

    /**
     * Updates the counter that tracks where to start querying for nation ranks.
     * @param rankList
     */
    private void updateStartCounter(CensusNationRankList rankList) {
        if (rankList != null && rankList.ranks.size() > 0) {
            start += rankList.ranks.size();
        }
    }

    /**
     * Query the next set of nation census rankings.
     */
    private void queryNextRankData() {
        String queryTarget = "";
        String targetURL = "";

        switch (mode) {
            case TREND_REGION:
                queryTarget = String.format(Locale.US, CensusHistory.REGION_HISTORY,
                        SparkleHelper.getIdFromName(target));
                targetURL = String.format(Locale.US, CensusNationRankData.QUERY, queryTarget, id,
                        start);
                break;
            case TREND_WORLD:
                targetURL = String.format(Locale.US, CensusNationRankData.QUERY, queryTarget, id,
                        start);
                break;
        }

        NSStringRequest stringRequest = new NSStringRequest(getApplicationContext(),
                Request.Method.GET, targetURL,
                new Response.Listener<String>() {
                    CensusNationRankData rankDataResponse = null;

                    @Override
                    public void onResponse(String response) {
                        Persister serializer = new Persister();
                        try {
                            rankDataResponse = serializer.read(CensusNationRankData.class,
                                    response);
                            if (rankDataResponse.ranks != null && rankDataResponse.ranks.ranks.size() > 0) {
                                dataset.ranks.ranks.addAll(rankDataResponse.ranks.ranks);
                                Collections.sort(dataset.ranks.ranks);

                                int oldItemCount = mRecyclerAdapter.getItemCount() - 1;
                                ((TrendsRecyclerAdapter) mRecyclerAdapter).addNewCensusNationRanks(rankDataResponse.ranks);
                                ((LinearLayoutManager) mLayoutManager).scrollToPositionWithOffset(oldItemCount, 40);
                                updateStartCounter(rankDataResponse.ranks);
                            } else {
                                SparkleHelper.makeSnackbar(view, getString(R.string.rmb_caught_up));
                            }
                        } catch (Exception e) {
                            SparkleHelper.logError(e.toString());
                            SparkleHelper.makeSnackbar(view,
                                    getString(R.string.login_error_parsing));
                        }
                        stopRefreshing();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                SparkleHelper.logError(error.toString());
                stopRefreshing();
                if (error instanceof TimeoutError || error instanceof NoConnectionError || error instanceof NetworkError) {
                    SparkleHelper.makeSnackbar(view, getString(R.string.login_error_no_internet));
                } else {
                    SparkleHelper.makeSnackbar(view, getString(R.string.login_error_generic));
                }
            }
        });

        if (!DashHelper.getInstance(this).addRequest(stringRequest)) {
            stopRefreshing();
            SparkleHelper.makeSnackbar(view, getString(R.string.rate_limit_error));
        }
    }

    /**
     * Call to setup the swipe refresher to stop refreshing.
     */
    private void stopRefreshing() {
        mSwipeRefreshLayout.setRefreshing(false);
        if (mode != TREND_NATION) {
            mSwipeRefreshLayout.setEnabled(true);
            mSwipeRefreshLayout.setDirection(SwipyRefreshLayoutDirection.BOTTOM);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_trends, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // Respond to the action bar's Up/Home button
                finish();
                return true;
            case R.id.nav_dataset:
                if (!isFinishing()) {
                    FragmentManager fm = getSupportFragmentManager();
                    DatasetDialog dialog = new DatasetDialog();
                    dialog.setDatasets(censusScales, id);
                    dialog.show(fm, DatasetDialog.DIALOG_TAG);
                }
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save state
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putInt(TREND_DATA_ID, id);
        savedInstanceState.putInt(TREND_DATA_MODE, mode);
        savedInstanceState.putInt(TREND_DATA_START, start);
        if (target != null) {
            savedInstanceState.putString(TREND_DATA_TARGET, target);
        }
        if (dataset != null) {
            savedInstanceState.putParcelable(TREND_DATA_DATASET, dataset);
        }
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Restore state
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState != null) {
            id = savedInstanceState.getInt(TREND_DATA_ID);
            mode = savedInstanceState.getInt(TREND_DATA_MODE);
            start = savedInstanceState.getInt(TREND_DATA_START);
            if (target == null) {
                target = savedInstanceState.getString(TREND_DATA_TARGET);
            }
            if (dataset == null) {
                dataset = savedInstanceState.getParcelable(TREND_DATA_DATASET);
            }
        }
    }
}


text:
copyright:
  years: 2016, 2017
lastupdated: "2017-02-23"

---

{:shortdesc: .shortdesc}
{:codeblock: .codeblock}
{:screen: .screen}
{:pre: .pre}

# Usando o pacote Cloudant
{: #openwhisk_catalog_cloudant}
O pacote `/whisk.system/cloudant` permite trabalhar com um banco de dados do Cloudant. Ele inclui as ações e os feeds a seguir.

| Entidade | Tipo | Parâmetros | Descrição |
| --- | --- | --- | --- |
| `/whisk.system/cloudant` | pacote | dbname, host, username, password | Trabalhar com um banco de dados do Cloudant |
| `/whisk.system/cloudant/read` | ação | dbname, id | Ler um documento a partir de um banco de dados |
| `/whisk.system/cloudant/write` | ação | dbname, overwrite, doc | Gravar um documento em um banco de dados |
| `/whisk.system/cloudant/changes` | alimentação | dbname, maxTriggers | Disparar eventos acionadores nas mudanças em um banco de dados |

Os tópicos a seguir percorrem a configuração de um banco de dados do Cloudant, a configuração de um pacote associado e o uso de ações e feeds no pacote `/whisk.system/cloudant`.

## Configurando um banco de dados Cloudant no Bluemix
{: #openwhisk_catalog_cloudant_in}

Se você estiver usando o OpenWhisk no Bluemix, o OpenWhisk criará automaticamente as ligações de pacote para as suas instâncias de serviço do Bluemix Cloudant. Se você não estiver usando o OpenWhisk e o Cloudant no Bluemix, vá para a próxima etapa.

1. Crie uma instância de serviço do Cloudant em seu [painel](http://console.ng.Bluemix.net) do Bluemix.

  Certifique-se de lembrar do nome da instância de serviço e da organização e do espaço do Bluemix nos quais você está.

2. Certifique-se de que a sua CLI do OpenWhisk esteja no namespace correspondente à organização e ao espaço do Bluemix que você usou na etapa anterior.

  ```
  wsk property set --namespace myBluemixOrg_myBluemixSpace
  ```
  {: pre}

  Como alternativa, é possível usar `wsk property set --namespace` para configurar um namespace a partir de uma lista daqueles disponíveis para você.

3. Atualize os pacotes em seu namespace. A atualização cria automaticamente um pacote de ligação para a instância de serviço do Cloudant criada.

  ```
  wsk package refresh
  ```
  {: pre}
  ```
  created bindings:
  Bluemix_testCloudant_Credentials-1
  ```

  ```
  wsk package list
  ```
  {: pre}
  ```
  packages
  /myBluemixOrg_myBluemixSpace/Bluemix_testCloudant_Credentials-1 private binding
  ```

  Você vê o nome completo da ligação do pacote que corresponde à instância de serviço do Bluemix Cloudant.

4. Verifique se a ligação do pacote que foi criada anteriormente está configurada com seu host e credenciais da instância de serviço do Cloudant Bluemix.

  ```
  wsk package get /myBluemixOrg_myBluemixSpace/Bluemix_testCloudant_Credentials-1 parameters
  ```
  {: pre}
  ```
  ok: got package /myBluemixOrg_myBluemixSpace/Bluemix_testCloudant_Credentials-1, displaying field parameters
  ```
  ```json
  [
      {
          "key": "username",
          "value": "cdb18832-2bbb-4df2-b7b1-Bluemix"
      },
      {
          "key": "host",
          "value": "cdb18832-2bbb-4df2-b7b1-Bluemix.cloudant.com"
      },
      {
          "key": "password",
          "value": "c9088667484a9ac827daf8884972737"
      }
  ]
  ```

## Configurando um banco de dados Cloudant fora do Bluemix
{: #openwhisk_catalog_cloudant_outside}

Caso você não esteja usando o OpenWhisk no Bluemix ou caso deseje configurar o banco de dados Cloudant fora do Bluemix, deve-se criar manualmente uma ligação de pacote para sua conta do Cloudant. Você
precisa do nome do host, do nome do usuário e da senha da conta do Cloudant.

1. Crie uma ligação de pacote que esteja configurada para sua conta do Cloudant.

  ```
  wsk package bind /whisk.system/cloudant myCloudant -p username MYUSERNAME -p password MYPASSWORD -p host MYCLOUDANTACCOUNT.cloudant.com
  ```
  {: pre}

2. Verifique se a ligação do pacote existe.

  ```
  wsk package list
  ```
  {: pre}
  ```
  pacotes
  /myNamespace/myCloudant private binding
  ```

## Recebendo mudanças em um banco de dados do Cloudant
{: #openwhisk_catalog_cloudant_listen}

É possível usar o feed `changes` para configurar um serviço para disparar um acionador em cada mudança em seu banco de dados do Cloudant. Os parâmetros são como segue:

- `dbname`: nome do banco de dados do Cloudant.
- `maxTriggers`: parar de disparar acionadores quando esse limite for atingido. O padrão é definido como infinite.

1. Crie um acionador com o feed `changes` na ligação do pacote criada anteriormente. Certifique-se de substituir `/myNamespace/myCloudant` pelo nome de seu pacote.

  ```
  wsk trigger create myCloudantTrigger --feed /myNamespace/myCloudant/changes --param dbname testdb
  ```
  {: pre}
  ```
  ok: feed do acionador myCloudantTrigger criado
  ```

2. Pesquisa de ativações.

  ```
  wsk activation poll
  ```
  {: pre}

3. Em seu painel do Cloudant, modifique um documento existente ou crie um novo.

4. Observe novas ativações para o acionador `myCloudantTrigger` para cada mudança no documento.

  **Nota**: se você não for capaz de observar novas ativações, consulte as seções subsequentes sobre leitura e gravação em um banco de dados do Cloudant. O teste das etapas de leitura e
gravação a seguir ajudará a verificar se as suas credenciais do Cloudant estão corretas.

  Agora, é possível criar regras e associá-las a ações para reagir às atualizações do documento.

  O conteúdo dos eventos gerados tem os parâmetros a seguir:

  - `id`: o ID do documento.
  - `seq`: o identificador de sequência que é gerado pelo Cloudant.
  - `changes`: uma matriz de objetos, cada um dos quais tendo um campo `rev` que contém o ID da revisão do documento.

  A representação JSON do evento acionador é a seguinte:

  ```json
     {
      "id": "6ca436c44074c4c2aa6a40c9a188b348",
      "seq": "2-g1AAAAL9aJyV-GJCaEuqx4-BktQkYp_dmIfC",
      "changes": [
          {
              "rev": "2-da3f80848a480379486fb4a2ad98fa16"
          }
      ]
  }
  ```

## Gravando em um banco de dados do Cloudant
{: #openwhisk_catalog_cloudant_write}

É possível usar uma ação para armazenar um documento em um banco de dados do Cloudant denominado `testdb`. Certifique-se de que esse banco de dados exista em sua conta do Cloudant.

1. Armazene um documento usando a ação `write` na ligação do pacote anteriormente criada. Certifique-se de substituir `/myNamespace/myCloudant` pelo nome de seu pacote.

  ```
  wsk action invoke /myNamespace/myCloudant/write --blocking --result --param dbname testdb --param doc "{\"_id\":\"heisenberg\",\"name\":\"Walter White\"}"
  ```
  {: pre}
  ```
  ok: invoked /myNamespace/myCloudant/write with id 62bf696b38464fd1bcaff216a68b8287
  ```
  ```json
     {
    "id": "heisenberg",
    "ok": true,
    "rev": "1-9a94fb93abc88d8863781a248f63c8c3"
  }
  ```

2. Verifique se o documento existe procurando-o em seu painel do Cloudant.

  A URL do painel para o banco de dados `testdb` é semelhante à seguinte: `https://MYCLOUDANTACCOUNT.cloudant.com/dashboard.html#database/testdb/_all_docs?limit=100`.

## Lendo de um banco de dados do Cloudant
{: #openwhisk_catalog_cloudant_read}

É possível usar uma ação para buscar um documento a partir de um banco de dados do Cloudant chamado `testdb`. Certifique-se de que esse banco de dados exista em sua conta do Cloudant.

- Busque um documento usando a ação `read` na ligação do pacote anteriormente criada. Certifique-se de substituir `/myNamespace/myCloudant` pelo nome de seu pacote.

  ```
  wsk action invoke /myNamespace/myCloudant/read --blocking --result --param dbname testdb --param id heisenberg
  ```
  {: pre}
  ```json
     {
    "_id": "heisenberg",
    "_rev": "1-9a94fb93abc88d8863781a248f63c8c3",
    "name": "Walter White"
  }
  ```

## Usando uma sequência de ações e um acionador de mudança para processar um documento de um banco de dados do Cloudant
{: #openwhisk_catalog_cloudant_read_change notoc}
É possível usar uma sequência de ações em uma regra para buscar e processar o documento associado a um evento de mudança do Cloudant.

Aqui está um código de amostra de uma ação que manipula um documento:
```javascript
function main(doc){
  return { "isWalter:" : doc.name === "Walter White"};
}
```

Crie a ação para processar o documento do Cloudant:
```
wsk action create myAction myAction.js
```
{: pre}

Para ler um documento do banco de dados, é possível usar a ação `read` do pacote do Cloudant.
A ação `read` pode ser editada com `myAction` para criar uma sequência de ações.
```
wsk action create sequenceAction --sequence /myNamespace/myCloudant/read,myAction
```
{: pre}

A ação `sequenceAction` pode ser usada em uma regra que ativa a ação em novos eventos acionadores do Cloudant.
```
wsk rule create myRule myCloudantTrigger sequenceAction
```
{: pre}

**Nota**: o acionador `changes` do Cloudant é usado para suportar o parâmetro `includeDoc`, que não é mais suportado.
  Será necessário recriar os acionadores criados anteriormente com `includeDoc`. Sigas estas etapas para recriar o acionador:
  ```
  wsk trigger delete myCloudantTrigger
  ```
  {: pre}
  ```
  wsk trigger create myCloudantTrigger --feed /myNamespace/myCloudant/changes --param dbname testdb
  ```
  {: pre}

  O exemplo ilustrado acima pode ser usado para criar uma sequência de ações para ler o documento mudado e chamar suas ações existentes.
  Lembre-se de desativar as regras que podem não ser mais válidas e criar novas usando o padrão de sequência de ações.

redpajama_set_name: RedPajamaGithub


text:
package com.happydroids.droidtowers.gui;

public abstract class OnClickCallback {
  public abstract void onClick(Dialog dialog);
}


text:
#import <Foundation/Foundation.h>
#import <WCDB/WCTDeclare.h>
#import <WCDB/WCTSelectBase.h>

/**
 Not Thread-safe
 */
@interface WCTSelect : WCTSelectBase

/**
 @brief Get next selected object. You can do an iteration using it.

     WCTObject* object = nil;
     while ((object = [select nextObject]) {
        //...
     }

 @return The real type of WCTObject depends on your selection and ORM.
 */
- (id /* WCTObject* */)nextObject;

/**
 @brief Get all selected objects.
 @return The NSArray collection of WCTObject.
         The real type of WCTObject depends on your selection and ORM.
 */
- (NSArray /* <WCTObject*> */ *)allObjects;

@end


text:
package de.bytefish.elasticutils.elasticsearch7.client.bulk.options;

import org.elasticsearch.action.bulk.BackoffPolicy;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;

public class BulkProcessingOptions {

    private String name;
    private int concurrentRequests;
    private int bulkActions;
    private ByteSizeValue bulkSize;
    private TimeValue flushInterval;
    private BackoffPolicy backoffPolicy;

    public BulkProcessingOptions(String name, int concurrentRequests, int bulkActions, ByteSizeValue bulkSize, TimeValue flushInterval, BackoffPolicy backoffPolicy) {
        this.name = name;
        this.concurrentRequests = concurrentRequests;
        this.bulkActions = bulkActions;
        this.bulkSize = bulkSize;
        this.flushInterval = flushInterval;
        this.backoffPolicy = backoffPolicy;
    }

    public String getName() {
        return name;
    }

    public int getConcurrentRequests() {
        return concurrentRequests;
    }

    public int getBulkActions() {
        return bulkActions;
    }

    public ByteSizeValue getBulkSize() {
        return bulkSize;
    }

    public TimeValue getFlushInterval() {
        return flushInterval;
    }

    public BackoffPolicy getBackoffPolicy() {
        return backoffPolicy;
    }

    public static BulkProcessingOptionsBuilder builder() {
        return new BulkProcessingOptionsBuilder();
    }
}


text:
require File.dirname(__FILE__) + '/spec_helper'

describe "Headliner" do

  before(:each) do
    @view = ActionView::Base.new
  end

  describe "loading plugin" do

    it "should be mixed into ActionView::Base" do
      ActionView::Base.included_modules.include?(Headliner).should be_true
    end

    it "should respond to 'title' helper" do
      @view.should respond_to(:title)
    end

    it "should respond to 'title' helper alias" do
      @view.should respond_to(:t)
    end

  end

  describe "saving title" do

    it "should save title" do
      @view.title("iPhone").should eql("iPhone")
    end

    it "should save headline if present" do
      @view.title("iPhone", "iPhone 3G is now on sale!").should eql("iPhone 3G is now on sale!")
    end

  end

  describe "displaying title" do

    it "should use website name if title is empty" do
      @view.title(:site => "Apple").should eql("<title>Apple</title>")
    end

    it "should use website before page by default" do
      save_basic_title
      @view.title(:site => "Apple").should eql("<title>Apple | iPhone</title>")
    end

    it "should only use markup in titles in the view" do
      save_basic_title("iPhone").should eql("iPhone")
      @view.title(:site => "Apple").should eql("<title>Apple | iPhone</title>")
    end

    it "should use page before website if :reverse" do
      save_basic_title
      @view.title(:site => "Apple", :reverse => true).should eql("<title>iPhone | Apple</title>")
    end

    it "should be lowercase if :lowercase" do
      save_basic_title
      @view.title(:site => "apple", :lowercase => true).should eql("<title>apple | iphone</title>")
    end

    it "should use custom separator if :separator" do
      save_basic_title
      @view.title(:site => "Apple", :separator => "-").should eql("<title>Apple - iPhone</title>")
      @view.title(:site => "Apple", :separator => ":").should eql("<title>Apple : iPhone</title>")
      @view.title(:site => "Apple", :separator => "—").should eql("<title>Apple — iPhone</title>")
    end

    it "should use custom prefix and suffix if available" do
      save_basic_title
      @view.title(:site => "Apple", :prefix => " |", :suffix => "| ").should eql("<title>Apple ||| iPhone</title>")
    end

    it "should collapse prefix if false" do
      save_basic_title
      @view.title(:site => "Apple", :prefix => false, :separator => ":").should eql("<title>Apple: iPhone</title>")
    end

    it "should collapse suffix if false" do
      save_basic_title
      @view.title(:site => "Apple", :suffix => false, :separator => "~").should eql("<title>Apple ~iPhone</title>")
    end

    it "should use all custom options if available" do
      save_basic_title
      @view.title(:site => "apple",
                  :prefix => " ",
                  :suffix => " ",
                  :separator => "-",
                  :lowercase => true,
                  :reverse => true).should eql("<title>iphone - apple</title>")
    end

    it "should use default one if title is not present or blank" do
      save_basic_title("")
      @view.title(:site => "Apple", :default => "New MacBook").should eql("<title>Apple | New MacBook</title>")
    end

  end

  def save_basic_title(title='iPhone')
    @view.title(title)
  end

end


text:
#import <PassKit/PKPassBackFaceView.h>

@interface PKPassGenericBackFaceView : PKPassBackFaceView
{
}

- (id)passFaceTemplate;

@end


text:
package com.ilivoo.xag.model.core.trigger.model;

public enum TriggerType {
	NULL_TRIGGER{
		@SuppressWarnings("unchecked")
		@Override
		public NullTrigger create() {
			return new NullTrigger();
		}
	}
	;
	public abstract <T extends AbstractTrigger<?>> T create();
}


text:
<?php

namespace Aggressiveswallow\Controllers;

use Symfony\Component\HttpFoundation\Response;
use Aggressiveswallow\Tools\Container;
use Aggressiveswallow\Helpers\Cart;
use Aggressiveswallow\Helpers\AjaxResponses\CartMessage;
use Aggressiveswallow\Tools\Responses\JsonResponse;
use Aggressiveswallow\Tools\Template;
use Aggressiveswallow\Tools\Responses\ErrorResponse;
use Aggressiveswallow\Models\Order;
use Aggressiveswallow\Models\User;
use Aggressiveswallow\Helpers\LoginHelper as Login;

/**
 * Simple cart controller for adding and removing products from the cart
 *
 * @author Patrick
 */
class CheckoutController
        extends BaseController {

    /**
     *
     * @var \Aggressiveswallow\Helpers\Cart
     */
    private $cart;

    public function __construct() {
        parent::__construct();
        $this->initCart();
    }

    public function paymentAction() {
        $t = new Template("cartViews/payment");
        $t->cart = $this->cart;
        return new Response($t);
    }

    public function confirmAction() {
        if (!Login::isLoggedIn()) {
            return new ErrorResponse("U bent niet ingelogd, voor deze pagina dient u ingelogd te zijn.");
        }

        if ($this->cart->isEmpty()) {
            return new ErrorResponse("De winkelwagen is leeg, dus er valt niets te kopen.");
        }

        if (!isset($_POST)) {
            return new ErrorResponse("Er zijn geen telefoon nummer en IBAN ontvangen.");
        }

        $order = new Order();
        foreach ($this->cart->getItems() as $location) {
            /* @var $location \Aggressiveswallow\Models\Location */

            // Set the binding both ways.
            $location->setOrder($order);
            $order->addLocation($location);
        }

        $user = $this->session->user;
        $order->setUser($user);

        $orderRepo = Container::make("orderRepository");
        /* @var $orderRepo \Aggressiveswallow\Repositories\OrderRepository */

        // Will update all the locations as well.
        $orderRepo->create($order);
        $t = new Template("cartViews/success");
        $t->cart = clone $this->cart;
        $this->cart->destroy();

        return new Response($t);
    }

    private function initCart() {
        $cart_name = Cart::SESSION_NAME;

        if (!$this->session->has($cart_name)) {
            $this->session->$cart_name = Container::make("cart");
        }

        $this->cart = $this->session->$cart_name;
    }

}


text:
libs=".:lib/*:/usr/share/java/*"
src="net/wimpi/modbus/*.java \
net/wimpi/modbus/cmd/*.java \
net/wimpi/modbus/facade/*.java \
net/wimpi/modbus/io/*.java \
net/wimpi/modbus/msg/*.java \
net/wimpi/modbus/net/*.java \
net/wimpi/modbus/procimg/*.java \
net/wimpi/modbus/util/*.java"
outputDir="output/"
distDir="dist/"
outputDistRoot="output/net/"
projectName="jamod-1.2mod"

java="java"
javac="javac"
jar="jar"
compileErrorsFile="errors.txt"
compileArgs="-cp $libs -d $outputDir"

COMMAND="$1"

cleanup() {
	echo "Cleaning..."
	rm -rf $outputDir
	mkdir -p $outputDir
}

dist() {
	echo "Packaging..."
	rm -rf $distDir
	mkdir -p $distDir
  jar cf $distDir$projectName.jar -C $outputDir .
}

if [ "$COMMAND" = "d" ] || [ "$COMMAND" = "clean" ]; then
	cleanup;
elif [ "$COMMAND" = "c" ] || [ "$COMMAND" = "compile" ]; then
	cleanup;
	echo "Compiling...."
	$javac $compileArgs $src &> $compileErrorsFile
	if [ $? = 0 ] ; then
		dist;
	fi
elif [ "$COMMAND" = "r" ] || [ "$COMMAND" = "run" ]; then
	echo "No running of this project..."
fi


text:
 layout: post
---

Well, be fit for such a long time. 118.8 pounds


text:
static GLenum valid_attachment_table[] = {
  GL_COLOR_ATTACHMENT0,
  GL_DEPTH_ATTACHMENT,
  GL_STENCIL_ATTACHMENT,
};

static GLenum valid_blit_filter_table[] = {
  GL_NEAREST,
  GL_LINEAR,
};

static GLenum valid_buffer_parameter_table[] = {
  GL_BUFFER_SIZE,
  GL_BUFFER_USAGE,
};

static GLenum valid_buffer_target_table[] = {
  GL_ARRAY_BUFFER,
  GL_ELEMENT_ARRAY_BUFFER,
};

static GLenum valid_buffer_usage_table[] = {
  GL_STREAM_DRAW,
  GL_STATIC_DRAW,
  GL_DYNAMIC_DRAW,
};

static GLenum valid_capability_table[] = {
  GL_DITHER,
  GL_BLEND,
  GL_CULL_FACE,
  GL_DEPTH_TEST,
  GL_POLYGON_OFFSET_FILL,
  GL_SAMPLE_ALPHA_TO_COVERAGE,
  GL_SAMPLE_COVERAGE,
  GL_SCISSOR_TEST,
  GL_STENCIL_TEST,
};

static GLenum valid_cmp_function_table[] = {
  GL_NEVER,
  GL_LESS,
  GL_EQUAL,
  GL_LEQUAL,
  GL_GREATER,
  GL_NOTEQUAL,
  GL_GEQUAL,
  GL_ALWAYS,
};

static GLenum valid_draw_mode_table[] = {
  GL_POINTS,
  GL_LINE_STRIP,
  GL_LINE_LOOP,
  GL_LINES,
  GL_TRIANGLE_STRIP,
  GL_TRIANGLE_FAN,
  GL_TRIANGLES,
};

static GLenum valid_dst_blend_factor_table[] = {
  GL_ZERO,
  GL_ONE,
  GL_SRC_COLOR,
  GL_ONE_MINUS_SRC_COLOR,
  GL_DST_COLOR,
  GL_ONE_MINUS_DST_COLOR,
  GL_SRC_ALPHA,
  GL_ONE_MINUS_SRC_ALPHA,
  GL_DST_ALPHA,
  GL_ONE_MINUS_DST_ALPHA,
  GL_CONSTANT_COLOR,
  GL_ONE_MINUS_CONSTANT_COLOR,
  GL_CONSTANT_ALPHA,
  GL_ONE_MINUS_CONSTANT_ALPHA,
};

static GLenum valid_equation_table[] = {
  GL_FUNC_ADD,
  GL_FUNC_SUBTRACT,
  GL_FUNC_REVERSE_SUBTRACT,
};

static GLenum valid_face_mode_table[] = {
  GL_CW,
  GL_CCW,
};

static GLenum valid_face_type_table[] = {
  GL_FRONT,
  GL_BACK,
  GL_FRONT_AND_BACK,
};

static GLboolean valid_false_only_table[] = {
  false,
};

static GLenum valid_frame_buffer_parameter_table[] = {
  GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE,
  GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME,
  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL,
  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE,
};

static GLenum valid_frame_buffer_target_table[] = {
  GL_FRAMEBUFFER,
};

static GLenum valid_g_l_state_table[] = {
  GL_ACTIVE_TEXTURE,
  GL_ALIASED_LINE_WIDTH_RANGE,
  GL_ALIASED_POINT_SIZE_RANGE,
  GL_ALPHA_BITS,
  GL_ARRAY_BUFFER_BINDING,
  GL_BLEND,
  GL_BLEND_COLOR,
  GL_BLEND_DST_ALPHA,
  GL_BLEND_DST_RGB,
  GL_BLEND_EQUATION_ALPHA,
  GL_BLEND_EQUATION_RGB,
  GL_BLEND_SRC_ALPHA,
  GL_BLEND_SRC_RGB,
  GL_BLUE_BITS,
  GL_COLOR_CLEAR_VALUE,
  GL_COLOR_WRITEMASK,
  GL_COMPRESSED_TEXTURE_FORMATS,
  GL_CULL_FACE,
  GL_CULL_FACE_MODE,
  GL_CURRENT_PROGRAM,
  GL_DEPTH_BITS,
  GL_DEPTH_CLEAR_VALUE,
  GL_DEPTH_FUNC,
  GL_DEPTH_RANGE,
  GL_DEPTH_TEST,
  GL_DEPTH_WRITEMASK,
  GL_DITHER,
  GL_ELEMENT_ARRAY_BUFFER_BINDING,
  GL_FRAMEBUFFER_BINDING,
  GL_FRONT_FACE,
  GL_GENERATE_MIPMAP_HINT,
  GL_GREEN_BITS,
  GL_IMPLEMENTATION_COLOR_READ_FORMAT,
  GL_IMPLEMENTATION_COLOR_READ_TYPE,
  GL_LINE_WIDTH,
  GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS,
  GL_MAX_CUBE_MAP_TEXTURE_SIZE,
  GL_MAX_FRAGMENT_UNIFORM_VECTORS,
  GL_MAX_RENDERBUFFER_SIZE,
  GL_MAX_TEXTURE_IMAGE_UNITS,
  GL_MAX_TEXTURE_SIZE,
  GL_MAX_VARYING_VECTORS,
  GL_MAX_VERTEX_ATTRIBS,
  GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS,
  GL_MAX_VERTEX_UNIFORM_VECTORS,
  GL_MAX_VIEWPORT_DIMS,
  GL_NUM_COMPRESSED_TEXTURE_FORMATS,
  GL_NUM_SHADER_BINARY_FORMATS,
  GL_PACK_ALIGNMENT,
  GL_POLYGON_OFFSET_FACTOR,
  GL_POLYGON_OFFSET_FILL,
  GL_POLYGON_OFFSET_UNITS,
  GL_RED_BITS,
  GL_RENDERBUFFER_BINDING,
  GL_SAMPLE_BUFFERS,
  GL_SAMPLE_COVERAGE_INVERT,
  GL_SAMPLE_COVERAGE_VALUE,
  GL_SAMPLES,
  GL_SCISSOR_BOX,
  GL_SCISSOR_TEST,
  GL_SHADER_BINARY_FORMATS,
  GL_SHADER_COMPILER,
  GL_STENCIL_BACK_FAIL,
  GL_STENCIL_BACK_FUNC,
  GL_STENCIL_BACK_PASS_DEPTH_FAIL,
  GL_STENCIL_BACK_PASS_DEPTH_PASS,
  GL_STENCIL_BACK_REF,
  GL_STENCIL_BACK_VALUE_MASK,
  GL_STENCIL_BACK_WRITEMASK,
  GL_STENCIL_BITS,
  GL_STENCIL_CLEAR_VALUE,
  GL_STENCIL_FAIL,
  GL_STENCIL_FUNC,
  GL_STENCIL_PASS_DEPTH_FAIL,
  GL_STENCIL_PASS_DEPTH_PASS,
  GL_STENCIL_REF,
  GL_STENCIL_TEST,
  GL_STENCIL_VALUE_MASK,
  GL_STENCIL_WRITEMASK,
  GL_SUBPIXEL_BITS,
  GL_TEXTURE_BINDING_2D,
  GL_TEXTURE_BINDING_CUBE_MAP,
  GL_UNPACK_ALIGNMENT,
  GL_UNPACK_FLIP_Y_CHROMIUM,
  GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM,
  GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM,
  GL_VIEWPORT,
};

static GLenum valid_get_max_index_type_table[] = {
  GL_UNSIGNED_BYTE,
  GL_UNSIGNED_SHORT,
  GL_UNSIGNED_INT,
};

static GLenum valid_get_tex_param_target_table[] = {
  GL_TEXTURE_2D,
  GL_TEXTURE_CUBE_MAP,
};

static GLenum valid_hint_mode_table[] = {
  GL_FASTEST,
  GL_NICEST,
  GL_DONT_CARE,
};

static GLenum valid_hint_target_table[] = {
  GL_GENERATE_MIPMAP_HINT,
};

static GLenum valid_index_type_table[] = {
  GL_UNSIGNED_BYTE,
  GL_UNSIGNED_SHORT,
};

static GLenum valid_pixel_store_table[] = {
  GL_PACK_ALIGNMENT,
  GL_UNPACK_ALIGNMENT,
  GL_UNPACK_FLIP_Y_CHROMIUM,
  GL_UNPACK_PREMULTIPLY_ALPHA_CHROMIUM,
  GL_UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM,
};

static GLint valid_pixel_store_alignment_table[] = {
  1,
  2,
  4,
  8,
};

static GLenum valid_pixel_type_table[] = {
  GL_UNSIGNED_BYTE,
  GL_UNSIGNED_SHORT_5_6_5,
  GL_UNSIGNED_SHORT_4_4_4_4,
  GL_UNSIGNED_SHORT_5_5_5_1,
};

static GLenum valid_program_parameter_table[] = {
  GL_DELETE_STATUS,
  GL_LINK_STATUS,
  GL_VALIDATE_STATUS,
  GL_INFO_LOG_LENGTH,
  GL_ATTACHED_SHADERS,
  GL_ACTIVE_ATTRIBUTES,
  GL_ACTIVE_ATTRIBUTE_MAX_LENGTH,
  GL_ACTIVE_UNIFORMS,
  GL_ACTIVE_UNIFORM_MAX_LENGTH,
};

static GLenum valid_query_object_parameter_table[] = {
  GL_QUERY_RESULT_EXT,
  GL_QUERY_RESULT_AVAILABLE_EXT,
};

static GLenum valid_query_parameter_table[] = {
  GL_CURRENT_QUERY_EXT,
};

static GLenum valid_query_target_table[] = {
  GL_ANY_SAMPLES_PASSED_EXT,
  GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT,
  GL_COMMANDS_ISSUED_CHROMIUM,
};

static GLenum valid_read_pixel_format_table[] = {
  GL_ALPHA,
  GL_RGB,
  GL_RGBA,
};

static GLenum valid_read_pixel_type_table[] = {
  GL_UNSIGNED_BYTE,
  GL_UNSIGNED_SHORT_5_6_5,
  GL_UNSIGNED_SHORT_4_4_4_4,
  GL_UNSIGNED_SHORT_5_5_5_1,
};

static GLenum valid_render_buffer_format_table[] = {
  GL_RGBA4,
  GL_RGB565,
  GL_RGB5_A1,
  GL_DEPTH_COMPONENT16,
  GL_STENCIL_INDEX8,
};

static GLenum valid_render_buffer_parameter_table[] = {
  GL_RENDERBUFFER_RED_SIZE,
  GL_RENDERBUFFER_GREEN_SIZE,
  GL_RENDERBUFFER_BLUE_SIZE,
  GL_RENDERBUFFER_ALPHA_SIZE,
  GL_RENDERBUFFER_DEPTH_SIZE,
  GL_RENDERBUFFER_STENCIL_SIZE,
  GL_RENDERBUFFER_WIDTH,
  GL_RENDERBUFFER_HEIGHT,
  GL_RENDERBUFFER_INTERNAL_FORMAT,
};

static GLenum valid_render_buffer_target_table[] = {
  GL_RENDERBUFFER,
};

static GLenum valid_shader_parameter_table[] = {
  GL_SHADER_TYPE,
  GL_DELETE_STATUS,
  GL_COMPILE_STATUS,
  GL_INFO_LOG_LENGTH,
  GL_SHADER_SOURCE_LENGTH,
  GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE,
};

static GLenum valid_shader_precision_table[] = {
  GL_LOW_FLOAT,
  GL_MEDIUM_FLOAT,
  GL_HIGH_FLOAT,
  GL_LOW_INT,
  GL_MEDIUM_INT,
  GL_HIGH_INT,
};

static GLenum valid_shader_type_table[] = {
  GL_VERTEX_SHADER,
  GL_FRAGMENT_SHADER,
};

static GLenum valid_src_blend_factor_table[] = {
  GL_ZERO,
  GL_ONE,
  GL_SRC_COLOR,
  GL_ONE_MINUS_SRC_COLOR,
  GL_DST_COLOR,
  GL_ONE_MINUS_DST_COLOR,
  GL_SRC_ALPHA,
  GL_ONE_MINUS_SRC_ALPHA,
  GL_DST_ALPHA,
  GL_ONE_MINUS_DST_ALPHA,
  GL_CONSTANT_COLOR,
  GL_ONE_MINUS_CONSTANT_COLOR,
  GL_CONSTANT_ALPHA,
  GL_ONE_MINUS_CONSTANT_ALPHA,
  GL_SRC_ALPHA_SATURATE,
};

static GLenum valid_stencil_op_table[] = {
  GL_KEEP,
  GL_ZERO,
  GL_REPLACE,
  GL_INCR,
  GL_INCR_WRAP,
  GL_DECR,
  GL_DECR_WRAP,
  GL_INVERT,
};

static GLenum valid_string_type_table[] = {
  GL_VENDOR,
  GL_RENDERER,
  GL_VERSION,
  GL_SHADING_LANGUAGE_VERSION,
  GL_EXTENSIONS,
};

static GLenum valid_texture_bind_target_table[] = {
  GL_TEXTURE_2D,
  GL_TEXTURE_CUBE_MAP,
};

static GLint valid_texture_border_table[] = {
  0,
};

static GLenum valid_texture_format_table[] = {
  GL_ALPHA,
  GL_LUMINANCE,
  GL_LUMINANCE_ALPHA,
  GL_RGB,
  GL_RGBA,
};

static GLenum valid_texture_internal_format_table[] = {
  GL_ALPHA,
  GL_LUMINANCE,
  GL_LUMINANCE_ALPHA,
  GL_RGB,
  GL_RGBA,
};

static GLenum valid_texture_internal_format_storage_table[] = {
  GL_RGB565,
  GL_RGBA4,
  GL_RGB5_A1,
  GL_ALPHA8_EXT,
  GL_LUMINANCE8_EXT,
  GL_LUMINANCE8_ALPHA8_EXT,
  GL_RGB8_OES,
  GL_RGBA8_OES,
};

static GLenum valid_texture_mag_filter_mode_table[] = {
  GL_NEAREST,
  GL_LINEAR,
};

static GLenum valid_texture_min_filter_mode_table[] = {
  GL_NEAREST,
  GL_LINEAR,
  GL_NEAREST_MIPMAP_NEAREST,
  GL_LINEAR_MIPMAP_NEAREST,
  GL_NEAREST_MIPMAP_LINEAR,
  GL_LINEAR_MIPMAP_LINEAR,
};

static GLenum valid_texture_parameter_table[] = {
  GL_TEXTURE_MAG_FILTER,
  GL_TEXTURE_MIN_FILTER,
  GL_TEXTURE_WRAP_S,
  GL_TEXTURE_WRAP_T,
};

static GLenum valid_texture_target_table[] = {
  GL_TEXTURE_2D,
  GL_TEXTURE_CUBE_MAP_POSITIVE_X,
  GL_TEXTURE_CUBE_MAP_NEGATIVE_X,
  GL_TEXTURE_CUBE_MAP_POSITIVE_Y,
  GL_TEXTURE_CUBE_MAP_NEGATIVE_Y,
  GL_TEXTURE_CUBE_MAP_POSITIVE_Z,
  GL_TEXTURE_CUBE_MAP_NEGATIVE_Z,
};

static GLenum valid_texture_usage_table[] = {
  GL_NONE,
  GL_FRAMEBUFFER_ATTACHMENT_ANGLE,
};

static GLenum valid_texture_wrap_mode_table[] = {
  GL_CLAMP_TO_EDGE,
  GL_MIRRORED_REPEAT,
  GL_REPEAT,
};

static GLint valid_vertex_attrib_size_table[] = {
  1,
  2,
  3,
  4,
};

static GLenum valid_vertex_attrib_type_table[] = {
  GL_BYTE,
  GL_UNSIGNED_BYTE,
  GL_SHORT,
  GL_UNSIGNED_SHORT,
  GL_FLOAT,
};

static GLenum valid_vertex_attribute_table[] = {
  GL_VERTEX_ATTRIB_ARRAY_NORMALIZED,
  GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING,
  GL_VERTEX_ATTRIB_ARRAY_ENABLED,
  GL_VERTEX_ATTRIB_ARRAY_SIZE,
  GL_VERTEX_ATTRIB_ARRAY_STRIDE,
  GL_VERTEX_ATTRIB_ARRAY_TYPE,
  GL_CURRENT_VERTEX_ATTRIB,
};

static GLenum valid_vertex_pointer_table[] = {
  GL_VERTEX_ATTRIB_ARRAY_POINTER,
};

static GLint valid_zero_only_table[] = {
  0,
};

Validators::Validators()
    : attachment(
          valid_attachment_table, arraysize(valid_attachment_table)),
      blit_filter(
          valid_blit_filter_table, arraysize(valid_blit_filter_table)),
      buffer_parameter(
          valid_buffer_parameter_table, arraysize(
              valid_buffer_parameter_table)),
      buffer_target(
          valid_buffer_target_table, arraysize(valid_buffer_target_table)),
      buffer_usage(
          valid_buffer_usage_table, arraysize(valid_buffer_usage_table)),
      capability(
          valid_capability_table, arraysize(valid_capability_table)),
      cmp_function(
          valid_cmp_function_table, arraysize(valid_cmp_function_table)),
      compressed_texture_format(),
      draw_mode(
          valid_draw_mode_table, arraysize(valid_draw_mode_table)),
      dst_blend_factor(
          valid_dst_blend_factor_table, arraysize(
              valid_dst_blend_factor_table)),
      equation(
          valid_equation_table, arraysize(valid_equation_table)),
      face_mode(
          valid_face_mode_table, arraysize(valid_face_mode_table)),
      face_type(
          valid_face_type_table, arraysize(valid_face_type_table)),
      false_only(
          valid_false_only_table, arraysize(valid_false_only_table)),
      frame_buffer_parameter(
          valid_frame_buffer_parameter_table, arraysize(
              valid_frame_buffer_parameter_table)),
      frame_buffer_target(
          valid_frame_buffer_target_table, arraysize(
              valid_frame_buffer_target_table)),
      g_l_state(
          valid_g_l_state_table, arraysize(valid_g_l_state_table)),
      get_max_index_type(
          valid_get_max_index_type_table, arraysize(
              valid_get_max_index_type_table)),
      get_tex_param_target(
          valid_get_tex_param_target_table, arraysize(
              valid_get_tex_param_target_table)),
      hint_mode(
          valid_hint_mode_table, arraysize(valid_hint_mode_table)),
      hint_target(
          valid_hint_target_table, arraysize(valid_hint_target_table)),
      index_type(
          valid_index_type_table, arraysize(valid_index_type_table)),
      pixel_store(
          valid_pixel_store_table, arraysize(valid_pixel_store_table)),
      pixel_store_alignment(
          valid_pixel_store_alignment_table, arraysize(
              valid_pixel_store_alignment_table)),
      pixel_type(
          valid_pixel_type_table, arraysize(valid_pixel_type_table)),
      program_parameter(
          valid_program_parameter_table, arraysize(
              valid_program_parameter_table)),
      query_object_parameter(
          valid_query_object_parameter_table, arraysize(
              valid_query_object_parameter_table)),
      query_parameter(
          valid_query_parameter_table, arraysize(valid_query_parameter_table)),
      query_target(
          valid_query_target_table, arraysize(valid_query_target_table)),
      read_pixel_format(
          valid_read_pixel_format_table, arraysize(
              valid_read_pixel_format_table)),
      read_pixel_type(
          valid_read_pixel_type_table, arraysize(valid_read_pixel_type_table)),
      render_buffer_format(
          valid_render_buffer_format_table, arraysize(
              valid_render_buffer_format_table)),
      render_buffer_parameter(
          valid_render_buffer_parameter_table, arraysize(
              valid_render_buffer_parameter_table)),
      render_buffer_target(
          valid_render_buffer_target_table, arraysize(
              valid_render_buffer_target_table)),
      shader_binary_format(),
      shader_parameter(
          valid_shader_parameter_table, arraysize(
              valid_shader_parameter_table)),
      shader_precision(
          valid_shader_precision_table, arraysize(
              valid_shader_precision_table)),
      shader_type(
          valid_shader_type_table, arraysize(valid_shader_type_table)),
      src_blend_factor(
          valid_src_blend_factor_table, arraysize(
              valid_src_blend_factor_table)),
      stencil_op(
          valid_stencil_op_table, arraysize(valid_stencil_op_table)),
      string_type(
          valid_string_type_table, arraysize(valid_string_type_table)),
      texture_bind_target(
          valid_texture_bind_target_table, arraysize(
              valid_texture_bind_target_table)),
      texture_border(
          valid_texture_border_table, arraysize(valid_texture_border_table)),
      texture_format(
          valid_texture_format_table, arraysize(valid_texture_format_table)),
      texture_internal_format(
          valid_texture_internal_format_table, arraysize(
              valid_texture_internal_format_table)),
      texture_internal_format_storage(
          valid_texture_internal_format_storage_table, arraysize(
              valid_texture_internal_format_storage_table)),
      texture_mag_filter_mode(
          valid_texture_mag_filter_mode_table, arraysize(
              valid_texture_mag_filter_mode_table)),
      texture_min_filter_mode(
          valid_texture_min_filter_mode_table, arraysize(
              valid_texture_min_filter_mode_table)),
      texture_parameter(
          valid_texture_parameter_table, arraysize(
              valid_texture_parameter_table)),
      texture_target(
          valid_texture_target_table, arraysize(valid_texture_target_table)),
      texture_usage(
          valid_texture_usage_table, arraysize(valid_texture_usage_table)),
      texture_wrap_mode(
          valid_texture_wrap_mode_table, arraysize(
              valid_texture_wrap_mode_table)),
      vertex_attrib_size(
          valid_vertex_attrib_size_table, arraysize(
              valid_vertex_attrib_size_table)),
      vertex_attrib_type(
          valid_vertex_attrib_type_table, arraysize(
              valid_vertex_attrib_type_table)),
      vertex_attribute(
          valid_vertex_attribute_table, arraysize(
              valid_vertex_attribute_table)),
      vertex_pointer(
          valid_vertex_pointer_table, arraysize(valid_vertex_pointer_table)),
      zero_only(
          valid_zero_only_table, arraysize(valid_zero_only_table)) {
}

#endif  // GPU_COMMAND_BUFFER_SERVICE_GLES2_CMD_VALIDATION_IMPLEMENTATION_AUTOGEN_H_  // NOLINT


text:
#ifndef __TCPIP_CONFIG_H
#define __TCPIP_CONFIG_H

#include "rX_Version.h"

/*-------------------------------------------------------------------------*
 * Program Options                                                         *
 *-------------------------------------------------------------------------*/

/*-------------------------------------------------------------------------*
 * Debug Options                                                           *
 *-------------------------------------------------------------------------*/

/* #define DEBUG_TCPIP_CONFIG      Enable debug options, see details below    */

#ifdef DEBUG_TCPIP_CONFIG

#warning  "!!!!!!!!!! Warning: Debug options DEBUG_TCPIP_CONFIG enabled !!!!!!!!!!"

/* #define DEBUG_TCP_FSM_EVENT_COUNTER              Enable TCP state machine event counters           */
/* #define DEBUG_ETH_OUT_FRAME_PADDING_BY_SOFTWARE  Circumvent automatic frame padding by controller  */
/* #define DEBUG_TCP_SEND_CALL_TRACE                Enable tcp_send call trace                        */
/* #define DEBUG_DHCP_EVENT_TRACE                   Enable DHCP event trace                           */
/* #define DEBUG_TCP_LED_LIVESIGN                   Enable LiveSign LED in cyclic event (packet)      */

#endif /* #ifdef DEBUG_TCPIP_CONFIG */

/*-------------------------------------------------------------------------*
 * Constants                                                               *
 *-------------------------------------------------------------------------*/

/* Optional functionality */
#define CONFIG_MCAST                            /* Enable multicast functionality */

/* #define CONFIG_NID_SET_IP_ADDR_TIME_RESTRICTED  Enable time restriction for NetIdent's SetIpAddress */

/* #define CONFIG_ARP_REQ_INTF                        Enable user interface for sending ARP requests */
#define CONFIG_ARP_REQ_INTF_DBLY                   /* Enable user interface for sending ARP requests (new version) */

/****************************************************************************************************************
 *
 *  TCP/IP stack configuration (memory consumption)
 *  See also startup parameters TCPIP_TCP_TASK_STARTUPPARAMETER_T (TcpipTcpTask_Functionlist.h)
 *
 *  Parameter               Declaration                                 Default
 *  ---------------------------------------------------------------------------------------------
 *
 *  TCP_RECV_BUF_SIZE       Socket's receive buffer size                2048
 *
 *  ETH_FRAME_MIN_LEN       Min length of an Ethernet frame             60
 *
 *  IP_MSS                  Maximum segment size for Ethernet           1400
 *
 *  ARP_HASH_SIZE           Number of entries in ARP hash table         16
 *  ARP_TIMEOUT_xx          See below..
 *
 *  ROUTE_CACHE_SIZE        Number of entries in route cache            32
 *  ROUTE_HASH_SIZE         Number of entries in route hash table       16
 *  ROUTE_TIMEOUT_CACHE     Timeout for route cache entries (seconds)   900
 *
 *  MCAST_TABLE_SIZE        Number of entries multicast address table   96
 *  MCAST_HASH_SIZE         Number of entries in multicast address
 *                          hash table                                  16
 *
 *  EMTY_QUE_DATA_SIZE      Empty queue max. data size for receive data TCPIP_MAX_TCP_UDP_DATA_CNT
 *                          (1472 = max. UDP datagram size!, see TcpipTcpTask_Public.h)
 *
 ****************************************************************************************************************/

/* Size of socket's receive buffer */
#define TCP_RECV_BUF_SIZE               (2048)  /* Equals max. TCP receive window                               */
                                                /* Note: TCP_RECV_BUF_SIZE must be a power of 2, else the ring  */
                                                /*        buffer mechanism will fail                            */
                                                /*       TCP_RECV_BUF_SIZE must not exceed 32767, else some     */
                                                /*        signed integer variables will overflow                */
                                                /*       Don't forget to adjust the TMIF_ADJUST_RECV_BUF_OFFSET */
                                                /*        macro definition when changing TCP_RECV_BUF_SIZE      */

/* Maximum segment size for Ethernet */
#define IP_MSS                          (1400)

#define ETH_FRAME_MIN_LEN               (60)    /* Min length of an Ethernet frame = 6 + 6 + 2 + 46 ( = Dst MAC */
                                                /* Adr + Src MAC Adr + Type field + min Ethernet data part      */
                                                /* (46 ... 1500 bytes) )                                        */

/* ARP cache sizes */
#define ARP_HASH_SIZE                   (16)    /* Number of entries in ARP hash table, must be power of 2      */

#define ARP_TIMEOUT_RESOLVE             (10)    /* Timeout before removing resolving cache entries (seconds)    */
#define ARP_TIMEOUT_RESOLVE_SILENT      (1)     /* Time between ARP requests for the same IP address (seconds)  */
/* #define ARP_TIMEOUT_CACHE            (600L)  Timeout for ARP cache entries (seconds) - is now a startup      */
                                                /* parameter ulArpTimeoutCache                                  */

#define ARP_TIMEOUT_CACHE_DIRECT        (5L)    /* Time "window" after ARP timeout ulArpTimeoutCache (startup   */
                                                /* parameter) is elapsed. Inside this window, we send a         */
                                                /* Direct ARP                                                   */

#define ARP_TIMEOUT_CACHE_HOLD          (10)    /* Timeout before removing old cache entries (seconds)          */
#define ARP_TIMEOUT_DIRECT_ARP          (ARP_TIMEOUT_RESOLVE_SILENT)  /* Timeout for Direct ARP answer          */

#define ARP_DIRECT_ARP_MAX_CNT          (3)     /* Max count of Direct ARP attempt after ARP timeout is elapsed */
#define ARP_MAX_RND_VALUE               (2047L) /* Max random value (milliseconds)  / RndGetRandom16(ptRsc)>>5  */
                                                /* = (2^16-1)>>5 = 2047 / if change, consider the >>5 (search   */
                                                /* for ARP_MAX_RND_VALUE!)                                      */
/* Route cache sizes */
#define ROUTE_CACHE_SIZE                (32)    /* Number of entries in route cache, must be multiple of 16     */
#define ROUTE_HASH_SIZE                 (16)    /* Number of entries in route hash table, must be power of 2    */

#define ROUTE_TIMEOUT_CACHE             (900)   /* Timeout for route cache entries (seconds)                    */

/* IP multicast management table sizes */
#define MCAST_TABLE_SIZE                (96)    /* Number of entries multicast address table, must be multiple  */
                                                /* of 16                                                        */
#define MCAST_HASH_SIZE                 (16)    /* Number of entries in multicast address hash table, must be   */
                                                /* power of 2                                                   */

/* Packet definitions */
#define EMTY_QUE_DATA_SIZE              TCPIP_MAX_TCP_UDP_DATA_CNT  /* Empty queue max. data size for receive   */
                                                /* data (request command TCPIP_TCP_UDP_CMD_RECEIVE_IND)         */

/* Debug: DHCP event trace */
#define DHCP_EVENT_TRACE_BUFFER_SIZE    (1000 * sizeof(DHCP_EVENT_TRACE_ENTRY))

/* Name of tasks */
#define TCP_TASK_NAME                   "TCP_UDP"

/* Name of database (DBM/NXD file) */
#if RCX_VERSION < MAKE_RCX_VERSION(2,2,0)
#define IP_DBM_FILENAME_DBM             "CONFIG.DBM"
#define IP_DBM_FILENAME_NXD             "CONFIG.NXD"
#else
#define IP_DBM_FILENAME_DBM             "SYSVOLUME:/PORT_0/CONFIG.DBM"
#define IP_DBM_FILENAME_NXD             "SYSVOLUME:/PORT_0/CONFIG.NXD"
#endif
#define IP_DBM_FILENAME_LEN             10

/* Directory of database (DBM file) */
#define IP_DBM_DIR_NAME                 "PORT_0"  /* Default = _0 = Task instance 0 -   */
                                                  /* changed by software to _0 ... _3!  */
#define IP_DBM_DIR_NAME_LEN             6

/* Names of DBM tables */
#define IP_DBM_TABLE_NAME_ETHERNET      "ETHERNET"
#define IP_DBM_TABLE_NAME_SETUP         "IP_SETUP"

#define TCP_PACKET_TIMEOUT_SEND      10
#define TCP_PACKET_TIMEOUT_WAIT      1000

#endif /* #ifndef __TCPIP_CONFIG_H */


text:
/**
 *    @file
 *          Provides an implementation of the ConfigurationManager object
 *          for MW320 platforms using the NXP SDK.
 */

#pragma once

#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
#include "wifi.h"
#ifdef __cplusplus
}
#endif //__cplusplus

#include "MW320Config.h"
#include <platform/internal/GenericConfigurationManagerImpl.h>

namespace chip {
namespace DeviceLayer {

namespace Internal {
class NetworkProvisioningServerImpl;
}

/**
 * Concrete implementation of the ConfigurationManager singleton object for the MW320 platform.
 */
// class ConfigurationManagerImpl final : public ConfigurationManager,
//                                       public Internal::GenericConfigurationManagerImpl<ConfigurationManagerImpl>,
//                                       private Internal::MW320Config
class ConfigurationManagerImpl final : public Internal::GenericConfigurationManagerImpl<Internal::MW320Config>
{
public:
    // This returns an instance of this class.
    static ConfigurationManagerImpl & GetDefaultInstance();

    // Allow the ConfigurationManager interface class to delegate method calls to
    // the implementation methods provided by this class.
    //    friend class ConfigurationManager;

    // Allow the GenericConfigurationManagerImpl base class to access helper methods and types
    // defined on this class.
    //#ifndef DOXYGEN_SHOULD_SKIP_THIS
    //    friend class Internal::GenericConfigurationManagerImpl<ConfigurationManagerImpl>;
    //#endif

private:
    // ===== Members that implement the ConfigurationManager public interface.

    CHIP_ERROR Init(void) override;
    CHIP_ERROR GetPrimaryWiFiMACAddress(uint8_t * buf) override;
    bool CanFactoryReset(void) override;
    void InitiateFactoryReset(void) override;
    CHIP_ERROR ReadPersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t & value) override;
    CHIP_ERROR WritePersistedStorageValue(::chip::Platform::PersistedStorage::Key key, uint32_t value) override;

    // NOTE: Other public interface methods are implemented by GenericConfigurationManagerImpl<>.

    // ===== Members that implement the GenericConfigurationManagerImpl protected interface.
    CHIP_ERROR ReadConfigValue(Key key, bool & val) override;
    CHIP_ERROR ReadConfigValue(Key key, uint32_t & val) override;
    CHIP_ERROR ReadConfigValue(Key key, uint64_t & val) override;
    CHIP_ERROR ReadConfigValueStr(Key key, char * buf, size_t bufSize, size_t & outLen) override;
    CHIP_ERROR ReadConfigValueBin(Key key, uint8_t * buf, size_t bufSize, size_t & outLen) override;
    CHIP_ERROR WriteConfigValue(Key key, bool val) override;
    CHIP_ERROR WriteConfigValue(Key key, uint32_t val) override;
    CHIP_ERROR WriteConfigValue(Key key, uint64_t val) override;
    CHIP_ERROR WriteConfigValueStr(Key key, const char * str) override;
    CHIP_ERROR WriteConfigValueStr(Key key, const char * str, size_t strLen) override;
    CHIP_ERROR WriteConfigValueBin(Key key, const uint8_t * data, size_t dataLen) override;
    void RunConfigUnitTest(void) override;

    // ===== Members for internal use by the following friends.

    friend class Internal::NetworkProvisioningServerImpl;
    friend ConfigurationManager & ConfigurationMgr(void);
    friend ConfigurationManagerImpl & ConfigurationMgrImpl(void);

    //    static ConfigurationManagerImpl sInstance;

    // ===== Private members reserved for use by this class only.

    static void DoFactoryReset(intptr_t arg);
};

#if 0
/**
 * Returns the public interface of the ConfigurationManager singleton object.
 *
 * Chip applications should use this to access features of the ConfigurationManager object
 * that are common to all platforms.
 */
inline ConfigurationManager & ConfigurationMgr(void)
{
    return ConfigurationManagerImpl::sInstance;
}

/**
 * Returns the platform-specific implementation of the ConfigurationManager singleton object.
 *
 * Chio applications can use this to gain access to features of the ConfigurationManager
 * that are specific to the MW320 platform.
 */
inline ConfigurationManagerImpl & ConfigurationMgrImpl(void)
{
    return ConfigurationManagerImpl::sInstance;
}
#endif // 0

inline CHIP_ERROR ConfigurationManagerImpl::GetPrimaryWiFiMACAddress(uint8_t * buf)
{
    wifi_mac_addr_t mac_addr;
    wifi_get_device_mac_addr(&mac_addr);

    memcpy(buf, mac_addr.mac, 6);
    PRINTF("MAC: %02x:%02x:%02x:%02x:%02x:%02x \r\n", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]);
    // return CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;
    return CHIP_NO_ERROR;
}

} // namespace DeviceLayer
} // namespace chip


text:
				<video autoplay="" preload="auto" loop="" poster="../wp-content/themes/tejiendoconciencia/images/alternativa2.jpg">
					<source src="../wp-content/themes/tejiendoconciencia/images/tejiendo.mp4" type="video/mp4">
					Your browser does not support the video tag.
				</video>

Somos tejedoras, somos científicas y somos concientes.

								Conocenos

A través del tejido en plástico buscamos generar conciencia sobre el consumo responsable individual.

Social

Trabajamos con sectores populares de la sociedad para que descubran en las bolsas plásticas descartadas un "recurso".

							Ver Mas

Servicios

Ofrecemos charlas, talleres, eventos y asesorías para empresas responsables social y ambientalmente; y otras organizaciones interesadas en el consumo responsable.

							Ver Mas

Investigación

Estudiamos el impacto de la sobreproducción de plástico a nivel local y global en los continentes y su relación con los desechos en el mar.

							Ver Mas

Productos

Nuestros productos son tejidos al crochet usando como materia prima bolsas de plástico que comúnmente terminarían en la basura.

							Ver Mas

Una bolsa plástica demora entre 100 y 1000 años en convertirse en minúsculas partículas de plástico, que nunca desaparecen por completo.

HASTA EL MOMENTO
HEMOS REUTILIZADO

						+

BOLSAS PLÁSTICAS

Nuestros productos son artesanales, hechos con materiales 100% reutilizados principalmente de bolsas plásticas.


text:
@implementation TimeUtilities

// Seconds per day (24h * 60m * 60s)
#define kSecondsPerDay 86400.0f

+ (BOOL) dateIsToday:(NSDate*)dateToCheck
{
    // Split today into components
    NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents* comps = [gregorian components:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit)
                                           fromDate:[NSDate date]];

    // Set to this morning 00:00:00
    [comps setHour:0];
    [comps setMinute:0];
    [comps setSecond:0];
    NSDate* theMidnightHour = [gregorian dateFromComponents:comps];
    [gregorian release];

    // Get time difference (in seconds) between date and then
    NSTimeInterval diff = [dateToCheck timeIntervalSinceDate:theMidnightHour];

    return ( diff>=0.0f && diff < kSecondsPerDay );
}

+ (NSString *) getNicelyFormattedTimeSinceDate: (NSDate *) date {

    if(date == nil) {
        return @"...";
    }

    NSUInteger desiredComponents = NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit
    | NSMinuteCalendarUnit | NSSecondCalendarUnit;

    // NSLog(@"Getting time difference for date: %@", date);

    NSDateComponents *elapsedTimeUnits = [[NSCalendar currentCalendar] components: desiredComponents
                                                                         fromDate: date
                                                                           toDate: [NSDate date]
                                                                          options:0];
    // format to be used to generate string to display
    NSString *scannedFormat = @"%d %@ ago";
    NSInteger number = 0;
    NSString *unit = @"";

    if ([elapsedTimeUnits year] > 0) {
        number = [elapsedTimeUnits year];
        unit = [NSString stringWithFormat:@"year"];
    }
    else if ([elapsedTimeUnits month] > 0) {
        number = [elapsedTimeUnits month];
        unit = [NSString stringWithFormat:@"month"];
    }
    else if ([elapsedTimeUnits week] > 0) {
        number = [elapsedTimeUnits week];
        unit = [NSString stringWithFormat:@"week"];
    }
    else if ([elapsedTimeUnits day] > 0) {
        number = [elapsedTimeUnits day];
        unit = [NSString stringWithFormat:@"day"];
    }
    else if ([elapsedTimeUnits hour] > 0) {
        number = [elapsedTimeUnits hour];
        unit = [NSString stringWithFormat:@"hour"];
    }
    else if ([elapsedTimeUnits minute] > 0) {
        number = [elapsedTimeUnits minute];
        unit = [NSString stringWithFormat:@"minute"];
    }
    else if ([elapsedTimeUnits second] > 0) {
        number = [elapsedTimeUnits second];
        unit = [NSString stringWithFormat:@"second"];
    }
    else if([elapsedTimeUnits second] == 0) {
        return @"Just now";
    }

    // check if unit number is greater then append s at the end
    if (number > 1) {
        unit = [NSString stringWithFormat:@"%@s", unit];
    }
    // resultant string required
    NSString *scannedString = [NSString stringWithFormat:scannedFormat, number, unit];

    return scannedString;
}

@end


text:
'use strict';

var EvStore = require('./index.js');

var test = require('tape');
var document = require('global/document');

test('can fetch records out of DS', function t(assert) {
    var elem = document.body;
    var ds = EvStore(elem);

    ds.foo = 'bar';

    var ds2 = EvStore(elem);

    assert.equal(ds2.foo, 'bar');

    assert.end();
});

test('setting dash names', function t(assert) {
    var elem = document.createElement('div');
    EvStore(elem)['foo-bar'] = 'baz';

    var ds = EvStore(elem);

    assert.equal(ds['foo-bar'], 'baz');

    assert.end();
});


text:
/**
 * Generated with Acceleo
 */
package org.wso2.developerstudio.eclipse.gmf.esb.parts.forms;

// Start of user code for imports
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;

import org.eclipse.emf.edit.ui.provider.AdapterFactoryLabelProvider;

import org.eclipse.emf.eef.runtime.api.component.IPropertiesEditionComponent;

import org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent;

import org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart;

import org.eclipse.emf.eef.runtime.impl.notify.PropertiesEditionEvent;

import org.eclipse.emf.eef.runtime.part.impl.SectionPropertiesEditingPart;

import org.eclipse.emf.eef.runtime.ui.parts.PartComposer;

import org.eclipse.emf.eef.runtime.ui.parts.sequence.BindingCompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionSequence;
import org.eclipse.emf.eef.runtime.ui.parts.sequence.CompositionStep;

import org.eclipse.emf.eef.runtime.ui.utils.EditingUtils;

import org.eclipse.emf.eef.runtime.ui.widgets.EEFFeatureEditorDialog;
import org.eclipse.emf.eef.runtime.ui.widgets.FormUtils;

import org.eclipse.jface.window.Window;

import org.eclipse.swt.SWT;

import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;

import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;

import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ScrolledForm;
import org.eclipse.ui.forms.widgets.Section;

import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;

import org.wso2.developerstudio.eclipse.gmf.esb.parts.CommentMediatorPropertiesEditionPart;
import org.wso2.developerstudio.eclipse.gmf.esb.parts.EsbViewsRepository;

import org.wso2.developerstudio.eclipse.gmf.esb.providers.EsbMessages;

// End of user code

/**
 *
 *
 */
public class CommentMediatorPropertiesEditionPartForm extends SectionPropertiesEditingPart implements IFormPropertiesEditionPart, CommentMediatorPropertiesEditionPart {

	protected Text description;
	protected Text commentsList;
	protected Button editCommentsList;
	protected EList commentsListList;
	protected Button reverse;
	protected Text commentText;

	/**
	 * For {@link ISection} use only.
	 */
	public CommentMediatorPropertiesEditionPartForm() { super(); }

	/**
	 * Default constructor
	 * @param editionComponent the {@link IPropertiesEditionComponent} that manage this part
	 *
	 */
	public CommentMediatorPropertiesEditionPartForm(IPropertiesEditionComponent editionComponent) {
		super(editionComponent);
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
	 *  createFigure(org.eclipse.swt.widgets.Composite, org.eclipse.ui.forms.widgets.FormToolkit)
	 *
	 */
	public Composite createFigure(final Composite parent, final FormToolkit widgetFactory) {
		ScrolledForm scrolledForm = widgetFactory.createScrolledForm(parent);
		Form form = scrolledForm.getForm();
		view = form.getBody();
		GridLayout layout = new GridLayout();
		layout.numColumns = 3;
		view.setLayout(layout);
		createControls(widgetFactory, view);
		return scrolledForm;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.parts.IFormPropertiesEditionPart#
	 *  createControls(org.eclipse.ui.forms.widgets.FormToolkit, org.eclipse.swt.widgets.Composite)
	 *
	 */
	public void createControls(final FormToolkit widgetFactory, Composite view) {
		CompositionSequence commentMediatorStep = new BindingCompositionSequence(propertiesEditionComponent);
		CompositionStep propertiesStep = commentMediatorStep.addStep(EsbViewsRepository.CommentMediator.Properties.class);
		propertiesStep.addStep(EsbViewsRepository.CommentMediator.Properties.description);
		propertiesStep.addStep(EsbViewsRepository.CommentMediator.Properties.commentsList);
		propertiesStep.addStep(EsbViewsRepository.CommentMediator.Properties.reverse);
		propertiesStep.addStep(EsbViewsRepository.CommentMediator.Properties.commentText);

		composer = new PartComposer(commentMediatorStep) {

			@Override
			public Composite addToPart(Composite parent, Object key) {
				if (key == EsbViewsRepository.CommentMediator.Properties.class) {
					return createPropertiesGroup(widgetFactory, parent);
				}
				if (key == EsbViewsRepository.CommentMediator.Properties.description) {
					return createDescriptionText(widgetFactory, parent);
				}
				if (key == EsbViewsRepository.CommentMediator.Properties.commentsList) {
					return createCommentsListMultiValuedEditor(widgetFactory, parent);
				}
				if (key == EsbViewsRepository.CommentMediator.Properties.reverse) {
					return createReverseCheckbox(widgetFactory, parent);
				}
				if (key == EsbViewsRepository.CommentMediator.Properties.commentText) {
					return createCommentTextText(widgetFactory, parent);
				}
				return parent;
			}
		};
		composer.compose(view);
	}
	/**
	 *
	 */
	protected Composite createPropertiesGroup(FormToolkit widgetFactory, final Composite parent) {
		Section propertiesSection = widgetFactory.createSection(parent, Section.TITLE_BAR | Section.TWISTIE | Section.EXPANDED);
		propertiesSection.setText(EsbMessages.CommentMediatorPropertiesEditionPart_PropertiesGroupLabel);
		GridData propertiesSectionData = new GridData(GridData.FILL_HORIZONTAL);
		propertiesSectionData.horizontalSpan = 3;
		propertiesSection.setLayoutData(propertiesSectionData);
		Composite propertiesGroup = widgetFactory.createComposite(propertiesSection);
		GridLayout propertiesGroupLayout = new GridLayout();
		propertiesGroupLayout.numColumns = 3;
		propertiesGroup.setLayout(propertiesGroupLayout);
		propertiesSection.setClient(propertiesGroup);
		return propertiesGroup;
	}

	protected Composite createDescriptionText(FormToolkit widgetFactory, Composite parent) {
		createDescription(parent, EsbViewsRepository.CommentMediator.Properties.description, EsbMessages.CommentMediatorPropertiesEditionPart_DescriptionLabel);
		description = widgetFactory.createText(parent, ""); //$NON-NLS-1$
		description.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
		widgetFactory.paintBordersFor(parent);
		GridData descriptionData = new GridData(GridData.FILL_HORIZONTAL);
		description.setLayoutData(descriptionData);
		description.addFocusListener(new FocusAdapter() {
			/**
			 * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
			 *
			 */
			@Override
			@SuppressWarnings("synthetic-access")
			public void focusLost(FocusEvent e) {
				if (propertiesEditionComponent != null) {
					propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(
							CommentMediatorPropertiesEditionPartForm.this,
							EsbViewsRepository.CommentMediator.Properties.description,
							PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, description.getText()));
					propertiesEditionComponent
							.firePropertiesChanged(new PropertiesEditionEvent(
									CommentMediatorPropertiesEditionPartForm.this,
									EsbViewsRepository.CommentMediator.Properties.description,
									PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST,
									null, description.getText()));
				}
			}

			/**
			 * @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent)
			 */
			@Override
			public void focusGained(FocusEvent e) {
				if (propertiesEditionComponent != null) {
					propertiesEditionComponent
							.firePropertiesChanged(new PropertiesEditionEvent(
									CommentMediatorPropertiesEditionPartForm.this,
									null,
									PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED,
									null, null));
				}
			}
		});
		description.addKeyListener(new KeyAdapter() {
			/**
			 * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
			 *
			 */
			@Override
			@SuppressWarnings("synthetic-access")
			public void keyPressed(KeyEvent e) {
				if (e.character == SWT.CR) {
					if (propertiesEditionComponent != null)
						propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(CommentMediatorPropertiesEditionPartForm.this, EsbViewsRepository.CommentMediator.Properties.description, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, description.getText()));
				}
			}
		});
		EditingUtils.setID(description, EsbViewsRepository.CommentMediator.Properties.description);
		EditingUtils.setEEFtype(description, "eef::Text"); //$NON-NLS-1$
		FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.CommentMediator.Properties.description, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
		// Start of user code for createDescriptionText

		// End of user code
		return parent;
	}

	/**
	 *
	 */
	protected Composite createCommentsListMultiValuedEditor(FormToolkit widgetFactory, Composite parent) {
		commentsList = widgetFactory.createText(parent, "", SWT.READ_ONLY); //$NON-NLS-1$
		GridData commentsListData = new GridData(GridData.FILL_HORIZONTAL);
		commentsListData.horizontalSpan = 2;
		commentsList.setLayoutData(commentsListData);
		EditingUtils.setID(commentsList, EsbViewsRepository.CommentMediator.Properties.commentsList);
		EditingUtils.setEEFtype(commentsList, "eef::MultiValuedEditor::field"); //$NON-NLS-1$
		editCommentsList = widgetFactory.createButton(parent, getDescription(EsbViewsRepository.CommentMediator.Properties.commentsList, EsbMessages.CommentMediatorPropertiesEditionPart_CommentsListLabel), SWT.NONE);
		GridData editCommentsListData = new GridData();
		editCommentsList.setLayoutData(editCommentsListData);
		editCommentsList.addSelectionListener(new SelectionAdapter() {

			/**
			 * {@inheritDoc}
			 *
			 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
			 *
			 */
			public void widgetSelected(SelectionEvent e) {
				EEFFeatureEditorDialog dialog = new EEFFeatureEditorDialog(
						commentsList.getShell(), "CommentMediator", new AdapterFactoryLabelProvider(adapterFactory), //$NON-NLS-1$
						commentsListList, EsbPackage.eINSTANCE.getEsbElement_CommentsList().getEType(), null,
						false, true,
						null, null);
				if (dialog.open() == Window.OK) {
					commentsListList = dialog.getResult();
					if (commentsListList == null) {
						commentsListList = new BasicEList();
					}
					commentsList.setText(commentsListList.toString());
					propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(CommentMediatorPropertiesEditionPartForm.this, EsbViewsRepository.CommentMediator.Properties.commentsList, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new BasicEList(commentsListList)));
					setHasChanged(true);
				}
			}
		});
		EditingUtils.setID(editCommentsList, EsbViewsRepository.CommentMediator.Properties.commentsList);
		EditingUtils.setEEFtype(editCommentsList, "eef::MultiValuedEditor::browsebutton"); //$NON-NLS-1$
		// Start of user code for createCommentsListMultiValuedEditor

		// End of user code
		return parent;
	}

	protected Composite createReverseCheckbox(FormToolkit widgetFactory, Composite parent) {
		reverse = widgetFactory.createButton(parent, getDescription(EsbViewsRepository.CommentMediator.Properties.reverse, EsbMessages.CommentMediatorPropertiesEditionPart_ReverseLabel), SWT.CHECK);
		reverse.addSelectionListener(new SelectionAdapter() {

			/**
			 * {@inheritDoc}
			 *
			 * @see org.eclipse.swt.events.SelectionAdapter#widgetSelected(org.eclipse.swt.events.SelectionEvent)
			 *
			 */
			public void widgetSelected(SelectionEvent e) {
				if (propertiesEditionComponent != null)
					propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(CommentMediatorPropertiesEditionPartForm.this, EsbViewsRepository.CommentMediator.Properties.reverse, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, new Boolean(reverse.getSelection())));
			}

		});
		GridData reverseData = new GridData(GridData.FILL_HORIZONTAL);
		reverseData.horizontalSpan = 2;
		reverse.setLayoutData(reverseData);
		EditingUtils.setID(reverse, EsbViewsRepository.CommentMediator.Properties.reverse);
		EditingUtils.setEEFtype(reverse, "eef::Checkbox"); //$NON-NLS-1$
		FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.CommentMediator.Properties.reverse, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
		// Start of user code for createReverseCheckbox

		// End of user code
		return parent;
	}

	protected Composite createCommentTextText(FormToolkit widgetFactory, Composite parent) {
		createDescription(parent, EsbViewsRepository.CommentMediator.Properties.commentText, EsbMessages.CommentMediatorPropertiesEditionPart_CommentTextLabel);
		commentText = widgetFactory.createText(parent, ""); //$NON-NLS-1$
		commentText.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
		widgetFactory.paintBordersFor(parent);
		GridData commentTextData = new GridData(GridData.FILL_HORIZONTAL);
		commentText.setLayoutData(commentTextData);
		commentText.addFocusListener(new FocusAdapter() {
			/**
			 * @see org.eclipse.swt.events.FocusAdapter#focusLost(org.eclipse.swt.events.FocusEvent)
			 *
			 */
			@Override
			@SuppressWarnings("synthetic-access")
			public void focusLost(FocusEvent e) {
				if (propertiesEditionComponent != null) {
					propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(
							CommentMediatorPropertiesEditionPartForm.this,
							EsbViewsRepository.CommentMediator.Properties.commentText,
							PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, commentText.getText()));
					propertiesEditionComponent
							.firePropertiesChanged(new PropertiesEditionEvent(
									CommentMediatorPropertiesEditionPartForm.this,
									EsbViewsRepository.CommentMediator.Properties.commentText,
									PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_LOST,
									null, commentText.getText()));
				}
			}

			/**
			 * @see org.eclipse.swt.events.FocusAdapter#focusGained(org.eclipse.swt.events.FocusEvent)
			 */
			@Override
			public void focusGained(FocusEvent e) {
				if (propertiesEditionComponent != null) {
					propertiesEditionComponent
							.firePropertiesChanged(new PropertiesEditionEvent(
									CommentMediatorPropertiesEditionPartForm.this,
									null,
									PropertiesEditionEvent.FOCUS_CHANGED, PropertiesEditionEvent.FOCUS_GAINED,
									null, null));
				}
			}
		});
		commentText.addKeyListener(new KeyAdapter() {
			/**
			 * @see org.eclipse.swt.events.KeyAdapter#keyPressed(org.eclipse.swt.events.KeyEvent)
			 *
			 */
			@Override
			@SuppressWarnings("synthetic-access")
			public void keyPressed(KeyEvent e) {
				if (e.character == SWT.CR) {
					if (propertiesEditionComponent != null)
						propertiesEditionComponent.firePropertiesChanged(new PropertiesEditionEvent(CommentMediatorPropertiesEditionPartForm.this, EsbViewsRepository.CommentMediator.Properties.commentText, PropertiesEditionEvent.COMMIT, PropertiesEditionEvent.SET, null, commentText.getText()));
				}
			}
		});
		EditingUtils.setID(commentText, EsbViewsRepository.CommentMediator.Properties.commentText);
		EditingUtils.setEEFtype(commentText, "eef::Text"); //$NON-NLS-1$
		FormUtils.createHelpButton(widgetFactory, parent, propertiesEditionComponent.getHelpContent(EsbViewsRepository.CommentMediator.Properties.commentText, EsbViewsRepository.FORM_KIND), null); //$NON-NLS-1$
		// Start of user code for createCommentTextText

		// End of user code
		return parent;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionListener#firePropertiesChanged(org.eclipse.emf.eef.runtime.api.notify.IPropertiesEditionEvent)
	 *
	 */
	public void firePropertiesChanged(IPropertiesEditionEvent event) {
		// Start of user code for tab synchronization

		// End of user code
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CommentMediatorPropertiesEditionPart#getDescription()
	 *
	 */
	public String getDescription() {
		return description.getText();
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CommentMediatorPropertiesEditionPart#setDescription(String newValue)
	 *
	 */
	public void setDescription(String newValue) {
		if (newValue != null) {
			description.setText(newValue);
		} else {
			description.setText(""); //$NON-NLS-1$
		}
		boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.CommentMediator.Properties.description);
		if (eefElementEditorReadOnlyState && description.isEnabled()) {
			description.setEnabled(false);
			description.setToolTipText(EsbMessages.CommentMediator_ReadOnly);
		} else if (!eefElementEditorReadOnlyState && !description.isEnabled()) {
			description.setEnabled(true);
		}

	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CommentMediatorPropertiesEditionPart#getCommentsList()
	 *
	 */
	public EList getCommentsList() {
		return commentsListList;
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CommentMediatorPropertiesEditionPart#setCommentsList(EList newValue)
	 *
	 */
	public void setCommentsList(EList newValue) {
		commentsListList = newValue;
		if (newValue != null) {
			commentsList.setText(commentsListList.toString());
		} else {
			commentsList.setText(""); //$NON-NLS-1$
		}
		boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.CommentMediator.Properties.commentsList);
		if (eefElementEditorReadOnlyState && commentsList.isEnabled()) {
			commentsList.setEnabled(false);
			commentsList.setToolTipText(EsbMessages.CommentMediator_ReadOnly);
		} else if (!eefElementEditorReadOnlyState && !commentsList.isEnabled()) {
			commentsList.setEnabled(true);
		}

	}

	public void addToCommentsList(Object newValue) {
		commentsListList.add(newValue);
		if (newValue != null) {
			commentsList.setText(commentsListList.toString());
		} else {
			commentsList.setText(""); //$NON-NLS-1$
		}
	}

	public void removeToCommentsList(Object newValue) {
		commentsListList.remove(newValue);
		if (newValue != null) {
			commentsList.setText(commentsListList.toString());
		} else {
			commentsList.setText(""); //$NON-NLS-1$
		}
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CommentMediatorPropertiesEditionPart#getReverse()
	 *
	 */
	public Boolean getReverse() {
		return Boolean.valueOf(reverse.getSelection());
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CommentMediatorPropertiesEditionPart#setReverse(Boolean newValue)
	 *
	 */
	public void setReverse(Boolean newValue) {
		if (newValue != null) {
			reverse.setSelection(newValue.booleanValue());
		} else {
			reverse.setSelection(false);
		}
		boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.CommentMediator.Properties.reverse);
		if (eefElementEditorReadOnlyState && reverse.isEnabled()) {
			reverse.setEnabled(false);
			reverse.setToolTipText(EsbMessages.CommentMediator_ReadOnly);
		} else if (!eefElementEditorReadOnlyState && !reverse.isEnabled()) {
			reverse.setEnabled(true);
		}

	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CommentMediatorPropertiesEditionPart#getCommentText()
	 *
	 */
	public String getCommentText() {
		return commentText.getText();
	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.wso2.developerstudio.eclipse.gmf.esb.parts.CommentMediatorPropertiesEditionPart#setCommentText(String newValue)
	 *
	 */
	public void setCommentText(String newValue) {
		if (newValue != null) {
			commentText.setText(newValue);
		} else {
			commentText.setText(""); //$NON-NLS-1$
		}
		boolean eefElementEditorReadOnlyState = isReadOnly(EsbViewsRepository.CommentMediator.Properties.commentText);
		if (eefElementEditorReadOnlyState && commentText.isEnabled()) {
			commentText.setEnabled(false);
			commentText.setToolTipText(EsbMessages.CommentMediator_ReadOnly);
		} else if (!eefElementEditorReadOnlyState && !commentText.isEnabled()) {
			commentText.setEnabled(true);
		}

	}

	/**
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.emf.eef.runtime.api.parts.IPropertiesEditionPart#getTitle()
	 *
	 */
	public String getTitle() {
		return EsbMessages.CommentMediator_Part_Title;
	}

	// Start of user code additional methods

	// End of user code

}


text:
set -ex

npm install

# Prime database
mongoimport \
  --verbose \
  --host=$DB_HOST \
  --db=app-ask-craig \
  --collection=jobs \
  --type=csv \
  --headerline \
  --file=../workflow/data/craigslistJobTitles.csv


text:
package org.embulk.input.zendesk.services;

import org.apache.http.client.utils.URIBuilder;
import org.embulk.input.zendesk.ZendeskInputPlugin.PluginTask;
import org.embulk.input.zendesk.models.Target;
import org.embulk.input.zendesk.utils.ZendeskConstants;
import org.embulk.input.zendesk.utils.ZendeskUtils;

public class ZendeskSupportAPIService extends ZendeskNormalServices
{
    public ZendeskSupportAPIService(final PluginTask task)
    {
        super(task);
    }

    public boolean isSupportIncremental()
    {
        return !(task.getTarget().equals(Target.TICKET_FORMS) || task.getTarget().equals(Target.TICKET_FIELDS));
    }

    @Override
    protected String buildURI(final int page, long startTime)
    {
        final URIBuilder uriBuilder = ZendeskUtils.getURIBuilder(task.getLoginUrl()).setPath(buildPath());

        if (isSupportIncremental()) {
            uriBuilder.setParameter(ZendeskConstants.Field.START_TIME, String.valueOf(startTime));
            if (Target.TICKET_METRICS.equals(task.getTarget())) {
                uriBuilder.setParameter("include", "metric_sets");
            }
        }
        else {
            uriBuilder.setParameter("sort_by", "id")
                    .setParameter("per_page", String.valueOf(100))
                    .setParameter("page", String.valueOf(page));
        }

        return uriBuilder.toString();
    }

    private String buildPath()
    {
        return (isSupportIncremental()
                ? ZendeskConstants.Url.API_INCREMENTAL
                : ZendeskConstants.Url.API) +
                "/" +
                (Target.TICKET_METRICS.equals(task.getTarget())
                        ? Target.TICKETS.toString()
                        : task.getTarget().toString())
                + ".json";
    }
}