How to convert a Vector to a comma-delimited String - blackberry

I am using a vector in my BlackBerry app to hold email addresses, one string per address. When I populate an EditField, I get output as : [mahesh#gmail.com, ensisinfo15#gmail.com]
I need output as : mahesh#gmail.com, ensisinfo15#gmail.com
This is because I need to assign these output values as a To address for an email.
here selected is one vector.
first class
obj.call(selected);
These vector element assigned in another vector in second class named as selected2
second class call event in first class
public static BasicEditField toadd;
public void call(Vector selected2)
{
selected = new Vector();
selected.addElement(selected2);
for(int i=0;i<selected.size();i++)
{
toadd.setText((String) selected.elementAt(i).toString());
}
}

In the call() method you are expecting the selected vector to have two elements while in reality it has one. The only element in selected is the vector selected2. If you want to assign all the elements of selected2 to selected then you should loop through selected2 and put all of its elements in selected. So the start of your method should look like this:
public void call(Vector selected2)
{
Vector selected = new Vector();
for(int i = 0; i < selected2.size(); i++)
{
selected.addElement(selected2.elementAt(i));
And then the rest of the method will proceed normally.

Related

Ho to use a custom mapper with mapstruct with nested values and conditional values

I am trying to map one object to another using mapstrut and currently facing some challenges on how to use it for some cases.
public class TargetOrderDto {
String id;
String preferedItem;
List<Item> items;
String status;
Address address;
}
public class Item {
String id;
String name;
}
public abstract class TargetOrderMapper {
#Autowired
private StatusRepository statusRepository;
#Mappings({
#Mapping(target = "id", source = "reference"),
#Mapping(target = "preferedItem", source = ""), // Here I need to loop through these values checking for a single value with a specific tag
#Mapping(target = "items", source = "items"), // List of objects to another list of different data types.
#Mapping(target = "status", source = "remoteStatus") // may need to extract a value from a repository
})
abstract OrderDto toTargetOrderDto(RemoteOrder remoteOrder);
}
// Remote Data
public class RemoteOrder {
String reference;
List<Item> items;
String remoteStatus;
}
public class RemoteItem {
String id;
String flag;
String description;
}
These are the current scenarios that I have failed to get my head around (maybe I am mapping a complex object).
preferedItem :
for this, I need to loop though the items in the order and identify the item with a specific flag. (if it matches then I take that value else I use null)
items :
I need to convert this to a list of 2 different lists; List from List, all have different mapping rules of their own.
remoteStatus :
This one is abit more tricky, I need to extract the status from remoteOrder then lookit up in the db using the statusRepository for an alternate mapped value in db.
any help is highly appreciated.
You can't do business logic with MapStruct. So keep mappings simple and define your own methods were it comes to conditional mappings in list. Note: you can write your own method and MapStruct will select it. Also, from this own implementation you can refer to MapStruct methods again.
public abstract class TargetOrderMapper {
#Autowired
private StatusRepository statusRepository;
#Mappings({
#Mapping(target = "id", source = "reference"),
#Mapping(target = "preferedItem", source = ""), // Here I need to loop through these values checking for a single value with a specific tag
#Mapping(target = "items", source = "items"), // List of objects to another list of different data types.
#Mapping(target = "status", source = "remoteStatus") // may need to extract a value from a repository
})
abstract OrderDto toTargetOrderDto(RemoteOrder remoteOrder);
protected List<Item> toItemList(List<Item> items) {
// do what ever you want..
// and call toItem during iterating.
}
protected abstract Item toItem(Item item);
}
The same goes for status. I added a FAQ entry some time ago about list (mainly about updating, but I guess the same applies here).
About lookups, you can use #MappingContext to pass down a context that contains the logic to access a DB. See here

How to do group by key on custom logic in cloud data flow

I am trying to achieve the Groupby key based on custom object in cloud data flow pipe line.
public static void main(String[] args) {
Pipeline pipeline = Pipeline.create(PipelineOptionsFactory.create());
List<KV<Student,StudentValues>> studentList = new ArrayList<>();
studentList.add(KV.of(new Student("pawan", 10,"govt"),
new StudentValues("V1", 123,"govt")));
studentList.add(KV.of(new Student("pawan", 13223,"word"),
new StudentValues("V2", 456,"govt")));
PCollection<KV<Student,StudentValues>> pc =
pipeline.apply(Create.of(studentList));
PCollection<KV<Student, Iterable<StudentValues>>> groupedWords =
pc.apply(GroupByKey.<Student,StudentValues>create());
}
I just wanted to groupBy both the PCollection record based on the Student object.
#DefaultCoder(AvroCoder.class)
static class Student /*implements Serializable*/{
public Student(){}
public Student(String n, Integer i, String sc){
name = n;
id = i;
school = sc;
}
public String name;
public Integer id;
public String school;
#Override
public boolean equals(Object obj) {
System.out.println("obj = "+obj);
System.out.println("this = "+this);
Student stObj= (Student)obj;
if (stObj.Name== this.Name){
return true;
} else{
return false;
}
}
}
I have overridden the equals method of my custom class, but each time i am getting same instance of Student object to compare inside equals method.
Ideally it sholud compare first student key with second one.
Whats wrong i am doing here.
Why do you think you are doing anything wrong? The keys of each element are serialized (using the AvroCoder you specified) and the GroupByKey can group all of the elements with the same serialized representation together. After that it doesn't need to compare the students to make sure that the values with the same key have been grouped together.

Accord.NET Comparing two images to determine similarity

I would like your advice as to why the code might be becoming unresponsive and how to fix it.
I am using Accord.NET to compare images. The first stage of my project is to compare two images, an observed image and a model image, and determine how similar they are; the second, is to compare an observed image against my whole database to determine what the observed image most likely is based on how the models have been categorized. Right now I am focusing on the first. I initially tried using ExhaustiveTemplateMatching.ProcessImage() but it didn't fit my need. Now, I am using SURF. Here is my code as is:
public class ProcessImage
{
public static void Similarity(System.IO.Stream model, System.IO.Stream observed,
out float similPercent)
{
Bitmap bitModel = new Bitmap(model);
Bitmap bitObserved = new Bitmap(observed);
// For method Difference, see http://www.aforgenet.com/framework/docs/html/673023f7-799a-2ef6-7933-31ef09974dde.htm
// Inspiration for this process: https://www.youtube.com/watch?v=YHT46f2244E
// Greyscale class http://www.aforgenet.com/framework/docs/html/d7196dc6-8176-4344-a505-e7ade35c1741.htm
// Convert model and observed to greyscale
Grayscale filter = new Grayscale(0.2125, 0.7154, 0.0721);
// apply the filter to the model
Bitmap greyModel = filter.Apply(bitModel);
// Apply the filter to the observed image
Bitmap greyObserved = filter.Apply(bitObserved);
int modelPoints = 0, matchingPoints = 0;
/*
* This doesn't work. Images can have different sizes
// For an example, https://thecsharper.com/?p=94
// Match
var tm = new ExhaustiveTemplateMatching(similarityThreshold);
// Process the images
var results = tm.ProcessImage(greyModel, greyObserved);
*/
using (SpeededUpRobustFeaturesDetector detector = new SpeededUpRobustFeaturesDetector())
{
List<SpeededUpRobustFeaturePoint> surfModel = detector.ProcessImage(greyModel);
modelPoints = surfModel.Count();
List<SpeededUpRobustFeaturePoint> surfObserved = detector.ProcessImage(greyObserved);
KNearestNeighborMatching matcher = new KNearestNeighborMatching(5);
var results = matcher.Match(surfModel, surfObserved);
matchingPoints = results.Length;
}
// Determine if they represent the same points
// Obtain the pairs of associated points, we determine the homography matching all these pairs
// Compare the results, 0 indicates no match so return false
if (matchingPoints <= 0)
{
similPercent = 0.0f;
}
similPercent = (matchingPoints * 100) / modelPoints;
}
}
So far I get to obtain the list of points but then when matching the code seems to become unresponsive.
I am calling the above code from an ASP.NET web page after the user posts a bitmap. Here is the code if it may help:
public ActionResult Compare(int id)
{
ViewData["SampleID"] = id;
return View();
}
[HttpPost]
public ActionResult Compare(int id, HttpPostedFileBase uploadFile)
{
Sample model = _db.Sample_Read(id);
System.IO.Stream modelStream = null;
float result = 0;
_db.Sample_Stream(model.FileId, out modelStream);
ImgProc.ProcessImage.Similarity(modelStream, uploadFile.InputStream,
out result);
ViewData["SampleID"] = id;
ViewData["match"] = result;
return View();
}
The page itself is rather simple, a hidden field, an file type input and a submit.
Problem was my PC. After some time processing the calculation finishes.
Thanks,
For KNearestNeighborMatching to decide, it is necessary to put
Accord.Imaging and Accord.Vision.

Field and values connection in Storm

I have a fundamental question in storm. I can clearly understand some basic things. For example i have a main class with this code inside:
...
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout(SENTENCE_SPOUT_ID, new SentenceSpout());
builder.setBolt(SPLIT_BOLT_ID, new SplitSentenceBolt()).shuffleGrouping(SENTENCE_SPOUT_ID);
builder.setBolt(COUNT_BOLT_ID, new WordCountBolt(), 3).fieldsGrouping(SPLIT_BOLT_ID, new Fields("word"));
builder.setBolt(REPORT_BOLT_ID, new ReportBolt()).globalGrouping(COUNT_BOLT_ID);
...
and i understand that 1st element(ex. "SENTENCE_SPOUT_ID") is the id of the bolt/spout in order to show the connection between 2 of them. The 2nd element(ex.new SentenceSpout()) specifies the spout or bold that we set in our topology. 3rd element marks the num of tasks that we need for this certain bolt spout.
Then we use .fieldsGrouping or .shuffleGrouping etc to specify the type of grouping and then between the parenthesis the 1st element is the connection with the bolt/spout that takes the input and the 2nd (ex. new Fields("word")) determines the fields that we will group by.
Inside the code of one of the bolts:
public class SplitSentenceBolt extends BaseRichBolt{
private OutputCollector collector;
public void prepare(Map config, TopologyContext context, OutputCollector collector) {
this.collector = collector;
}
public void execute(Tuple tuple) {
this.collector.emit(a, new Values(word, time, name));
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word"));
}
}
At this.collector.emit(a, new Values(word, time, name)); a is the stream_ID and values(...) are the elements of the tuple.
At declarer.declare(new Fields("word")); word must be one of the previous values. Am i right to all the previous?
So my question is: that in declarer.declare(new Fields("word")); word must be the same with word in this.collector.emit(a, new Values(word, time, name)); and the same with the word in builder.setBolt(COUNT_BOLT_ID, new WordCountBolt(), 3).fieldsGrouping(SPLIT_BOLT_ID, new Fields("word")); ????
The number and order of the fields you declare in declareOutputFields should match the fields you emit.
Two changes I'd recommend:
For now use the default stream by omitting the first parameter: collector.emit(new Values(word, time, name));
Make sure you declare the same number of fields: declarer.declare(new Fields("word", "time", "name"));

vaadin : multiple links in one field on the table

I want to ask about the UI of the vaadin, which is Table.
If I used this component, then I have to create a field using this command:
userTable.addContainerProperty("Status", String.class, "Active");
If I want to create link into this field, then I have to do like this:
userTable.addContainerProperty("Action", Link.class, new Link("Remove", new ExternalResource("#")));
My question is, the example above, only display single link in one field which is REMOVE Link. I want to create two links in one field of that table. For example link for EDIT and DELETE below the "Action" field, how can I do that?
Use a generated column to add the components to each row. Create an Horizontal Layout and two Buttons as the content.
class ValueColumnGenerator implements Table.ColumnGenerator {
String format; /* Format string for the Double values. */
/**
* Creates double value column formatter with the given
* format string.
*/
public ValueColumnGenerator(String format) {
this.format = format;
}
/**
* Generates the cell containing the Double value.
* The column is irrelevant in this use case.
*/
public Component generateCell(Table source, Object itemId,
Object columnId) {
// Get the object stored in the cell as a property
Property prop =
source.getItem(itemId).getItemProperty(columnId);
if (prop.getType().equals(Double.class)) {
HorizontalLayout hbox = new HorizontalLayout()
hbox.addComponent(new Button("Status"))
hbox.addComponent(new Button("Remove"))
return hbox;
}
return null;
}
}
See Section 5.14.5 of the Book of Vaadin for more info:
https://vaadin.com/book/-/page/components.table.html
You can add this buttons to HorizontalLayout or any other container component. Then add this layout to the container property in your table.

Resources