How to add tags to a parsed tree that has no tag? - stanford-nlp

For example, the parsing tree from Stanford Sentiment Treebank
"(2 (2 (2 near) (2 (2 the) (2 end))) (3 (3 (2 takes) (2 (2 on) (2 (2 a) (2 (2 whole) (2 (2 other) (2 meaning)))))) (2 .)))",
where the number is the sentiment label of each node.
I want to add POS tagging information to each node. Such as:
"(NP (ADJP (IN near)) (DT the) (NN end)) "
I have tried to directly parse the sentence, but the resulted tree is different from that in the Sentiment Treebank (may be because of the parsing version or parameters, I have tried to contact to the author but there is no response).
How can I obtain the tagging information?

I think the code in edu.stanford.nlp.sentiment.BuildBinarizedDataset should be helpful. The main() method steps through how these binary trees can be created in Java code.
Some key lines to look out for in the code:
LexicalizedParser parser = LexicalizedParser.loadModel(parserModel);
TreeBinarizer binarizer = TreeBinarizer.simpleTreeBinarizer(parser.getTLPParams().headFinder(), parser.treebankLanguagePack());
...
Tree tree = parser.apply(tokens);
Tree binarized = binarizer.transformTree(tree);
You can access the node tag information from the Tree object. You should look at the javadoc for edu.stanford.nlp.trees.Tree to see how to access this information.
Also in this answer I have some code that shows accessing a Tree:
How to get NN andNNS from a text?
You want to look at the label() of each tree and subtree to get the tag for a node.
Here is the reference on GitHub to BuildBinarizedDataset.java:
https://github.com/stanfordnlp/CoreNLP/blob/master/src/edu/stanford/nlp/sentiment/BuildBinarizedDataset.java
Please let me know if anything is unclear about this and I can provide further assistance!

First, you need to download the Stanford Parser
Set up
private LexicalizedParser parser;
private TreeBinarizer binarizer;
private CollapseUnaryTransformer transformer;
parser = LexicalizedParser.loadModel(PCFG_PATH);
binarizer = TreeBinarizer.simpleTreeBinarizer(
parser.getTLPParams().headFinder(), parser.treebankLanguagePack());
transformer = new CollapseUnaryTransformer();
Parse
Tree tree = parser.apply(tokens);
Access POSTAG
public String[] constTreePOSTAG(Tree tree) {
Tree binarized = binarizer.transformTree(tree);
Tree collapsedUnary = transformer.transformTree(binarized);
Trees.convertToCoreLabels(collapsedUnary);
collapsedUnary.indexSpans();
List<Tree> leaves = collapsedUnary.getLeaves();
int size = collapsedUnary.size() - leaves.size();
String[] tags = new String[size];
HashMap<Integer, Integer> index = new HashMap<Integer, Integer>();
int idx = leaves.size();
int leafIdx = 0;
for (Tree leaf : leaves) {
Tree cur = leaf.parent(collapsedUnary); // go to preterminal
int curIdx = leafIdx++;
boolean done = false;
while (!done) {
Tree parent = cur.parent(collapsedUnary);
if (parent == null) {
tags[curIdx] = cur.label().toString();
break;
}
int parentIdx;
int parentNumber = parent.nodeNumber(collapsedUnary);
if (!index.containsKey(parentNumber)) {
parentIdx = idx++;
index.put(parentNumber, parentIdx);
} else {
parentIdx = index.get(parentNumber);
done = true;
}
tags[curIdx] = parent.label().toString();
cur = parent;
curIdx = parentIdx;
}
}
return tags;
}
Here is the full source code ConstituencyParse.java that run:
Use param:
java ConstituencyParse -tokpath outputtoken.toks -parentpath outputparent.txt -tagpath outputag.txt < input_sentence_in_text_file_one_sent_per_line.txt
(Note: the source code is adapt from treelstm repo, you also need to replace preprocess-sst.py to call ConstituencyParse.java file below)
import edu.stanford.nlp.process.WordTokenFactory;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.ling.Word;
import edu.stanford.nlp.ling.CoreLabel;
import edu.stanford.nlp.ling.TaggedWord;
import edu.stanford.nlp.process.PTBTokenizer;
import edu.stanford.nlp.util.StringUtils;
import edu.stanford.nlp.parser.lexparser.LexicalizedParser;
import edu.stanford.nlp.parser.lexparser.TreeBinarizer;
import edu.stanford.nlp.tagger.maxent.MaxentTagger;
import edu.stanford.nlp.trees.GrammaticalStructure;
import edu.stanford.nlp.trees.GrammaticalStructureFactory;
import edu.stanford.nlp.trees.PennTreebankLanguagePack;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.Trees;
import edu.stanford.nlp.trees.TreebankLanguagePack;
import edu.stanford.nlp.trees.TypedDependency;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.StringReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.HashMap;
import java.util.Properties;
import java.util.Scanner;
public class ConstituencyParse {
private boolean tokenize;
private BufferedWriter tokWriter, parentWriter, tagWriter;
private LexicalizedParser parser;
private TreeBinarizer binarizer;
private CollapseUnaryTransformer transformer;
private GrammaticalStructureFactory gsf;
private static final String PCFG_PATH = "edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz";
public ConstituencyParse(String tokPath, String parentPath, String tagPath, boolean tokenize) throws IOException {
this.tokenize = tokenize;
if (tokPath != null) {
tokWriter = new BufferedWriter(new FileWriter(tokPath));
}
parentWriter = new BufferedWriter(new FileWriter(parentPath));
tagWriter = new BufferedWriter(new FileWriter(tagPath));
parser = LexicalizedParser.loadModel(PCFG_PATH);
binarizer = TreeBinarizer.simpleTreeBinarizer(
parser.getTLPParams().headFinder(), parser.treebankLanguagePack());
transformer = new CollapseUnaryTransformer();
// set up to produce dependency representations from constituency trees
TreebankLanguagePack tlp = new PennTreebankLanguagePack();
gsf = tlp.grammaticalStructureFactory();
}
public List<HasWord> sentenceToTokens(String line) {
List<HasWord> tokens = new ArrayList<>();
if (tokenize) {
PTBTokenizer<Word> tokenizer = new PTBTokenizer(new StringReader(line), new WordTokenFactory(), "");
for (Word label; tokenizer.hasNext(); ) {
tokens.add(tokenizer.next());
}
} else {
for (String word : line.split(" ")) {
tokens.add(new Word(word));
}
}
return tokens;
}
public Tree parse(List<HasWord> tokens) {
Tree tree = parser.apply(tokens);
return tree;
}
public String[] constTreePOSTAG(Tree tree) {
Tree binarized = binarizer.transformTree(tree);
Tree collapsedUnary = transformer.transformTree(binarized);
Trees.convertToCoreLabels(collapsedUnary);
collapsedUnary.indexSpans();
List<Tree> leaves = collapsedUnary.getLeaves();
int size = collapsedUnary.size() - leaves.size();
String[] tags = new String[size];
HashMap<Integer, Integer> index = new HashMap<Integer, Integer>();
int idx = leaves.size();
int leafIdx = 0;
for (Tree leaf : leaves) {
Tree cur = leaf.parent(collapsedUnary); // go to preterminal
int curIdx = leafIdx++;
boolean done = false;
while (!done) {
Tree parent = cur.parent(collapsedUnary);
if (parent == null) {
tags[curIdx] = cur.label().toString();
break;
}
int parentIdx;
int parentNumber = parent.nodeNumber(collapsedUnary);
if (!index.containsKey(parentNumber)) {
parentIdx = idx++;
index.put(parentNumber, parentIdx);
} else {
parentIdx = index.get(parentNumber);
done = true;
}
tags[curIdx] = parent.label().toString();
cur = parent;
curIdx = parentIdx;
}
}
return tags;
}
public int[] constTreeParents(Tree tree) {
Tree binarized = binarizer.transformTree(tree);
Tree collapsedUnary = transformer.transformTree(binarized);
Trees.convertToCoreLabels(collapsedUnary);
collapsedUnary.indexSpans();
List<Tree> leaves = collapsedUnary.getLeaves();
int size = collapsedUnary.size() - leaves.size();
int[] parents = new int[size];
HashMap<Integer, Integer> index = new HashMap<Integer, Integer>();
int idx = leaves.size();
int leafIdx = 0;
for (Tree leaf : leaves) {
Tree cur = leaf.parent(collapsedUnary); // go to preterminal
int curIdx = leafIdx++;
boolean done = false;
while (!done) {
Tree parent = cur.parent(collapsedUnary);
if (parent == null) {
parents[curIdx] = 0;
break;
}
int parentIdx;
int parentNumber = parent.nodeNumber(collapsedUnary);
if (!index.containsKey(parentNumber)) {
parentIdx = idx++;
index.put(parentNumber, parentIdx);
} else {
parentIdx = index.get(parentNumber);
done = true;
}
parents[curIdx] = parentIdx + 1;
cur = parent;
curIdx = parentIdx;
}
}
return parents;
}
// convert constituency parse to a dependency representation and return the
// parent pointer representation of the tree
public int[] depTreeParents(Tree tree, List<HasWord> tokens) {
GrammaticalStructure gs = gsf.newGrammaticalStructure(tree);
Collection<TypedDependency> tdl = gs.typedDependencies();
int len = tokens.size();
int[] parents = new int[len];
for (int i = 0; i < len; i++) {
// if a node has a parent of -1 at the end of parsing, then the node
// has no parent.
parents[i] = -1;
}
for (TypedDependency td : tdl) {
// let root have index 0
int child = td.dep().index();
int parent = td.gov().index();
parents[child - 1] = parent;
}
return parents;
}
public void printTokens(List<HasWord> tokens) throws IOException {
int len = tokens.size();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len - 1; i++) {
if (tokenize) {
sb.append(PTBTokenizer.ptbToken2Text(tokens.get(i).word()));
} else {
sb.append(tokens.get(i).word());
}
sb.append(' ');
}
if (tokenize) {
sb.append(PTBTokenizer.ptbToken2Text(tokens.get(len - 1).word()));
} else {
sb.append(tokens.get(len - 1).word());
}
sb.append('\n');
tokWriter.write(sb.toString());
}
public void printParents(int[] parents) throws IOException {
StringBuilder sb = new StringBuilder();
int size = parents.length;
for (int i = 0; i < size - 1; i++) {
sb.append(parents[i]);
sb.append(' ');
}
sb.append(parents[size - 1]);
sb.append('\n');
parentWriter.write(sb.toString());
}
public void printTags(String[] tags) throws IOException {
StringBuilder sb = new StringBuilder();
int size = tags.length;
for (int i = 0; i < size - 1; i++) {
sb.append(tags[i]);
sb.append(' ');
}
sb.append(tags[size - 1]);
sb.append('\n');
tagWriter.write(sb.toString().toLowerCase());
}
public void close() throws IOException {
if (tokWriter != null) tokWriter.close();
parentWriter.close();
tagWriter.close();
}
public static void main(String[] args) throws Exception {
String TAGGER_MODEL = "stanford-tagger/models/english-left3words-distsim.tagger";
Properties props = StringUtils.argsToProperties(args);
if (!props.containsKey("parentpath")) {
System.err.println(
"usage: java ConstituencyParse -deps - -tokenize - -tokpath <tokpath> -parentpath <parentpath>");
System.exit(1);
}
// whether to tokenize input sentences
boolean tokenize = false;
if (props.containsKey("tokenize")) {
tokenize = true;
}
// whether to produce dependency trees from the constituency parse
boolean deps = false;
if (props.containsKey("deps")) {
deps = true;
}
String tokPath = props.containsKey("tokpath") ? props.getProperty("tokpath") : null;
String parentPath = props.getProperty("parentpath");
String tagPath = props.getProperty("tagpath");
ConstituencyParse processor = new ConstituencyParse(tokPath, parentPath, tagPath, tokenize);
Scanner stdin = new Scanner(System.in);
int count = 0;
long start = System.currentTimeMillis();
while (stdin.hasNextLine() && count < 2) {
String line = stdin.nextLine();
List<HasWord> tokens = processor.sentenceToTokens(line);
//end tagger
Tree parse = processor.parse(tokens);
// produce parent pointer representation
int[] parents = deps ? processor.depTreeParents(parse, tokens)
: processor.constTreeParents(parse);
String[] tags = processor.constTreePOSTAG(parse);
// print
if (tokPath != null) {
processor.printTokens(tokens);
}
processor.printParents(parents);
processor.printTags(tags);
// print tag
StringBuilder sb = new StringBuilder();
int size = tags.length;
for (int i = 0; i < size - 1; i++) {
sb.append(tags[i]);
sb.append(' ');
}
sb.append(tags[size - 1]);
sb.append('\n');
count++;
if (count % 100 == 0) {
double elapsed = (System.currentTimeMillis() - start) / 1000.0;
System.err.printf("Parsed %d lines (%.2fs)\n", count, elapsed);
}
}
long totalTimeMillis = System.currentTimeMillis() - start;
System.err.printf("Done: %d lines in %.2fs (%.1fms per line)\n",
count, totalTimeMillis / 100.0, totalTimeMillis / (double) count);
processor.close();
}
}

Related

Is it possible to convert an AutoCAD solid3d entity to an Eyeshot brep entity and add it to the Eyeshot model viewport?

I am drawing a Cad Solid3d Entity by changing it to Brep and approaching the face,
but the shape is different. what's wrong
Or is there a way to directly import Autocad solid3d entity into the Eyeshot Model Viewport without redrawing with geometry information?
Below is my code
public void Main()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
CivilDocument cdoc = CivilApplication.ActiveDocument;
using (doc.LockDocument())
{
using (Transaction tr = db.TransactionManager.StartTransaction())
{
List<GBrep.Face> gFaces = new List<GBrep.Face>();
ObjectId solid3dId = EditorInputUtil.GetEntityId(ed, typeof(Solid3d));
GBRepView gBRepView = new GBRepView();
using (Solid3d solid = tr.GetObject(solid3dId, OpenMode.ForWrite) as Solid3d)
using (Brep brep = new Brep(solid))
{
foreach (Face face in brep.Faces)
{
Autodesk.AutoCAD.Geometry.NurbSurface nurbSurface = face.GetSurfaceAsNurb();
int uDegree = nurbSurface.DegreeInU;
int vDegree = nurbSurface.DegreeInV;
KnotCollection uKnotVector = nurbSurface.UKnots;
KnotCollection vKnotVector = nurbSurface.VKnots;
double[] uKnots = ConvertKnotVector(uKnotVector);
double[] vKnots = ConvertKnotVector(vKnotVector);
Point3dCollection p3ts = nurbSurface.ControlPoints;
Point4D[,] controlPoints = ConvertControlPoints(p3ts, nurbSurface.NumControlPointsInU, nurbSurface.NumControlPointsInV);
GSurface gSurface = new GSurface(uDegree, uKnots, vDegree, vKnots, controlPoints);
gBRepView.GetModel.Entities.Add(new devDept.Eyeshot.Entities.Surface(gSurface));
}
}
gBRepView.ShowDialog();
}
}
}
private Point4D[,] ConvertControlPoints(Point3dCollection point3ds, int uNums, int vNums)
{
Point4D[,] controlPoints = new Point4D[uNums, vNums];
int count = 0;
for (int i = 0; i < uNums; i++)
{
for (int j = 0; j < vNums; j++)
{
Point3d cadPoint = point3ds[count];
controlPoints[i, j] = new Point4D(cadPoint.X, cadPoint.Y, cadPoint.Z);
count++;
}
}
return controlPoints;
}

how to print image to thermal printer in kotlin

i already able to print text using kotlin to thermal printer, but im still dont know how to print image to thermal printer in kotlin. please give me sample printing image to thermal printer in kotlin.i already search for the topics, but it written in java, i doesnt know java very much thanks for the help
private fun p1() {
val namaToko = "Rose Medical"
val alamatToko = "Pramuka raya no.1 Jakarta Timur"
val telp = "021-85901642"
val enter = "\n"
val strip = "-"
val rp ="Rp."
val ex = " X "
val textTotal = "Total Rp:"
val ppnTv = "PPN :Rp."
val chargeTv ="Charge :Rp."
val totalTv = "Total Belanja :Rp."
val scope = CoroutineScope(Dispatchers.IO)
scope.launch {
// chunks1
try{
writeWithFormat(namaToko.toByteArray(),Formatter().get(),Formatter.centerAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(alamatToko.toByteArray(),Formatter().get(),Formatter.centerAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(telp.toByteArray(),Formatter().get(),Formatter.centerAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
}catch (e: Exception) {
Log.e("PrintActivity", "Exe ", e)
}
// chunks2
for(pointer in salesBody.indices){
try {
val merk = salesBody[pointer].merk
writeWithFormat(merk!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(strip.toByteArray(),Formatter().get(),Formatter.leftAlign())
val barang = salesBody[pointer].namaBrg
writeWithFormat(barang!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
val varian = salesBody[pointer].varian
writeWithFormat(varian!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(rp.toByteArray(),Formatter().get(),Formatter.leftAlign())
val harga = ValidNumber().deciformat(salesBody[pointer].hargaJual.toString())
writeWithFormat(harga.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(ex.toByteArray(),Formatter().get(),Formatter.leftAlign())
val jumlah = ValidNumber().deciformat(salesBody[pointer].qty.toString())
writeWithFormat(jumlah.toByteArray(),Formatter().get(),Formatter.leftAlign())
val satuan = salesBody[pointer].unit
writeWithFormat(satuan!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(textTotal.toByteArray(),Formatter().get(),Formatter.rightAlign())
val total = ValidNumber().deciformat(salesBody[pointer].total.toString())
writeWithFormat(total.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
}catch (e: Exception) {
Log.e("PrintActivity", "Exe ", e)
}
}
// chunks3
try{
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
val tanggal = salesHeader[0].tanggal
writeWithFormat(tanggal!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(strip.toByteArray(),Formatter().get(),Formatter.leftAlign())
val jam = salesHeader[0].jam
writeWithFormat(jam!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(strip.toByteArray(),Formatter().get(),Formatter.leftAlign())
val idTag= salesHeader[0].idTag
writeWithFormat(idTag!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
val payment= salesHeader[0].payment
writeWithFormat(payment!!.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.leftAlign())
writeWithFormat(ppnTv.toByteArray(),Formatter().get(),Formatter.rightAlign())
val ppnValue = ValidNumber().deciformat(salesHeader[0].ppn.toString())
writeWithFormat(ppnValue.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(chargeTv.toByteArray(),Formatter().get(),Formatter.rightAlign())
val chargeValue = ValidNumber().deciformat(salesHeader[0].charge.toString())
writeWithFormat(chargeValue.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(totalTv.toByteArray(),Formatter().get(),Formatter.rightAlign())
var totalValue = ValidNumber().deciformat(salesHeader[0].allTotal.toString())
writeWithFormat(totalValue.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
writeWithFormat(enter.toByteArray(),Formatter().get(),Formatter.rightAlign())
}catch (e: Exception) {
Log.e("PrintActivity", "Exe ", e)
}
}
}
//print code
class Formatter {
/** The format that is being build on */
private val mFormat: ByteArray
init {
// Default:
mFormat = byteArrayOf(27, 33, 0)
}
/**
* Method to get the Build result
*
* #return the format
*/
fun get(): ByteArray {
return mFormat
}
fun bold(): Formatter {
// Apply bold:
mFormat[2] = (0x8 or mFormat[2].toInt()).toByte()
return this
}
fun small(): Formatter {
mFormat[2] = (0x1 or mFormat[2].toInt()).toByte()
return this
}
fun height(): Formatter {
mFormat[2] = (0x10 or mFormat[2].toInt()).toByte()
return this
}
fun width(): Formatter {
mFormat[2] = (0x20 or mFormat[2].toInt()).toByte()
return this
}
fun underlined(): Formatter {
mFormat[2] = (0x80 or mFormat[2].toInt()).toByte()
return this
}
companion object {
fun rightAlign(): ByteArray {
return byteArrayOf(0x1B, 'a'.code.toByte(), 0x02)
}
fun leftAlign(): ByteArray {
return byteArrayOf(0x1B, 'a'.code.toByte(), 0x00)
}
fun centerAlign(): ByteArray {
return byteArrayOf(0x1B, 'a'.code.toByte(), 0x01)
}
}
}//last
fun writeWithFormat(buffer: ByteArray, pFormat: ByteArray?, pAlignment: ByteArray?): Boolean {
val mmOutStream: OutputStream = mBluetoothSocket.outputStream
return try {
// Notify printer it should be printed with given alignment:
mmOutStream.write(pAlignment)
// Notify printer it should be printed in the given format:
mmOutStream.write(pFormat)
// Write the actual data:
mmOutStream.write(buffer, 0, buffer.size)
// Share the sent message back to the UI Activity
//App.getInstance().getHandler().obtainMessage(MESSAGE_WRITE, buffer.size, -1, buffer).sendToTarget()
true
} catch (e: IOException) {
Log.e(TAG, "Exception during write", e)
false
}
}
//print code close
Using Thermal Printer repo references, I managed to print image to Bluetooth thermal printer. Make sure to use a proper black and white image to print.
Here is the piece of code I used to make a java class
--BitmapHelper.java.
public class BitmapHelper {
private static String[] binaryArray = { "0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111" };
public static byte[] decodeBitmap(Bitmap bmp){
//Bitmap bmp = Bitmap.createScaledBitmap(bitmap, 50, 50, false);
int maxWidth = 350;
int bmpWidth = bmp.getWidth();
int bmpHeight = bmp.getHeight();
if(bmpWidth > maxWidth){
float aspectRatio = bmp.getWidth() /
(float) bmp.getHeight();
bmpWidth = maxWidth;
bmpHeight = Math.round(bmpWidth / aspectRatio);
bmp = Bitmap.createScaledBitmap(bmp, bmpWidth, bmpHeight, false);
}
List<String> list = new ArrayList<>(); //binaryString list
StringBuffer sb;
int zeroCount = bmpWidth % 8;
StringBuilder zeroStr = new StringBuilder();
if (zeroCount > 0) {
for (int i = 0; i < (8 - zeroCount); i++) {
zeroStr.append("0");
}
}
for (int i = 0; i < bmpHeight; i++) {
sb = new StringBuffer();
for (int j = 0; j < bmpWidth; j++) {
int color = bmp.getPixel(j, i);
int r = (color >> 16) & 0xff;
int g = (color >> 8) & 0xff;
int b = color & 0xff;
// if color close to white,bit='0', else bit='1'
if (r > 160 && g > 160 && b > 160)
sb.append("0");
else
sb.append("1");
}
if (zeroCount > 0) {
sb.append(zeroStr);
}
list.add(sb.toString());
}
List<String> bmpHexList = binaryListToHexStringList(list);
String commandHexString = "1D763000";
String widthHexString = Integer
.toHexString(bmpWidth % 8 == 0 ? bmpWidth / 8
: (bmpWidth / 8 + 1));
if (widthHexString.length() > 2) {
Log.e("decodeBitmap error", " width is too large");
return null;
} else if (widthHexString.length() == 1) {
widthHexString = "0" + widthHexString;
}
widthHexString = widthHexString + "00";
String heightHexString = Integer.toHexString(bmpHeight);
if (heightHexString.length() > 2) {
Log.e("decodeBitmap error", " height is too large");
return null;
} else if (heightHexString.length() == 1) {
heightHexString = "0" + heightHexString;
}
heightHexString = heightHexString + "00";
List<String> commandList = new ArrayList<>();
commandList.add(commandHexString+widthHexString+heightHexString);
commandList.addAll(bmpHexList);
return hexList2Byte(commandList);
}
private static List<String> binaryListToHexStringList(List<String> list) {
List<String> hexList = new ArrayList<String>();
for (String binaryStr : list) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < binaryStr.length(); i += 8) {
String str = binaryStr.substring(i, i + 8);
String hexString = myBinaryStrToHexString(str);
sb.append(hexString);
}
hexList.add(sb.toString());
}
return hexList;
}
private static String myBinaryStrToHexString(String binaryStr) {
StringBuilder hex = new StringBuilder();
String f4 = binaryStr.substring(0, 4);
String b4 = binaryStr.substring(4, 8);
String hexStr = "0123456789ABCDEF";
for (int i = 0; i < binaryArray.length; i++) {
if (f4.equals(binaryArray[i]))
hex.append(hexStr.substring(i, i + 1));
}
for (int i = 0; i < binaryArray.length; i++) {
if (b4.equals(binaryArray[i]))
hex.append(hexStr.substring(i, i + 1));
}
return hex.toString();
}
private static byte[] hexList2Byte(List<String> list) {
List<byte[]> commandList = new ArrayList<byte[]>();
for (String hexStr : list) {
commandList.add(hexStringToBytes(hexStr));
}
return sysCopy(commandList);
}
private static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte[] sysCopy(List<byte[]> srcArrays) {
int len = 0;
for (byte[] srcArray : srcArrays) {
len += srcArray.length;
}
byte[] destArray = new byte[len];
int destLen = 0;
for (byte[] srcArray : srcArrays) {
System.arraycopy(srcArray, 0, destArray, destLen, srcArray.length);
destLen += srcArray.length;
}
return destArray;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}
Then I use it in the print activity:
private fun p2(){
val convertBmp : Bitmap
convertBmp = BitmapFactory.decodeResource(getResources(),com.example.ronibluetooth.R.drawable.poly)
val decodeBmp = BitmapHelper.decodeBitmap(convertBmp)
val scope = CoroutineScope(Dispatchers.IO)
scope.launch {
try {
val os =mBluetoothSocket.outputStream
os.write(decodeBmp,0,decodeBmp.size)
}
catch (e: Exception) {
Log.e("PrintActivity", "Exe ", e)
}
}
}
image to print
result print

How to arrange array of objects with same property value?

I have an person model with two property like this:
int id;
String name;
and some object with this data:
person0 = {1,"James"};
person1 = {2,"James"};
person2 = {3,"James"};
person3 = {4,"Barbara"};
person4 = {5,"Barbara"};
person5 = {6,"Ramses"};
and array contain objects:
firstArray = [person0, person1, person2, person3, person4, person5];
Therefore how can have this array:
secondArray = [
[person0, person1, person2],
[person3, person4],
[person5]
]
Thank you.
If language does not matter.
map = new Map();
for (persona of personas) {
name = persona.name;
arrayForName = map.get(name);
if (arrayForName == null) {
arrayForName = [];
map.put(name, arrayForName);
}
arrayForName.put(persona)
}
The idea is to have a map (which is a collection key->value).
The value of the map should in turn be an array.
To add elements efficiently, you iterate only once through the data, and add arrays each time a new key is discovered (i.e. the name).
In Java it would be something like:
Map<String, List<Persona>> map = new HashMap<>();
for (Persona persona : personas) {
String name = persona.getName();
List<Persona> listForName = map.get(name);
if (listForName == null) {
listForName = new ArrayList<Persona>();
map.put(name, listForName);
}
listForName.add(persona)
}
Try this code in Java Android:
ArrayList<ArrayList<Person>> secondArr = new ArrayList<>();
ArrayList<Course> tempArr = new ArrayList<>();
for (int i = 0; i < firstArr.size(); i++) {
if ((i + 1) >= firstArr.size()) {
tempArr.add(firstArr.get(i));
secondArr.add(tempArr);
} else {
if (firstArr.get(i).name .equals( firstArr.get(i + 1).name) ) {
tempArr.add(firstArr.get(i));
} else {
tempArr.add(firstArr.get(i));
secondArr.add(tempArr);
tempArr = new ArrayList<>();
}
}
}
Finally secondArr prepared.
And if list not sorted we can use code like this:
for (int i = 0; i <firstArr.size() ; i++) {
boolean isAdd = false;
for (int j = 0; j < secondArr.size() ; j++) {
if (secondArr.get(j).get(0).getName().equals(firstArr.get(i).getName())){
secondArr.get(j).add(firstArr.get(i));
isAdd =true;
break;
}
}
if (!isAdd){
ArrayList<Person> arrayList = new ArrayList<>();
arrayList.add(firstArr.get(i));
secondArr.add(arrayList);
}
}

Best way to handle awt.Image buffering in JavaFX

I have a class that takes a String parameter and performs a google search, then it gets the ten images and puts them in an array, that is then handled by another method in the same class. Using Javafx.scene.image would probably allow me to implement the buffering progress easily, but there is a bug with JavaFX Image, that misinterprets the color encoding of normal Images, and saves a weird looking image to the hard drive, so I just decided to use awt.Image.
This is the image search class:
public class GoogleCustomSearch {
static String key = //custom google id;
static String cx = // also a custom google id;
static String searchType = "image";
static java.awt.Image[] publicImageArray;
public static java.awt.Image[] Search(String searchParameter,int start) throws IOException, URISyntaxException{
String formatedText = URLEncoder.encode(searchParameter,"UTF-8");
URL url = new URL("https://www.googleapis.com/customsearch/v1?" + "key=" +key + "&cx=" +cx + "&q=" +formatedText + "&searchType=" +searchType +"&imgSize=medium" + "&start=" + start + "&num=10");
System.out.println(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader( ( conn.getInputStream() ) ) );
GResults results = new Gson().fromJson(br, GResults.class);
java.awt.Image [] imageArray = new java.awt.Image[10];
//JProgressBar prb = new JProgressBar();
//MediaTracker loadTracker = new MediaTracker(prb);
for(int i = 0; i<10; i++){
try {
imageArray[i] = ImageIO.read(new URL(results.getLink(i)));
}catch (java.io.IOException e){
imageArray[i] = ImageIO.read(new File("C:\\Users\\FILIP.D\\IdeaProjects\\Manual_Artwork\\src\\MAT - NoImage.jpg"));
}
}
conn.disconnect();
return imageArray;
}
public static BufferedImage getImage(String searchPar, int index, boolean newSearch) throws IOException, URISyntaxException {
int adaptedIndex;
int start;
BufferedImage bimage;
if(index<10){
adaptedIndex = index;
start = 1;
}else if (index<20){
start = 11;
adaptedIndex = index % 10;
if(index == 10){
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
}
}else if(index < 30){
start = 21;
adaptedIndex = index % 10;
if (index == 20) {
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
}
}else{
adaptedIndex = index % 10;
start = 21; //ovo ce posle 30 da ga vrti u loop prvih 10
}
if(newSearch){
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
return bimage = (BufferedImage) publicImageArray[adaptedIndex];
}else{
return bimage = (BufferedImage) publicImageArray[adaptedIndex];
}
}
public static RenderedImage getLiveImage (int index){
return (RenderedImage) publicImageArray[index % 10];
}
}
And this is the snippet of the main GUI class that just handles opening the new image in the array
private void nextImageResult() throws IOException, URISyntaxException {
if(imgNr == -1){
imgNr++;
changeImage(SwingFXUtils.toFXImage(GoogleCustomSearch.getImage(oppenedTrack.getArtistName() + "+" + oppenedTrack.getTrackName(),imgNr,true),null));
}else{
imgNr++;
changeImage(SwingFXUtils.toFXImage(GoogleCustomSearch.getImage(oppenedTrack.getArtistName() + "+" + oppenedTrack.getTrackName(),imgNr,false),null));
}
}
To summarise, I need a proper way to show a progress bar in the place of the image before it loads, and it needs not to hang the UI, for which I can use Task. I can optimise the loading of the array with MediaTracker, so it can prioritize loading the first few images first.

Find anagram of input on set of strings..?

Given a set of strings (large set), and an input string, you need to find all the anagrams of the input string efficiently. What data structure will you use. And using that, how will you find the anagrams?
Things that I have thought of are these:
Using maps
a) eliminate all words with more/less letters than the input.
b) put the input characters in map
c) Traverse the map for each string and see if all letters are present with their count.
Using Tries
a) Put all strings which have the right number of characters into a trie.
b) traverse each branch and go deeper if the letter is contained in the input.
c) if leaf reached the word is an anagram
Can anyone find a better solution?
Are there any problems that you find in the above approaches?
Build a frequency-map from each word and compare these maps.
Pseudo code:
class Word
string word
map<char, int> frequency
Word(string w)
word = w
for char in word
int count = frequency.get(char)
if count == null
count = 0
count++
frequency.put(char, count)
boolean is_anagram_of(that)
return this.frequency == that.frequency
You could build an hashmap where the key is sorted(word), and the value is a list of all the words that, sorted, give the corresponding key:
private Map<String, List<String>> anagrams = new HashMap<String, List<String>>();
void buildIndex(){
for(String word : words){
String sortedWord = sortWord(word);
if(!anagrams.containsKey(sortedWord)){
anagrams.put(sortedWord, new ArrayList<String>());
}
anagrams.get(sortedWord).add(word);
}
}
Then you just do a lookup for the sorted word in the hashmap you just built, and you'll have the list of all the anagrams.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/*
*Program for Find Anagrams from Given A string of Arrays.
*
*Program's Maximum Time Complexity is O(n) + O(klogk), here k is the length of word.
*
* By removal of Sorting, Program's Complexity is O(n)
* **/
public class FindAnagramsOptimized {
public static void main(String[] args) {
String[] words = { "gOd", "doG", "doll", "llod", "lold", "life",
"sandesh", "101", "011", "110" };
System.out.println(getAnaGram(words));
}
// Space Complexity O(n)
// Time Complexity O(nLogn)
static Set<String> getAnaGram(String[] allWords) {
// Internal Data Structure for Keeping the Values
class OriginalOccurence {
int occurence;
int index;
}
Map<String, OriginalOccurence> mapOfOccurence = new HashMap<>();
int count = 0;
// Loop Time Complexity is O(n)
// Space Complexity O(K+2K), here K is unique words after sorting on a
for (String word : allWords) {
String key = sortedWord(word);
if (key == null) {
continue;
}
if (!mapOfOccurence.containsKey(key)) {
OriginalOccurence original = new OriginalOccurence();
original.index = count;
original.occurence = 1;
mapOfOccurence.put(key, original);
} else {
OriginalOccurence tempVar = mapOfOccurence.get(key);
tempVar.occurence += 1;
mapOfOccurence.put(key, tempVar);
}
count++;
}
Set<String> finalAnagrams = new HashSet<>();
// Loop works in O(K), here K is unique words after sorting on
// characters
for (Map.Entry<String, OriginalOccurence> anaGramedWordList : mapOfOccurence.entrySet()) {
if (anaGramedWordList.getValue().occurence > 1) {
finalAnagrams.add(allWords[anaGramedWordList.getValue().index]);
}
}
return finalAnagrams;
}
// Array Sort works in O(nLogn)
// Customized Sorting for only chracter's works in O(n) time.
private static String sortedWord(String word) {
// int[] asciiArray = new int[word.length()];
int[] asciiArrayOf26 = new int[26];
// char[] lowerCaseCharacterArray = new char[word.length()];
// int characterSequence = 0;
// Ignore Case Logic written in lower level
for (char character : word.toCharArray()) {
if (character >= 97 && character <= 122) {
// asciiArray[characterSequence] = character;
if (asciiArrayOf26[character - 97] != 0) {
asciiArrayOf26[character - 97] += 1;
} else {
asciiArrayOf26[character - 97] = 1;
}
} else if (character >= 65 && character <= 90) {
// asciiArray[characterSequence] = character + 32;
if (asciiArrayOf26[character + 32 - 97] != 0) {
asciiArrayOf26[character + 32 - 97] += 1;
} else {
asciiArrayOf26[character + 32 - 97] = 1;
}
} else {
return null;
}
// lowerCaseCharacterArray[characterSequence] = (char)
// asciiArray[characterSequence];
// characterSequence++;
}
// Arrays.sort(lowerCaseCharacterArray);
StringBuilder sortedWord = new StringBuilder();
int asciiToIndex = 0;
// This Logic uses for reading the occurrences from array and copying
// back into the character array
for (int asciiValueOfCharacter : asciiArrayOf26) {
if (asciiValueOfCharacter != 0) {
if (asciiValueOfCharacter == 1) {
sortedWord.append((char) (asciiToIndex + 97));
} else {
for (int i = 0; i < asciiValueOfCharacter; i++) {
sortedWord.append((char) (asciiToIndex + 97));
}
}
}
asciiToIndex++;
}
// return new String(lowerCaseCharacterArray);
return sortedWord.toString();
}
}

Resources