Processing: Confusion with UnHex, is there an easier way? - processing

Doing a uni assignment that requires the importing of table data and conversion of numbers into hexadecimal number.
I tried using unHex() but it got quite confusing converting the strings.
Is there an easier way to convert them?
This is a screenshot of the table data:
Table table;
void setup() {
size(200, 200);
background(255);
table = loadTable("msfw15.csv", "header");
}
void draw() {
//Getting tags, probably an easier way.
String work = table.getString(0, 1);
String fashion = table.getString(1, 1);
String blogger = table.getString(2, 1);
String girlsnight = table.getString(3, 1);
String backstage = table.getString(4, 1);
String ootd = table.getString(5, 1);
String melbourne = table.getString(6, 1);
String sydney = table.getString(7, 1);
String emergingdesigner = table.getString(8, 1);
String fashiongram = table.getString(9, 1);
String foodblogger = table.getString(10, 1);
String hiphop = table.getString(11, 1);
String muji = table.getString(12, 1);
String monochrome = table.getString(13, 1);
String swag = table.getString(14, 1);
String alannahhill = table.getString(15, 1);
String popsofcolour = table.getString(16, 1);
String stylesketch = table.getString(17, 1);
String artist = table.getString(18, 1);
String designer = table.getString(19, 1);
String model = table.getString(20, 1);
String vogue = table.getString(21, 1);
String knitwear = table.getString(22, 1);
String knitting = table.getString(23, 1);
color workd = unhex("FF" + work);
fill(workd);
noStroke();
rect(50, 50, 100, 100);
}

First, I think you really need to learn about for loops. Going through that table should only take a couple lines of code. Here is a link to the for loop reference.
Next, I'd recommend checking out the unhex() reference:
String hs = "FF006699";
int hi = unhex(hs);
fill(hi);
rect(30, 20, 55, 55);
Other than that, you need to be much more specific about exactly what you're confused about. What about the unhex() function isn't working how you expect?

Related

What this parameter is responsible for? markerSpec in InteractiveInfoWindowAndroid by Appolica

in https://github.com/Appolica/InteractiveInfoWindowAndroid i read that
markerSpec - Provides the marker's offsetX and offsetY
but I can't understand what it is responsible for, I changed the values in every possible way, but the result was always the same. R.dimen.marker_offset_x =5dp R.dimen.marker_offset_y=39dp
public void onMapReady(GoogleMap googleMap) {
final Marker marker2 = googleMap.addMarker(new MarkerOptions().position(new LatLng(1, 1)).snippet(FORM_VIEW));
final int offsetX = (int) getResources().getDimension(R.dimen.marker_offset_x);
final int offsetY = (int) getResources().getDimension(R.dimen.marker_offset_y);
final InfoWindow.MarkerSpecification markerSpec =
new InfoWindow.MarkerSpecification(offsetX, offsetY);
formWindow = new InfoWindow(marker2, markerSpec, new FormFragment());
googleMap.setOnMarkerClickListener(MainActivity.this);
}
Maybe someone has worked with this and can explain it to me
Okay I was entering too large values

How to run processing script on multiple frames in a folder

Using processing I am trying to run a script that will process a folder full of frames.
The script is a combination of PixelSortFrames and SortThroughSeamCarving.
I am new to processing and what I want does not seems to be working. I would like the script to run back through and choose the following file in the folder to be processed. At the moment it stops at the end and does not return to start on next file (there are three other modules also involved).
Any help would be much appreciated. :(
/* ASDFPixelSort for video frames v1.0
Original ASDFPixelSort by Kim Asendorf <http://kimasendorf.com>
https://github.com/kimasendorf/ASDFPixelSort
Fork by dx <http://dequis.org> and chinatsu <http://360nosco.pe>
// Main configuration
String basedir = ".../Images/Seq_002"; // Specify the directory in which the frames are located. Use forward slashes.
String fileext = ".jpg"; // Change to the format your images are in.
int resumeprocess = 0; // If you wish to resume a previously stopped process, change this value.
boolean reverseIt = true;
boolean saveIt = true;
int mode = 2; // MODE: 0 = black, 1 = bright, 2 = white
int blackValue = -10000000;
int brightnessValue = -1;
int whiteValue = -6000000;
// -------
PImage img, original;
float[][] sums;
int bottomIndex = 0;
String[] filenames;
int row = 0;
int column = 0;
int i = 0;
java.io.File folder = new java.io.File(dataPath(basedir));
java.io.FilenameFilter extfilter = new java.io.FilenameFilter() {
boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(fileext);
}
};
void setup() {
if (resumeprocess > 0) {i = resumeprocess - 1;frameCount = i;}
size(1504, 1000); // Resolution of the frames. It's likely there's a better way of doing this..
filenames = folder.list(extfilter);
size(1504, 1000);
println(" " + width + " x " + height + " px");
println("Creating buffer images...");
PImage hImg = createImage(1504, 1000, RGB);
PImage vImg = createImage(1504, 1000, RGB);
// draw image and convert to grayscale
if (i +1 > filenames.length) {println("Uh.. Done!"); System.exit(0);}
img = loadImage(basedir+"/"+filenames[i]);
original = loadImage(basedir+"/"+filenames[i]);
image(img, 0, 0);
filter(GRAY);
img.loadPixels(); // updatePixels is in the 'runKernals'
// run kernels to create "energy map"
println("Running kernals on image...");
runKernels(hImg, vImg);
image(img, 0, 0);
// sum pathways through the image
println("Getting sums through image...");
sums = getSumsThroughImage();
image(img, 0, 0);
loadPixels();
// get start point (smallest value) - this is used to find the
// best seam (starting at the lowest energy)
bottomIndex = width/2;
// bottomIndex = findStartPoint(sums, 50);
println("Bottom index: " + bottomIndex);
// find the pathway with the lowest information
int[] path = new int[height];
path = findPath(bottomIndex, sums, path);
for (int bi=0; bi<width; bi++) {
// get the pixels of the path from the original image
original.loadPixels();
color[] c = new color[path.length]; // create array of the seam's color values
for (int i=0; i<c.length; i++) {
try {
c[i] = original.pixels[i*width + path[i] + bi]; // set color array to values from original image
}
catch (Exception e) {
// when we run out of pixels, just ignore
}
}
println(" " + bi);
c = sort(c); // sort (use better algorithm later)
if (reverseIt) {
c = reverse(c);
}
for (int i=0; i<c.length; i++) {
try {
original.pixels[i*width + path[i] + bi] = c[i]; // reverse! set the pixels of the original from sorted array
}
catch (Exception e) {
// when we run out of pixels, just ignore
}
}
original.updatePixels();
}
// when done, update pixels to display
updatePixels();
// display the result!
image(original, 0, 0);
if (saveIt) {
println("Saving file...");
//filenames = stripFileExtension(filenames);
save("results/SeamSort_" + filenames + ".tiff");
}
println("DONE!");
}
// strip file extension for saving and renaming
String stripFileExtension(String s) {
s = s.substring(s.lastIndexOf('/')+1, s.length());
s = s.substring(s.lastIndexOf('\\')+1, s.length());
s = s.substring(0, s.lastIndexOf('.'));
return s;
}
This code works by processing all images in the selected folder
String basedir = "D:/things/pixelsortframes"; // Specify the directory in which the frames are located. Use forward slashes.
String fileext = ".png"; // Change to the format your images are in.
int resumeprocess = 0; // If you wish to resume a previously stopped process, change this value.
int mode = 1; // MODE: 0 = black, 1 = bright, 2 = white
int blackValue = -10000000;
int brightnessValue = -1;
int whiteValue = -6000000;
PImage img;
String[] filenames;
int row = 0;
int column = 0;
int i = 0;
java.io.File folder = new java.io.File(dataPath(basedir));
java.io.FilenameFilter extfilter = new java.io.FilenameFilter() {
boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(fileext);
}
};
void setup() {
if (resumeprocess > 0) {i = resumeprocess - 1;frameCount = i;}
size(1920, 1080); // Resolution of the frames. It's likely there's a better way of doing this..
filenames = folder.list(extfilter);
}
void draw() {
if (i +1 > filenames.length) {println("Uh.. Done!"); System.exit(0);}
row = 0;
column = 0;
img = loadImage(basedir+"/"+filenames[i]);
image(img,0,0);
while(column < width-1) {
img.loadPixels();
sortColumn();
column++;
img.updatePixels();
}
while(row < height-1) {
img.loadPixels();
sortRow();
row++;
img.updatePixels();
}
image(img,0,0);
saveFrame(basedir+"/out/"+filenames[i]);
println("Frames processed: "+frameCount+"/"+filenames.length);
i++;
}
essentially I want to do the same thing only with a different image process but my code is not doing this to all with in the folder... just one file.
You seem to be confused about what the setup() function does. It runs once, and only once, at the beginning of your code's execution. You don't have any looping structure for processing the other files, so it's no wonder that it only processes the first one. Perhaps wrap the entire thing in a for loop? It looks like you kind of thought about this, judging by the global variable i, but you never increment it to go to the next image and you overwrite its value in several for loops later anyway.

Blackberry APplication not rendering well on PORSCHE phones

I have got a Blackberry native application I have been working on in the past few weeks.
Basically it consists of a few screens in which I get to draw the designs of my screen by overriding the paint method of the FieldManagers
I have tested on blackberry 4.5 and other blackberry's.
It has rendered well so far until I ran into a hitch testing on Blackberry's Porsche version
which does not render my designs well. What I experience is that on scrolling, my screen gets wiped off.
Pls does any one here experienced such issues in the past and what would be the cause. I would be willing to show sections of the code to give insight into the issues I am experiencing. Least I mention it displays well on the simulator without these issues.
I have posted a sample screen which is my login screen:
final VerticalFieldManager everythingPanel = new VerticalFieldManager(VERTICAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(new UtilNew().ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(), Display.getHeight());
}
};
final VerticalFieldManager spaceHolder1 = new VerticalFieldManager()
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(new Util().ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(Display.getWidth(),topSpaceHeight);
setExtent(Display.getWidth(), topSpaceHeight);
}
};
final VerticalFieldManager contentHolderPix = new VerticalFieldManager(VerticalFieldManager.VERTICAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(util.ashbrand);//black
graphics.setColor(new Util().whitebrand);
System.out.println(">>>>!!!!>>>>" + "img/icons/logo" + new Util().getResource() + ".png");
EncodedImage image_1 = EncodedImage.getEncodedImageResource("img/icons/icon" + new Util().getResource() + ".png");
setFont(util.initializeUtilFont("Arial", editFieldFontHeaderSize, Font.BOLD));
int startHere = topSpaceHeight - image_1.getHeight() - 5;
int imageWidth1 = (int)((Display.getWidth() - image_1.getWidth() - getFont().getAdvance("Sign In"))/2);
graphics.drawBitmap(new XYRect(imageWidth1 - 10 - whiteBgEdge.left - whiteBgEdge.right, startHere, image_1.getWidth(), image_1.getHeight()), image_1.getBitmap(), 0, 0);
int startfonty = startHere + ((image_1.getHeight() - getFont().getHeight())/2);
graphics.drawText("Sign In", imageWidth1, startfonty);
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(whiteBgWidth,topSpaceHeight);
setExtent(whiteBgWidth, topSpaceHeight);
setMargin(whiteBgEdge);
}
};
System.out.println("whiteBgWidth>>>>" + whiteBgWidth);
System.out.println("padExtWhiteBg>>>>" + padExtWhiteBg);
usernameField = utilNew.newEditTextField(editFieldWidth, editFont.getHeight(), 30,
EditField.NO_NEWLINE, "", editFieldPad, editFont, false, "Username");
passwordField = utilNew.newPasswordField(editFieldWidth, editFont.getHeight(), 30,
PasswordEditField.NO_NEWLINE, "Password", editFieldPad, editFont);
//usernameField.setMargin(holderPad1);
if(user_!=null && user_.getSignInUserName()!=null && user_.getSignInUserName().trim().length()>0)
usernameField.setText(user_.getSignInUserName());
final int edHt = editFont.getHeight() + editFieldPad.top + editFieldPad.bottom;
final int edWt = editFieldWidth + editFieldPad.left + editFieldPad.right;
System.out.println("edHt = " + edHt);
System.out.println("edWt = " + edWt);
System.out.println("HolderPad1 = " + holderPad1.top + ", " + holderPad1.bottom + ", " + holderPad1.left + ", " + holderPad1.right);
usernameFieldHolder = utilNew.generateEditTextField(usernameField, true, holderPad1, edHt, edWt, true);
passwordFieldHolder = utilNew.generateEditTextField(passwordField, true, holderPad2, edHt, edWt, false);
final int height_ = edHt + edHt + holderPad1.top + holderPad1.bottom + holderPad2.top + holderPad2.bottom + 20;
System.out.println("height___>>>>>" + height_);
final VerticalFieldManager contentHolder1 = new VerticalFieldManager()
{
public void paint(Graphics graphics)
{
//System.out.println(edHt + "," + edHt + "," + holderPad1.top + "," + holderPad1.bottom + "," + holderPad2.top + "," + holderPad2.bottom);
graphics.setBackgroundColor(util.ashbrand);//black
graphics.setColor(new Util().whitebrand);
graphics.drawRoundRect(0, 0, whiteBgWidth, height_, 20, 20);
graphics.fillRoundRect(0, 0, whiteBgWidth, height_, 20, 20);
graphics.setColor(0x00808080);
//System.out.println("This is changed?");
//System.out.println("<<<<<<.." + usernameFieldHolder.getPreferredHeight() + "hfm.getPreferredHeight() = 0" + usernameFieldHolder.getWidth() );
//graphics.drawLine(40, usernameField.getPreferredHeight(), whiteBgWidth, usernameField.getPreferredHeight());/**/
super.paint(graphics);
}
public void sublayout(int width, int height){
System.out.println(Display.getHeight() + " - " + Display.getWidth());
System.out.println("Wdith & height = " + width + " && " + height);
System.out.println("Wdith & this.getPreferredHeight() = " + this.getWidth() + " && " + this.getHeight());
super.sublayout(whiteBgWidth,height_);
setExtent(whiteBgWidth, height_);
setMargin(whiteBgEdge);
}
};
int buttonHeight = 70;
/*CustomManager hfm_buttons = util.generateHFM1(
contentHolder1.getPreferredWidth(),
buttonHeight,
new Util().whitebrand,
0);*/
//submitButton = new UtilNew().generateButtonField(0x333333, util.whitebrand, "LOGIN", null);
//registerButton = new UtilNew().generateButtonField(0x333333, util.whitebrand, "REGISTER", null);
final LabelField loginButton = new LabelField("", Field.FOCUSABLE)
{
private int hColor;
public boolean isFocusable() {
return true;
}
protected void drawFocus(Graphics g, boolean on){
XYRect rect = new XYRect();
getFocusRect(rect);
drawHighlightRegion(g, HIGHLIGHT_FOCUS, false, rect.x, rect.y, rect.width, rect.height);
}
public void paint(Graphics g)
{
EncodedImage left;
EncodedImage right;
EncodedImage center;
if(isFocus())
{
left = EncodedImage.getEncodedImageResource("img/buttons/left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/right.png");
g.setColor(util.green);
hColor = 0xcccccc;
}
else
{
left = EncodedImage.getEncodedImageResource("img/buttons/_left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/_center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/_right.png");
g.setColor(util.greenDark);
hColor = util.ashbrand;
}
//g.fillRect(0, 0, getPreferredWidth(), getPreferredHeight());
int totalWidth = whiteBgWidth + 4;
XYRect left_edge=new XYRect(2, 2, left.getWidth(), left.getHeight());
g.drawBitmap(left_edge, left.getBitmap(), 0, 0);
//invalidate();
int startX= (Display.getWidth() - totalWidth)/2;
int vount = (int)((totalWidth - left.getWidth() - right.getWidth())/center.getWidth()) - 3;
//System.out.println("vount = " + vount);
int widthbt = 0;
for(int c=0; c<vount; c++)
{
widthbt = left.getWidth() + (c*center.getWidth())+2;
XYRect center_edge=new XYRect(widthbt, 2, center.getWidth(), center.getHeight());
g.drawBitmap(center_edge, center.getBitmap(), 0, 0);
}
XYRect right_edge=new XYRect(widthbt,2, right.getWidth(), right.getHeight());
g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//invalidate();
//g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//g.fillRect(left_edge.getWidth(), 0, getPreferredWidth(), getPreferredHeight());
int colorOld = g.getColor();
g.setColor(hColor);
g.drawRoundRect(0, 0, totalWidth-4, left.getHeight()+4, 3, 3);
g.setColor(colorOld);
if(isFocus())
{
g.setColor(util.black);
}
else
{
g.setColor(util.whitebrand);
}
int height = (left.getHeight() - getFont().getHeight())/2;
int width = (totalWidth - getFont().getAdvance("Sign In"))/2;
g.drawText("Sign In", width, height);
setExtent(totalWidth+ 5,left.getHeight() + 10);
//setMargin(new XYEdges(20, 10, 0, whiteBgEdge.left));
invalidate();
super.paint(g);
}
public int getPreferredHeight() {
return getFont().getHeight() + 20;
}
public int getPreferredWidth() {
return (int)(whiteBgWidth);
}
protected boolean navigationClick(int status, int time) {
removeAllMenuItems();
String userName = usernameField.getText().toString().toLowerCase();
user_.setSignInUserName(userName);
String passWord = passwordField.getText().toString();
System.out.println("username = " + userName + " & password = " + passWord);
User user = User.getInstance();
System.out.println(">>instance of user from sign in: " + user);
Records record = new Records();
if(passWord.trim().length() < 2 || userName.trim().length() < 2){
Dialog.alert("Invalid username and/or password entered");
SignIn screen = new SignIn();
ScreenController screenController = ScreenController.getInstance();
screenController.addNewScreen(screen);
}else{
System.out.println("else if data is calid");
String hashPassword = user.md5Java(passWord);
hashPassword = "e86e107b113b0f830b9b817b4a9addb8";
user_.setUserName(userName);
user_.setPassword(passWord);
System.out.println("Check data availability");
try
{
FileConnection fc = (FileConnection)Connector.open(utilNew.FOLDER_LOCATION);
FileConnection fc1 = (FileConnection)Connector.open(utilNew.FOLDER_LOCATION_REF);
if (!fc.exists())
{
fc.mkdir();
if (!fc1.exists())
{
fc.mkdir();
}
}
fc.close();
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage() );
}
if((record.isDataAvailable(record.userTable)==true))
{
System.out.println(">>>>### -1 ");
String[] allRecords = record.getAllRecords(record.userTable);
boolean proceedYes = true;
int count = 0;
while(proceedYes && count<allRecords.length)
{
System.out.println(">>>> Record = " + allRecords[count]);
//Dialog.alert(">>>> Record = " + allRecords[count]);
DataInputStream is = new DataInputStream(new ByteArrayInputStream(allRecords[count].getBytes()));
try {
System.out.println(">>>>555");
//System.out.println(">>>>" + is.readUTF() + " && " + is.readUTF() + " && " + is.readUTF());
String l = is.readUTF();
String u = is.readUTF();
String p = is.readUTF();
//System.out.println("e>>>>" + is.readUTF() + " && " + is.readUTF() + " && " + is.readUTF());
System.out.println("f>>>>" + l + " && " + u + " && " + p);
System.out.println("g>>>>" + userName + " && " + passWord + " && " + p);
if(u.equals(userName) && p.equals(passWord))
{
//Dialog.alert(">>>>12");
System.out.println(">>>889948444>");
proceedYes = false;
MenuLists screen = new MenuLists(10);
//UiApplication.getUiApplication().pushScreen(homeScreen);
ScreenController screenController = ScreenController.getInstance();
screenController.setCurrentScreen(SignIn.this);
screenController.addNewScreen(screen);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(">>>>Error " + e.getMessage() + " && " + e.toString() );
}
count++;
}
if(proceedYes)
{
System.out.println(">>>>### 3 ");
Hashtable jj = new Hashtable();
boolean proceedNow = false;
jj.put("username", userName);
jj.put("password", passWord);
jj.put("url", "https://localhost:8080/signinws/rest/account/login2");
System.out.println("object sent to server: "+jj);
ProcessAction processAction = new ProcessAction(jj, 0, record);
PopUpScreen.showScreenAndWait(processAction, "Setting up our account. Please Wait");
}
}
else
{
System.out.println(">>>>### o ");
Hashtable jj = new Hashtable();
boolean proceedNow=false;
System.out.println(">>>>### 4 ");
jj.put("username", userName);
jj.put("password", passWord);
jj.put("url", "https://localhost:8080/signinws/rest/account/login2");
System.out.println("object sent to server: "+jj);
proceedNow = true;
ProcessAction processAction = new ProcessAction(jj, 0, record);
PopUpScreen.showScreenAndWait(processAction, "Please Wait");
}
}
return super.navigationClick(status, time);
}
};
final LabelField registerButton = new LabelField("", Field.FOCUSABLE)
{
public boolean isFocusable() {
return true;
}
protected void drawFocus(Graphics g, boolean on){
XYRect rect = new XYRect();
getFocusRect(rect);
drawHighlightRegion(g, HIGHLIGHT_FOCUS, false, rect.x, rect.y, rect.width, rect.height);
}
public void paint(Graphics g)
{
EncodedImage left;
EncodedImage right;
EncodedImage center;
int hColor;
if(isFocus())
{
left = EncodedImage.getEncodedImageResource("img/buttons/left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/right.png");
g.setColor(util.green);
hColor = 0xcccccc;
}
else
{
left = EncodedImage.getEncodedImageResource("img/buttons/_left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/_center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/_right.png");
g.setColor(util.greenDark);
hColor = util.ashbrand;
}
//g.fillRect(0, 0, getPreferredWidth(), getPreferredHeight());
int totalWidth = whiteBgWidth + 4;
XYRect left_edge=new XYRect(2, 2, left.getWidth(), left.getHeight());
g.drawBitmap(left_edge, left.getBitmap(), 0, 0);
//invalidate();
int startX= (Display.getWidth() - totalWidth)/2;
int vount = (int)((totalWidth - left.getWidth() - right.getWidth())/center.getWidth()) - 3;
XYRect left_edgeH=new XYRect(0, 0, vount, left.getHeight()+2);
//System.out.println("vount = " + vount);
int widthbt = 0;
for(int c=0; c<vount; c++)
{
widthbt = left.getWidth() + (c*center.getWidth()) + 2;
XYRect center_edge=new XYRect(widthbt, 2, center.getWidth(), center.getHeight());
g.drawBitmap(center_edge, center.getBitmap(), 0, 0);
}
XYRect right_edge=new XYRect(widthbt,2, right.getWidth(), right.getHeight());
g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//invalidate();
//g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//g.fillRect(left_edge.getWidth(), 0, getPreferredWidth(), getPreferredHeight());
int colorOld = g.getColor();
g.setColor(hColor);
g.drawRoundRect(0, 0, totalWidth-4, left.getHeight()+4, 3, 3);
g.setColor(colorOld);
if(isFocus())
{
g.setColor(util.black);
}
else
{
g.setColor(util.whitebrand);
}
int height = (left.getHeight() - getFont().getHeight())/2;
int width = (totalWidth - getFont().getAdvance("Create An Account"))/2;
g.drawText("Create An Account", width, height);
setExtent(totalWidth + 5,left.getHeight() + 10);
setPosition(0, getFont().getHeight() + 30);
invalidate();
super.paint(g);
}
public int getPreferredHeight() {
return getFont().getHeight() + 20;
}
public int getPreferredWidth() {
return (int)(whiteBgWidth);
}
protected boolean navigationClick(int status, int time) {
removeAllMenuItems();
RegisterScreen registerScreen = new RegisterScreen();
ScreenController screenController = ScreenController.getInstance();
screenController.addNewScreen(registerScreen);
return super.navigationClick(status, time);
}
};
final VerticalFieldManager spaceHolder2 = new VerticalFieldManager(NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(utilNew.ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
int w = whiteBgWidth;
super.sublayout(w, (loginButton.getPreferredHeight() * 2) + 40);
setExtent(w, (loginButton.getPreferredHeight() * 2) + 40);
int startX = (int)((Display.getWidth() - whiteBgWidth)/2);
setMargin(new XYEdges(20, 0, 0, startX));
}
};
spaceHolder2.add(loginButton);
spaceHolder2.add(registerButton);
//spaceHolder2.add(registerButton);
spaceHolder1.add(contentHolderPix);
everythingPanel.add(spaceHolder1);
contentHolder1.add(usernameFieldHolder);
contentHolder1.add(passwordFieldHolder);
/*passwordFieldDummyHolder.setFocusListener(new FocusChangeListener(){
public void focusChanged(Field field, int eventType) {
// TODO Auto-generated method stub
if(eventType == FocusChangeListener.FOCUS_GAINED)
{
contentHolder1.replace(passwordFieldDummyHolder, passwordFieldHolder);
}
}
});
passwordFieldHolder.setFocusListener(new FocusChangeListener(){
public void focusChanged(Field field, int eventType) {
// TODO Auto-generated method stub
if(eventType == FocusChangeListener.FOCUS_LOST)
{
System.out.println(">>>>>|>>>" + passwordFieldHolder.getIndex());
System.out.println(">>>>>|>>>" + passwordFieldDummyHolder.getIndex());
if(passwordField.getText().length()==0)
{
System.out.println(">>>>>1>>>");
passwordFieldDummyHolder = utilNew.generateEditTextField(passwordFieldDummy, true, holderPad2, edHt, edWt, false);
contentHolder1.replace(passwordFieldHolder, passwordFieldDummyHolder);
//loginButton.setFocus();
}
System.out.println(">>>>>2>>>");
System.out.println(">>>>>2>>>");
}
}
});*/
everythingPanel.add(contentHolder1);
everythingPanel.add(spaceHolder2);
add(everythingPanel);
}
I don't know what your problem actually is, but from what I have seen in your sample code it is clear that you are using the UI framework in a way that is not correct. You need to fix these issues before proceeding further.
Here is an example:
final VerticalFieldManager everythingPanel = new VerticalFieldManager(VERTICAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(new UtilNew().ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(), Display.getHeight());
}
};
In this case you ask the parent Manager to lay itself out and give it specific sizes to do so. When doing this, you need to be sure that the sizes you are giving the parent class are not bigger than the size you have been given, So it is more correct to code something like:
super.sublayout(Math.min(Display.getWidth(), width),Math.min(Display.getHeight(), height));
What this will do is attempt to layout the Fields that are contained in the Manager, within the confines of the screen space you have told it to use (in this case the size of the screen). Having done this, it will set the actual size that it needs - in other words, at the end of the layout method, VerticalFieldManager will know how big it needs to be and will set that size. Then it returns. And then you do this:
setExtent(Display.getWidth(), Display.getHeight());
Effectively now you have a VerticalFieldManager that thinks it is working in a certain size, and will optimise its painting around that size, and you have potentially given it a different size. This could confuse!
The same comments apply within a Field's layout() method too.
In other words, if you are going to let the super class layout the Fields, then let the super class set the size, otherwise things can be confused.
Here is another, in fact worse, example:
final VerticalFieldManager spaceHolder2 = new VerticalFieldManager(NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(utilNew.ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
int w = whiteBgWidth;
super.sublayout(w, (loginButton.getPreferredHeight() * 2) + 40);
setExtent(w, (loginButton.getPreferredHeight() * 2) + 40);
int startX = (int)((Display.getWidth() - whiteBgWidth)/2);
setMargin(new XYEdges(20, 0, 0, startX));
}
};
Why is this worse? Because of this line:
setMargin(new XYEdges(20, 0, 0, startX));
Remember the point of sublayout is to position all your Fields on the screen. You have invoked the super.sublayout() processing to do this, and then, once it has done it, you suddenly say actually, I want some margins on the Field. Again you are potentially confusing the processing - in the middle of laying out the Fields you are changing one of the factors that is related to laying the Fields out...
I suggest you review the documentation around creating Managers (and presumably Fields) and look to remove any code that is disrupting this process. To assist you in this investigation, I recommend that you start here:
http://supportforums.blackberry.com/t5/Java-Development/MainScreen-explained/ta-p/606644
and then look at these:
http://supportforums.blackberry.com/t5/Java-Development/How-to-Extend-the-Screen/ta-p/446745
http://supportforums.blackberry.com/t5/Java-Development/How-to-Extend-the-Screen/ta-p/446745
http://supportforums.blackberry.com/t5/Java-Development/Create-a-custom-layout-manager-for-a-screen/ta-p/442990
http://supportforums.blackberry.com/t5/Java-Development/Create-custom-fields/ta-p/444962
You do a similar sort of thing in your paint routine. Here is a snippet:
public void paint(Graphics g)
{
EncodedImage left;
EncodedImage right;
...
left = EncodedImage.getEncodedImageResource("img/buttons/left.png");
...
setExtent(totalWidth + 5,left.getHeight() + 10);
setPosition(0, getFont().getHeight() + 30);
invalidate();
super.paint(g);
}
paint()'s job is to paint, not to position. Your code is supposed to position Fields in your layout (or sublayout) processing. But in the code above, you potentially move and change the size of a Field while it is trying to paint it!!!! This is bound to cause the system some problems.
The general rule in paint() is you do NOT change the Field, you just paint its current contents.
Two other things I will comment on with respect to the paint() code given above.
1) paint() is called often. You really want to minimise the processing done in paint. So don't create an image (see the left image in the code included above) each time you go through it. Create this once and then use paint to paint() the image. Doing excessive work in paint causes performance problems as well as killing the battery. This is the sort of thing you will not notice on the Simulator because it is so fast compared to the device.
2) And be aware that idea when using invalidate() is to repaint the Field. So there is no point calling invalidate() in the middle of paint(). In fact by doing this, you are causing an infinite loop. Each time you call paint(), your code is then using invalidate() to ask the Field to repaint itself, which causes paint() to be invoked, which asks for a invalidate(), ... You get the picture!.
I have pointed out problems in your layout processing and your paint processing. I'm not saying that these problems are in fact directly giving you the issues you see. It might be something else. You have supplied far too much code for me to review it all looking for that needle. If you want us to review code in detail, then I suggest you recreate the problem with a smaller sample of code. In fact I recommend you try to do this, because by cutting out code until the problem disappears, you will find out what actually is causing the problem.
Finally a couple of other points:
A) There is no real difference between doing background painting in paint() or paintBackground(). And in fact the only background painting you seem to do is this:
graphics.setBackgroundColor(new UtilNew().ashbrand);
graphics.clear();
which is absolutely fine in paint(), and I wouldn't bother changing this to use paintBackground() or a Background class. The one issue I have with this code is that fact that you create a new class instance of UtilNew each time paint is invoked (which is a lot). That won't help performance.
B) I would avoid calling Screen.invalidate() in a scroll change listener until you are sure that there is no other way to get the screen painted correctly. As noted, there is a lot of other suspect code in what you have supplied. Correct that before you try Screen.invalidate().

Processing and Twitter4j, problems searching for tweets

I have processing 2.0 and twitter4j 3.0.3; when I try to run the program I get the error message
"The function "getTweet() does not exist".
I have tried getStatuses instead to no avail, I get the same error message that the function does not exist.
Help?
ArrayList<String> words = new ArrayList();
TwitterFactory twitterFactory;
Twitter twitter;
void setup() {
size(500, 500);
background(0);
smooth();
connectTwitter();
}
void draw() {
//draw fade rectangle
fill(0, 1);
rect(0, 0, width, height);
//draw arraylist words
int i = (frameCount % words.size());
String word = words.get(i);
fill(255, random(50, 150));
textSize(random(10, 30));
text(word, random(width), random(height));
}
// Initial connection
void connectTwitter() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("FvnrJfRMsMUCEhL0xxPegQ");
cb.setOAuthConsumerSecret("ZSnKgo6EQmq9wVd5gCMbufcMP5ztFuQhVwKpJvDhAY");
cb.setOAuthAccessToken("274686457-ZiYxpWchtcwHod7UXPjLCj18djl9CyNrk1HMqtQx");
cb.setOAuthAccessTokenSecret("kafd2QHznAu4Mu0R9x5HNyeyA4J3UwCOpETQYeDU");
twitterFactory = new TwitterFactory(cb.build());
twitter = twitterFactory.getInstance();
Query query = new Query("#BioshockInfinite");
query.setCount(100);
try {
QueryResult result = twitter.search(query);
ArrayList Status = (ArrayList) result.getTweet();
for (int i = 0; i < tweet.size(); i++) {
Status s = (Status) tweet.get(i);
User user = s.getUser;
String name = user.getName();
String msg = s.getText();
Date d = s.getCreatedAt();
println("Tweet by" + user + "at" + d + ":" + msg);
}
}
catch (TwitterException te) {
println("Couldn't connect:" + te);
}
}
I changed the line
ArrayList Status = (ArrayList) result.getTweet();
(which looks a bit odd anyway) to
List<Status> tweets = result.getTweets();
and I get Results now.
Eclipse showed an error that getTweet() wants a List to store the Tweets.

SHA1 with salt on windows phone 7

I have some some time now reshearchd how to encode a password to SHA1 with a salt.
The is the code i used on my web application part, but it will not work on a phone environment.
public class Password
{
private string _password;
private int _salt;
public Password(string strPassword, int nSalt)
{
_password = strPassword;
_salt = nSalt;
}
public string ComputeSaltedHash()
{
// Create Byte array of password string
ASCIIEncoding encoder = new ASCIIEncoding();
Byte[] _secretBytes = encoder.GetBytes(_password);
// Create a new salt
Byte[] _saltBytes = new Byte[4];
_saltBytes[0] = (byte)(_salt >> 24);
_saltBytes[1] = (byte)(_salt >> 16);
_saltBytes[2] = (byte)(_salt >> 8);
_saltBytes[3] = (byte)(_salt);
// append the two arrays
Byte[] toHash = new Byte[_secretBytes.Length + _saltBytes.Length];
Array.Copy(_secretBytes, 0, toHash, 0, _secretBytes.Length);
Array.Copy(_saltBytes, 0, toHash, _secretBytes.Length, _saltBytes.Length);
SHA1 sha1 = SHA1.Create();
Byte[] computedHash = sha1.ComputeHash(toHash);
return encoder.GetString(computedHash);
}
public static int CreateRandomSalt()
{
Byte[] _saltBytes = new Byte[4];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(_saltBytes);
return ((((int)_saltBytes[0]) << 24) + (((int)_saltBytes[1]) << 16) +
(((int)_saltBytes[2]) << 8) + ((int)_saltBytes[3]));
}
public static string CreateRandomPassword(int PasswordLength)
{
String _allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789!\"#ยค%&/()=?$+-_.,;'*";
Byte[] randomBytes = new Byte[PasswordLength];
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
rng.GetBytes(randomBytes);
char[] chars = new char[PasswordLength];
int allowedCharCount = _allowedChars.Length;
for (int i = 0; i < PasswordLength; i++)
{
chars[i] = _allowedChars[(int)randomBytes[i] % allowedCharCount];
}
return new string(chars);
}
}
Silverlight and Windows Phone 7 do not have an ASCIIEncoding. I suggest you use the UTF8Encoding instead. If you are certain that your passwords are always within the ASCII range then this encoding will work the same as the ASCIIEncoding would of had it been present.
If on the other hand you cannot guarantee that passwords are always within the ASCII range then you would need to make sure both ends hash using the UTF8Encoding to ensure generated hashs are the same.

Resources