A primeira parte da prova será voltada a componentes na Web usando a implementação do Digital Content Component (DCC).
Utilize o ambiente DCC Playground testar a sua resposta das questões da Parte 1
, em seguida, copie e cole a resposta na respectiva resposta.
Utilize o ambiente da seguinte maneira:
Editor
Render
para que ele execute o códigoResult
Messages
Para consultar a sintaxe e ver exemplos dos DCCs veja a Referência dos DCCS.
<dcc-trigger label="Inicia"
action="button/start"
parameter="Inicia processo">
</dcc-trigger>
Crie um personagem patient
usando o <dcc-lively-talk>
com um balão de mensagens escrito "Estou me sentindo bem"
.
Acrescente dois botões:
"Sentindo mal"
e, ao ser clicado, faz a mensagem do balão do patient
mudar para "Estou me sentindo mal"
;"Sentindo bem"
e, ao ser clicado, faz a mensagem do balão do patient
mudar para "Estou me sentindo bem"
.<dcc-trigger label="Sentindo mal" action="send/message" parameter="Estou me sentindo mal.">
</dcc-trigger>
<dcc-trigger label="Sentindo bem" action="send/message" parameter="Estou me sentindo bem.">
</dcc-trigger>
<dcc-lively-talk id="patient"
duration="0s"
character="patient"
speech="Estou me sentindo bem">
<subscribe-dcc message="send/message"></subscribe>
</dcc-lively-talk>
Crie quatro botões com rótulos Mundo
, Brasil P
, Brasil E
e Bahia
que, ao serem clicados, publiquem notícias nos seguintes tópicos:
noticia/mundo/politica
noticia/brasil/politica
noticia/brasil/esporte
noticia/bahia/esporte
O segundo nível do tópico indica a região da notícia e o terceiro o assunto. Associe a cada tópico o texto de uma mensagem de sua criação.
Crie três personagens (doctor
, nurse
e patient
) usando o <dcc-lively-talk>
. Cada um deles deve mostrar seletivamente (em seu balão) notícias publicadas pelos botões, conforme os seguintes critérios:
doctor
- mostra notícias sobre política (independentemente de região);nurse
- mostra notícias cuja região é o Brasil (independentemente do assunto);patient
- mostra todas as notícias.<dcc-trigger label="Mundo"
action="noticia/mundo/politica"
parameter="Algo aconteceu no mundo.">
</dcc-trigger>
<dcc-trigger label="Brasil P"
action="noticia/brasil/politica"
parameter="Algo aconteceu no Brasil (política).">
</dcc-trigger>
<dcc-trigger label="Brasil E"
action="noticia/brasil/esporte"
parameter="Algo aconteceu no Brasil (esporte).">
</dcc-trigger>
<dcc-trigger label="Bahia"
action="noticia/bahia/esporte"
parameter="Algo aconteceu na Bahia (esporte).">
</dcc-trigger>
<dcc-lively-talk duration="0s"
character="doctor"
speech="...">
<subscribe-dcc message="noticia/+/politica"></subscribe>
</dcc-lively-talk>
<dcc-lively-talk duration="0s"
character="nurse"
speech="...">
<subscribe-dcc message="noticia/brasil/#"></subscribe>
</dcc-lively-talk>
<dcc-lively-talk duration="0s"
character="patient"
speech="...">
<subscribe-dcc message="#"></subscribe>
</dcc-lively-talk>
A segunda parte da prova será voltada a componentes em Java usando o catálogo de componentes fornecido. Este catálogo é o mesmo adotado em sala de aula.
A seguir são codificadas as interfaces e classes dos componentes que você precisará para responder as suas questões. No final do notebook, há duas questões para serem resolvidas.
In [1]:
public interface ITableProducer {
String[] requestAttributes();
String[][] requestInstances();
}
Out[1]:
In [2]:
public interface IDataSetProperties {
public String getDataSource();
public void setDataSource(String dataSource);
}
Out[2]:
In [3]:
public interface IDataSet extends IDataSetProperties, ITableProducer {
}
Out[3]:
In [4]:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class DataSetComponent implements IDataSet {
private String dataSource = null;
private String[] attributes = null;
private String[][] instances = null;
public DataSetComponent() {
/* nothing */
}
public String getDataSource() {
return dataSource;
}
public void setDataSource(String dataSource) {
this.dataSource = dataSource;
if (dataSource == null) {
attributes = null;
instances = null;
} else
readDS();
}
public String[] requestAttributes() {
return attributes;
}
public String[][] requestInstances() {
return instances;
}
private void readDS() {
ArrayList<String[]> instArray = new ArrayList<String[]>();
try {
BufferedReader file = new BufferedReader(new FileReader(dataSource));
String line = file.readLine();
if (line != null) {
attributes = line.split(",");
line = file.readLine();
while (line != null) {
String[] instLine = line.split(",");
instArray.add(instLine);
line = file.readLine();
}
instances = instArray.toArray(new String[0][]);
}
file.close();
} catch (IOException erro) {
erro.printStackTrace();
}
}
}
Out[4]:
In [5]:
try {
IDataSet ds = new DataSetComponent();
ds.setDataSource("../../../../src/db/datasets/zombie/complete/zombie-health-spreadsheet-ml-training.csv");
System.out.println("=== Attributes ===");
String attributes[] = ds.requestAttributes();
for (int a = 0; a < attributes.length-1; a++)
System.out.print(attributes[a] + ", ");
System.out.println(attributes[attributes.length-1]);
System.out.println();
System.out.println("=== Instances ===");
String instances[][] = ds.requestInstances();
for (int i = 0; i < instances.length; i++) {
for (int a = 0; a < attributes.length-1; a ++)
System.out.print(instances[i][a] + ", ");
System.out.println(instances[i][attributes.length-1]);
}
} catch (Exception e) {
e.printStackTrace();
}
Out[5]:
In [6]:
public interface ITableReceptacle {
public void connect(ITableProducer producer);
}
Out[6]:
In [7]:
public interface IConsoleUpdate {
public void update();
}
Out[7]:
In [8]:
public interface IConsole extends ITableReceptacle, IConsoleUpdate {
}
Out[8]:
In [9]:
public class ConsoleComponent implements IConsole {
private ITableProducer iProducer;
public void connect(ITableProducer producer) {
iProducer = producer;
}
public void update() {
if (iProducer != null) {
System.out.println("=== Attributes ===");
String attributes[] = iProducer.requestAttributes();
for (int a = 0; a < attributes.length-1; a++)
System.out.print(attributes[a] + ", ");
System.out.println(attributes[attributes.length-1]);
System.out.println();
System.out.println("=== Instances ===");
String instances[][] = iProducer.requestInstances();
for (int i = 0; i < instances.length; i++) {
for (int a = 0; a < attributes.length-1; a ++)
System.out.print(instances[i][a] + ", ");
System.out.println(instances[i][attributes.length-1]);
}
}
}
}
Out[9]:
In [10]:
try {
IDataSet dataset = new DataSetComponent();
dataset.setDataSource("../../../../src/db/datasets/zombie/complete/zombie-health-spreadsheet-ml-training.csv");
IConsole console = new ConsoleComponent();
console.connect(dataset);
console.update();
} catch (Exception e) {
e.printStackTrace();
}
Out[10]:
In [11]:
public interface IProjectionProperties {
String[] getAttributes();
void setAttributes(String attribute[]);
}
Out[11]:
In [12]:
public interface IProjection extends IProjectionProperties, ITableProducer, ITableReceptacle {
}
Out[12]:
In [13]:
public class ProjectionComponent implements IProjection {
private ITableProducer provider;
private String attributes[] = null;
public String[] getAttributes() {
return attributes;
}
public void setAttributes(String attributes[]) {
this.attributes = attributes;
}
public void connect(ITableProducer provider) {
this.provider = provider;
}
public String[] requestAttributes() {
return attributes;
}
public String[][] requestInstances() {
String[][] instances = null;
if (provider != null) {
String[][] allInstances = provider.requestInstances();
if (allInstances != null && attributes != null) {
instances = new String[allInstances.length][];
// busca a posicao dos atributos selecionados na tabela original
String[] allAttributes = provider.requestAttributes();
int attrPos[] = new int[attributes.length];
for (int as = 0; as < attributes.length; as++) {
int aa;
for (aa = 0; aa < allAttributes.length &&
!attributes[as].equalsIgnoreCase(allAttributes[aa]); aa++)
/* nothing */;
if (aa < allAttributes.length)
attrPos[as] = aa;
else
attrPos[as] = -1;
}
// filtra atributos selecionados
for (int i = 0; i < allInstances.length; i++) {
instances[i] = new String[attributes.length];
for (int as = 0; as < attributes.length; as++)
if (attrPos[as] > -1)
instances[i][as] = allInstances[i][attrPos[as]];
}
}
}
return instances;
}
}
Out[13]:
In [14]:
try {
IDataSet dataset = new DataSetComponent();
dataset.setDataSource("../../../../src/db/datasets/zombie/complete/zombie-health-spreadsheet-ml-training.csv");
IProjection projection = new ProjectionComponent();
projection.connect(dataset);
IConsole console = new ConsoleComponent();
console.connect(projection);
String[] attributes = {"name", "age"};
projection.setAttributes(attributes);
console.update();
} catch (Exception e) {
e.printStackTrace();
}
Out[14]:
In [15]:
public interface ISelectionProperties {
String getAttribute();
void setAttribute(String attributeA);
public String getOperator();
public void setOperator(String operator);
public String getValue();
public void setValue(String value);
boolean isNominalComparison();
void setNominalComparison(boolean nominalComparison);
}
Out[15]:
In [16]:
public interface ISelection extends ISelectionProperties, ITableProducer, ITableReceptacle {
}
Out[16]:
In [17]:
import java.util.ArrayList;
public class SelectionComponent implements ISelection {
private ITableProducer provider;
private String attribute = null,
operator = null,
value = null;
private boolean nominalComparison = true;
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public String getOperator() {
return operator;
}
public void setOperator(String operator) {
this.operator = operator;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public boolean isNominalComparison() {
return nominalComparison;
}
public void setNominalComparison(boolean nominalComparison) {
this.nominalComparison = nominalComparison;
}
public void connect(ITableProducer provider) {
this.provider = provider;
}
public String[] requestAttributes() {
return (provider == null) ? null : provider.requestAttributes();
}
public String[][] requestInstances() {
ArrayList<String[]> instances = null;
if (provider != null) {
String[][] allInstances = provider.requestInstances();
if (allInstances != null) {
// busca a posicao dos atributos selecionados na tabela original
String[] allAttributes = provider.requestAttributes();
int atrPos;
for (atrPos = 0; atrPos < allAttributes.length &&
!attribute.equalsIgnoreCase(allAttributes[atrPos]); atrPos++)
/* nothing */;
if (atrPos < allAttributes.length) {
instances = new ArrayList<String[]>();
for (String[] ai: allInstances) {
boolean match = false;
if (nominalComparison) {
switch (operator.charAt(0)) {
case '=': if (ai[atrPos].equalsIgnoreCase(value))
match = true;
break;
case '<': if (ai[atrPos].compareTo(value) < 0)
match = true;
break;
case '>': if (ai[atrPos].compareTo(value) > 0)
match = true;
break;
case '!': if (!ai[atrPos].equalsIgnoreCase(value))
match = true;
break;
}
} else {
switch (operator.charAt(0)) {
case '=': if (Double.parseDouble(ai[atrPos]) == Double.parseDouble(value))
match = true;
break;
case '<': if (Double.parseDouble(ai[atrPos]) < Double.parseDouble(value))
match = true;
break;
case '>': if (Double.parseDouble(ai[atrPos]) > Double.parseDouble(value))
match = true;
break;
case '!': if (Double.parseDouble(ai[atrPos]) != Double.parseDouble(value))
match = true;
break;
}
}
if (match)
instances.add(ai);
}
}
}
}
return (instances == null) ? null : instances.toArray(new String[1][]);
}
}
Out[17]:
In [18]:
try {
IDataSet dataset = new DataSetComponent();
dataset.setDataSource("../../../../src/db/datasets/zombie/complete/zombie-health-spreadsheet-ml-training.csv");
ISelection selection = new SelectionComponent();
selection.connect(dataset);
selection.setAttribute("diagnostic");
selection.setOperator("=");
selection.setValue("bacterial_infection");
IConsole console = new ConsoleComponent();
console.connect(selection);
console.update();
} catch (Exception e) {
e.printStackTrace();
}
Out[18]:
In [19]:
public interface IChartProperties {
String getTitle();
void setTitle(String title);
String getXTitle();
void setXTitle(String title);
String getYTitle();
void setYTitle(String title);
}
Out[19]:
In [20]:
public interface IRun {
public boolean start();
public boolean stop();
}
Out[20]:
In [21]:
public interface IChart extends ITableReceptacle, IRun, IChartProperties {
/* Component Interfaces Set */
}
Out[21]:
In [22]:
%classpath add jar ../../../../src/lib/xchart-3.5.2.jar
In [23]:
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.io.IOException;
import org.knowm.xchart.BubbleChart;
import org.knowm.xchart.BubbleChartBuilder;
import org.knowm.xchart.SwingWrapper;
import org.knowm.xchart.BitmapEncoder;
import org.knowm.xchart.BitmapEncoder.BitmapFormat;
import com.twosigma.beakerx.mimetype.MIMEContainer;
import java.io.File;
import java.nio.file.Files;
public class ChartBubbleComponent implements IChart {
private BubbleChart chart = null;
private String title = "Chart";
private String xTitle = "X",
yTitle = "Y";
private ITableProducer producer = null;
public void connect(ITableProducer producer) {
this.producer = producer;
}
public ChartBubbleComponent() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getXTitle() {
return xTitle;
}
public void setXTitle(String title) {
xTitle = title;
}
public String getYTitle() {
return title;
}
public void setYTitle(String title) {
yTitle = title;
}
public boolean start() {
boolean status = true;
chart = new BubbleChartBuilder().width(600).height(400).title(title).xAxisTitle(xTitle).yAxisTitle(yTitle).build();
try{
buildChart();
BitmapEncoder.saveBitmap(chart, "./chart", BitmapFormat.PNG);
File file = new File("chart.png");
byte[] data = Files.readAllBytes(file.toPath());
MIMEContainer image = new MIMEContainer(MIMEContainer.MIME.IMAGE_PNG, data);
display(image);
}catch(IOException ex){
status = false;
System.out.println (ex.toString());
}
return status;
}
public boolean stop() {
return true;
}
public double[] toDouble(String[][] instances, int column ) {
double[] numbers = new double[instances.length];
for (int i = 0; i < instances.length; i++)
numbers[i] = Double.parseDouble(instances[i][column]);
return numbers;
}
private void buildChart() {
if (chart != null && producer != null) {
String[][] instances = producer.requestInstances();
if (instances != null) {
double[] xData = toDouble(instances, 0),
yData = toDouble(instances, 1);
String[] categoryData = null;
if (instances[0].length > 2) {
categoryData = new String[instances.length];
for (int c = 0; c < instances.length; c++)
categoryData[c] = instances[c][2];
}
double[] bubbleData = null;
if (instances[0].length > 3)
bubbleData = toDouble(producer.requestInstances(), 3);
else {
bubbleData = new double[instances.length];
for (int i = 0; i < xData.length; i++)
bubbleData[i] = 10;
}
if (categoryData == null ||
xData.length != yData.length || yData.length != bubbleData.length ||
bubbleData.length != categoryData.length) {
chart.addSeries(" ", xData, yData, bubbleData);
} else {
Hashtable<String,String> hash = new Hashtable<String,String>();
int outer = 0;
int size = categoryData.length;
while (outer < size) {
if (hash.containsKey(categoryData[outer]))
outer++;
else {
hash.put(categoryData[outer],categoryData[outer]);
List<Double> xSub = new ArrayList<Double>(),
ySub = new ArrayList<Double>(),
bubbleSub = new ArrayList<Double>();
for (int inner = outer; inner < size; inner++)
if (categoryData[inner].equalsIgnoreCase(categoryData[outer])) {
xSub.add(xData[inner]);
ySub.add(yData[inner]);
bubbleSub.add(bubbleData[inner]);
}
chart.addSeries(categoryData[outer], xSub, ySub, bubbleSub);
outer++;
}
}
}
}
}
}
}
Out[23]:
In [24]:
IDataSet dataset = new DataSetComponent();
dataset.setDataSource("../../../../src/db/datasets/zombie/complete/zombie-health-spreadsheet-ml-training.csv");
IProjection projection = new ProjectionComponent();
projection.connect(dataset);
String attributes[] = {"days_recovery", "age"};
projection.setAttributes(attributes);
IChart chart = new ChartBubbleComponent();
chart.setTitle("Zombie Health");
chart.setXTitle("Days Recovery");
chart.setYTitle("Age");
chart.connect(projection);
return chart.start();
Out[24]:
In [25]:
IDataSet dataset = new DataSetComponent();
dataset.setDataSource("../../../../src/db/datasets/zombie/complete/zombie-health-spreadsheet-ml-training.csv");
ISelection selection = new SelectionComponent();
selection.connect(dataset);
selection.setAttribute("diagnostic");
selection.setOperator("=");
selection.setValue("bacterial_infection");
IProjection projection = new ProjectionComponent();
projection.connect(selection);
String attributes[] = {"days_recovery", "age"};
projection.setAttributes(attributes);
IChart chart = new ChartBubbleComponent();
chart.setTitle("Zombie Health");
chart.setXTitle("Days Recovery");
chart.setYTitle("Age");
chart.connect(projection);
return chart.start();
Out[25]:
In [26]:
public interface IStatisticsProperties {
int getSize();
double[] getValueSet();
void setValueSet(double[] valueSet);
double getValueSet(int index);
void setValueSet(int index, double value);
}
Out[26]:
In [27]:
/**
* Interface for a Statistics Class that registers a set of numbers
* and calculates the sum and average of these numbers.
*
* @author Andre Santanche
*/
public interface IStatisticsServices {
/**
* Inserts a value into the set.
* @param value the value to be inserted into the set
*/
public void insertValue(double value);
/**
* Calculates the sum of the values in the set. Returns zero if the set is empty.
* @return sum of the values in the set
*/
public double sum();
/**
* Calculates the average of the values in the set. Returns zero if the set is empty.
* @return average of the values in the set
*/
public double average();
}
Out[27]:
In [28]:
public interface IStatistics extends IStatisticsServices, IStatisticsProperties {
}
Out[28]:
In [29]:
import java.util.Vector;
/**
* Registers a set of numbers and calculates the sum and average of these numbers.
*
* @author Andre Santanche
*/
public class StatisticsComponent implements IStatistics {
private Vector<Double> valueSet;
/*
* Constructor
**************/
public StatisticsComponent() {
super();
valueSet = new Vector<Double>();
}
public StatisticsComponent(int capacity) {
super();
valueSet = new Vector<Double>(capacity);
}
/* Properties
************/
public int getSize() {
return valueSet.size();
}
public double[] getValueSet() {
int size = valueSet.size();
double result[] = new double[size];
for (int d = 0; d < size; d++)
result[d] = valueSet.get(d);
return result;
}
public void setValueSet(double[] valueSet) {
for (int d = 0; d < valueSet.length; d++)
this.valueSet.add(valueSet[d]);
}
public double getValueSet(int index) {
return (index < getSize()) ? valueSet.get(index) : 0;
}
public void setValueSet(int index, double value) {
int position = (index < getSize()) ? index : getSize();
if (position < getSize())
valueSet.set(index, value);
else
valueSet.add(value);
}
/*
* IStatisticsServices Interface
*******************************/
public void insertValue(double value) {
valueSet.add(value);
}
public double sum() {
double theSum = 0.0f;
for (double value : valueSet)
theSum += value;
return theSum;
}
public double average() {
double avg = 0;
if (valueSet.size() > 0)
avg = sum() / valueSet.size();
return avg;
}
}
Out[29]:
In [30]:
try {
IStatistics stat = new StatisticsComponent(3);
System.out.println("inserido valor: " + 50.0f);
stat.insertValue(50.0f);
System.out.println("inserido valor: " + 70.0f);
stat.insertValue(70.0f);
System.out.println("inserido valor: " + 30.0f);
stat.insertValue(30.0f);
System.out.println("-- somatorio: " + stat.sum());
System.out.println("-- media: " + stat.average());
System.out.println("-- tamanho: " + stat.getSize());
} catch (Exception e) {
e.printStackTrace();
}
Out[30]:
In [31]:
public interface IRun {
public void start();
}
Out[31]:
In [32]:
public interface IStatisticsReceptacle{
public void connect(IStatistics provider);
}
Out[32]:
In [33]:
public interface IClientProperties {
public int getSize();
public void setSize(int size);
}
Out[33]:
In [34]:
public interface IClient extends IStatisticsReceptacle, IClientProperties, IRun {
}
Out[34]:
In [35]:
public class ClientComponent implements IClient {
public final static int STANDARD_SIZE = 5;
private int size;
private int first, second;
private IStatistics provider = null;
/*
* Constructor
*************/
public ClientComponent() {
super();
size = STANDARD_SIZE;
first = 1;
second = 1;
}
/*
* Properties
*/
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
/*
* IStatisticsReceptacle Interface
**********************************/
public void connect(IStatistics provider)
{
this.provider = provider;
}
public int next() {
int returnNumber = first;
first = second;
second = returnNumber + first;
return returnNumber;
}
public void start()
{
for (int f = 1; f <= size; f++) {
int nextNumber = next();
System.out.println("produzido: " + nextNumber);
provider.insertValue(nextNumber);
}
System.out.println("-- somatorio: " + provider.sum());
System.out.println("-- media: " + provider.average());
}
}
Out[35]:
Tomando como base o Dataset dos Zumbis, instancie e conecte os componentes que você achar necessários para mostrar no console a média do tempo de recuperação (days_recovery
) dos zumbis.
In [36]:
public interface IConvert extends ITableReceptacle{
public double[] convert();
}
Out[36]:
In [37]:
public class ConvertComponent implements IConvert {
private ITableProducer provider;
private double[] vector;
public void connect(ITableProducer provider) {
this.provider = provider;
}
public double[] convert() {
if (provider != null) {
String instances[][] = provider.requestInstances();
vector = new double[instances.length];
for (int i = 0; i < instances.length; i++) {
vector[i] = Double.parseDouble(instances[i][0]);
}
}
return vector;
}
}
Out[37]:
In [38]:
try{
IDataSet dataset = new DataSetComponent();
dataset.setDataSource("../../../../src/db/datasets/zombie/complete/zombie-health-spreadsheet-ml-training.csv");
IProjection projection = new ProjectionComponent();
projection.connect(dataset);
String[] attributes = {"days_recovery"};
projection.setAttributes(attributes);
IConvert conversor = new ConvertComponent();
conversor.connect(projection);
double[] age = conversor.convert();
IStatistics stat = new StatisticsComponent();
stat.setValueSet(age);
System.out.println("Média do tempo de recuperação: " + stat.average());
}
catch (Exception e) {
e.printStackTrace();
}
Out[38]: