I want to work with the selected row of a Table when the device is a touch one in the pointerPressed method , and what I get is a wrong value : for example I clicked the third line ( PS : the header line is -1 ) and I got 0 as a value in the System.out.println ! And when I click another row then I get the row I selected before !
So how to synchronize LWUIT with the selected row ?
Ok , I found the solution : in the constructor I wrote :
for (short idxComp=3; idxComp<tList.getComponentCount(); idxComp++)
{
tList.getComponentAt(idxComp).addFocusListener(this);
}
isTableSelected = false;
And here are the implemented methods :
public void pointerPressed(int x, int y)
{
int startX, startY, endX, endY, nbComps;
nbComps = tList.getComponentCount();
startX = tList.getComponentAt(3).getAbsoluteX();
endX = tList.getComponentAt(5).getAbsoluteX() + tList.getComponentAt(5).getWidth();
startY = tList.getComponentAt(3).getAbsoluteY();
endY = tList.getComponentAt(nbComps-1).getAbsoluteY() + tList.getComponentAt(nbComps-1).getHeight();
if ( (x >= startX && x <= endX) && (y >= startY && y <= endY) )
{
isTableSelected = true;
if ( (x >= selectedComp.getAbsoluteX() && x <= (selectedComp.getAbsoluteX()+selectedComp.getWidth())) && (y >= selectedComp.getAbsoluteY() && y <= (selectedComp.getAbsoluteY()+selectedComp.getHeight())) )
afficheFicheCredit(selectedRow);
}
}
public void focusGained(Component comp) {
tList.repaint();
selectedComp = tList.getComponentAt(3*selectedRow+3);
if (isTableSelected)
{
isTableSelected = false;
selectedRow = tList.getSelectedRow();
afficheFicheCredit(selectedRow);
}
}
Related
I want to make my dot program turn around when they reach edge
so basically i just simply calculate
x = width/2+cos(a)*20;
y = height/2+sin(a)*20;
it's make circular movement. so i want to make this turn around by checking the edge. i also already make sure that y reach the if condition using println command
class particles {
float x, y, a, r, cosx, siny;
particles() {
x = width/2; y = height/2; a = 0; r = 20;
}
void display() {
ellipse(x, y, 20, 20);
}
void explode() {
a = a + 0.1;
cosx = cos(a)*r;
siny = sin(a)*r;
x = x + cosx;
y = y + siny;
}
void edge() {
if (x>width||x<0) cosx*=-1;
if (y>height||y<0) siny*=-1;
}
}
//setup() and draw() function
particles part;
void setup(){
size (600,400);
part = new particles();
}
void draw(){
background(40);
part.display();
part.explode();
part.edge();
}
they just ignore the if condition
There is no problem with your check, the problem is with the fact that presumably the very next time through draw() you ignore what you did in response to the check by resetting the values of cosx and siny.
I recommend creating two new variables, dx and dy ("d" for "direction") which will always be either +1 and -1 and change these variables in response to your edge check. Here is a minimal example:
float a,x,y,cosx,siny;
float dx,dy;
void setup(){
size(400,400);
background(0);
stroke(255);
noFill();
x = width/2;
y = height/2;
dx = 1;
dy = 1;
a = 0;
}
void draw(){
ellipse(x,y,10,10);
cosx = dx*20*cos(a);
siny = dy*20*sin(a);
a += 0.1;
x += cosx;
y += siny;
if (x > width || x < 0)
dx = -1*dx;
if (y > height || y < 0)
dy = -1*dy;
}
When you run this code you will observe the circles bouncing off the edges:
I'm new at coding. I make an app in Android Studio where the user enters a simple formula (such as 5*2/5+6 or something...) to the field and gets a answer. I am thinking about editText field. Is it posible to do that?
I found this parsing code here: (Didn't test it, but should work just fine)
public static double eval(final String str) {
return new Object() {
int pos = -1, ch;
void nextChar() {
ch = (++pos < str.length()) ? str.charAt(pos) : -1;
}
boolean eat(int charToEat) {
while (ch == ' ') nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}
double parse() {
nextChar();
double x = parseExpression();
if (pos < str.length()) throw new RuntimeException("Unexpected: " + (char)ch);
return x;
}
// Grammar:
// expression = term | expression `+` term | expression `-` term
// term = factor | term `*` factor | term `/` factor
// factor = `+` factor | `-` factor | `(` expression `)`
// | number | functionName factor | factor `^` factor
double parseExpression() {
double x = parseTerm();
for (;;) {
if (eat('+')) x += parseTerm(); // addition
else if (eat('-')) x -= parseTerm(); // subtraction
else return x;
}
}
double parseTerm() {
double x = parseFactor();
for (;;) {
if (eat('*')) x *= parseFactor(); // multiplication
else if (eat('/')) x /= parseFactor(); // division
else return x;
}
}
double parseFactor() {
if (eat('+')) return parseFactor(); // unary plus
if (eat('-')) return -parseFactor(); // unary minus
double x;
int startPos = this.pos;
if (eat('(')) { // parentheses
x = parseExpression();
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
x = Double.parseDouble(str.substring(startPos, this.pos));
} else if (ch >= 'a' && ch <= 'z') { // functions
while (ch >= 'a' && ch <= 'z') nextChar();
String func = str.substring(startPos, this.pos);
x = parseFactor();
if (func.equals("sqrt")) x = Math.sqrt(x);
else if (func.equals("sin")) x = Math.sin(Math.toRadians(x));
else if (func.equals("cos")) x = Math.cos(Math.toRadians(x));
else if (func.equals("tan")) x = Math.tan(Math.toRadians(x));
else throw new RuntimeException("Unknown function: " + func);
} else {
throw new RuntimeException("Unexpected: " + (char)ch);
}
if (eat('^')) x = Math.pow(x, parseFactor()); // exponentiation
return x;
}
}.parse();
}
in your onClick() method of the submit button (or whatever you use to trigger the calculation), do the follwowing:
EditText inputField = findViewById(R.id.your_id_here);
String inputText = inputField.getText().toString();
double output = eval(inputText);
Now do whatever you want with your output, e.g. display it somewhere.
What is the Mathematical formula for CUMIPMT function of EXCEL(how it is calculated)?
I want to calculate it mathematically.
Please Help
The implementation of CUMIPMT in Excel is impossible for us to provide seeing as Excel is not open-source.
However numerous results show up in a Google search such as this implementation in Javascript, this other implementation also in Javascript, or PHPExcel's implementation in PHP.
The closest result would probably be to look at Open Office's C++ implementation - thats very close or identical to Excel's implementation.
It's available in the OpenOffice repository on Github
double SAL_CALL AnalysisAddIn::getCumipmt( double fRate, sal_Int32 nNumPeriods, double fVal,
sal_Int32 nStartPer, sal_Int32 nEndPer, sal_Int32 nPayType ) THROWDEF_RTE_IAE
{
double fRmz, fZinsZ;
if( nStartPer < 1 || nEndPer < nStartPer || fRate <= 0.0 || nEndPer > nNumPeriods || nNumPeriods <= 0 ||
fVal <= 0.0 || ( nPayType != 0 && nPayType != 1 ) )
THROW_IAE;
fRmz = GetRmz( fRate, nNumPeriods, fVal, 0.0, nPayType );
fZinsZ = 0.0;
sal_uInt32 nStart = sal_uInt32( nStartPer );
sal_uInt32 nEnd = sal_uInt32( nEndPer );
if( nStart == 1 )
{
if( nPayType <= 0 )
fZinsZ = -fVal;
nStart++;
}
for( sal_uInt32 i = nStart ; i <= nEnd ; i++ )
{
if( nPayType > 0 )
fZinsZ += GetZw( fRate, double( i - 2 ), fRmz, fVal, 1 ) - fRmz;
else
fZinsZ += GetZw( fRate, double( i - 1 ), fRmz, fVal, 0 );
}
fZinsZ *= fRate;
RETURN_FINITE( fZinsZ );
}
The complete OpenOffice formula converted to C# based on Daniel's suggestion:
/// <summary>
/// The Excel CUMIPMT function as implemented by OpenOffice.
/// https://github.com/apache/openoffice/blob/c014b5f2b55cff8d4b0c952d5c16d62ecde09ca1/main/scaddins/source/analysis/financial.cxx
/// </summary>
/// <param name="rate">rate as double (0.05 for 5%)</param>
/// <param name="numberOfPayments">nper</param>
/// <param name="presentValue">pv</param>
/// <param name="startPeriod">start_period</param>
/// <param name="endPeriod">end_period</param>
/// <param name="type">0 (for payment at the end of period) or 1 (for payment at the beginning of the period</param>
/// <returns>The cumulative interest paid on a loan between start period and end period.</returns>
public double? CumulativeInterestPaid(double rate, int numberOfPayments, double presentValue, int startPeriod, int endPeriod, int type)
{
if (startPeriod < 1 || endPeriod < startPeriod || rate <= 0.0 || endPeriod > numberOfPayments || numberOfPayments <= 0 || presentValue <= 0.0 || (type != 0 && type != 1))
return null;
var fRmz = GetRmz(rate, numberOfPayments, presentValue, 0.0, type);
var fZinsZ = 0.0;
var nStart = startPeriod;
var nEnd = endPeriod;
if (nStart == 1)
{
if (type <= 0)
fZinsZ = -presentValue;
nStart++;
}
for (var i = nStart; i <= nEnd; i++)
{
if (type > 0)
fZinsZ += GetZw(rate, i - 2, fRmz, presentValue, 1) - fRmz;
else
fZinsZ += GetZw(rate, i - 1, fRmz, presentValue, 0);
}
fZinsZ *= rate;
return fZinsZ;
}
// https://github.com/apache/openoffice/blob/c014b5f2b55cff8d4b0c952d5c16d62ecde09ca1/main/scaddins/source/analysis/analysishelper.cxx
private double GetZw(double fZins, double fZzr, double fRmz, double fBw, int nF)
{
double fZw;
if (fZins == 0.0)
fZw = fBw + fRmz * fZzr;
else
{
var fTerm = Pow(1.0 + fZins, fZzr);
if (nF > 0)
fZw = fBw * fTerm + fRmz * (1.0 + fZins) * (fTerm - 1.0) / fZins;
else
fZw = fBw * fTerm + fRmz * (fTerm - 1.0) / fZins;
}
return -fZw;
}
// https://github.com/apache/openoffice/blob/c014b5f2b55cff8d4b0c952d5c16d62ecde09ca1/main/scaddins/source/analysis/analysishelper.cxx
private double GetRmz(double fZins, double fZzr, double fBw, double fZw, int nF)
{
double fRmz;
if (fZins == 0.0)
fRmz = (fBw + fZw) / fZzr;
else
{
var fTerm = Pow(1.0 + fZins, fZzr);
if (nF > 0)
fRmz = (fZw * fZins / (fTerm - 1.0) + fBw * fZins / (1.0 - 1.0 / fTerm)) / (1.0 + fZins);
else
fRmz = fZw * fZins / (fTerm - 1.0) + fBw * fZins / (1.0 - 1.0 / fTerm);
}
return -fRmz;
}
For context: I am going to analyze the breathing movement of parents during kangaroo mother care and I wish to respect their privacy by not recording them, but only the movement of stickers I placed on their chest and stomach.
So far, I'm able to track 2 colours based on webcam input through the code below. However, I would like to record only the tracked colours instead of the webcam feed as to preserve the privacy of the parent.
Does anybody know how to add a background colour, whilst still being able to track colour?
import processing.video.*;
Capture video;
final int TOLERANCE = 20;
float XRc = 0;// XY coordinate of the center of the first target
float YRc = 0;
float XRh = 0;// XY coordinate of the center of the second target
float YRh = 0;
int ii=0; //Mouse click counter
color trackColor; //The first color is the center of the robot
color trackColor2; //The second color is the head of the robot
void setup() {
size(640,480);
video = new Capture(this,640,480);
video.start();
trackColor = color(255,0,0);
trackColor2 = color(255,0,0);
smooth();
}
void draw() {
background(0);
if (video.available()) {
video.read();
}
video.loadPixels();
image(video,0,0);
float r2 = red(trackColor);
float g2 = green(trackColor);
float b2 = blue(trackColor);
float r3 = red(trackColor2);
float g3 = green(trackColor2);
float b3 = blue(trackColor2);
int somme_x = 0, somme_y = 0;
int compteur = 0;
int somme_x2 = 0, somme_y2 = 0;
int compteur2 = 0;
for(int x = 0; x < video.width; x++) {
for(int y = 0; y < video.height; y++) {
int currentLoc = x + y*video.width;
color currentColor = video.pixels[currentLoc];
float r1 = red(currentColor);
float g1 = green(currentColor);
float b1 = blue(currentColor);
if(dist(r1,g1,b1,r2,g2,b2) < TOLERANCE) {
somme_x += x;
somme_y += y;
compteur++;
}
else if(compteur > 0) {
XRc = somme_x / compteur;
YRc = somme_y / compteur;
}
if(dist(r1,g1,b1,r3,g3,b3) < TOLERANCE) {
somme_x2 += x;
somme_y2 += y;
compteur2++;
}
else if(compteur2 > 0) {
XRh = somme_x2 / compteur2;
YRh = somme_y2 / compteur2;
}
}
}
if(XRc != 0 || YRc != 0) { // Draw a circle at the first target
fill(trackColor);
strokeWeight(0.05);
stroke(0);
ellipse(XRc,YRc,20,20);
}
if(XRh != 0 || YRh != 0) {// Draw a circle at the second target
fill(trackColor2);
strokeWeight(0.05);
stroke(0);
ellipse(XRh,YRh,20,20);
}
}
void mousePressed() {
if (mousePressed && (mouseButton == RIGHT)) { // Save color where the mouse is clicked in trackColor variable
if(ii==0){
if (mouseY>480){mouseY=0;mouseX=0;}
int loc = mouseX + mouseY*video.width;
trackColor = video.pixels[loc];
ii=1;
}
else if(ii==1){
if (mouseY>480){mouseY=0;mouseX=0;}
int loc2 = mouseX + mouseY*video.width;
trackColor2 = video.pixels[loc2];
ii=2;
}
}
}
Try adding the background(0); right before you draw the first circle. It should cover the video and you can draw the circles on top of it.
Regards
Jose
There is a string whose characters can only be either ‘a’, ‘b’ or ‘$’, there is only one ‘$’ in the string.
At each step, we can modify the string as follows:
‘$’ can be swapped with its adjacent character, example “a$ba” can be changed to either “$aba” or “ab$a”.
You can swap $ character with next to adjacent character only if adjacent character is different from next to adjacent character. (For example ‘aba$ab’ can be converted into ‘a$abab’ or ‘ababa$’, but ‘ab$aab’ cannot be converted to ‘abaa$b’, because ‘a’ cannot jump over ‘a’).
You are given two strings, the initial state and the final state (lengths will be same), you have to output the minimum number of steps required to change the string in initial state to the string in the final state.
How to solve this problem using Breadth first search ?
example:
string s1 ,s2 ;
input: s1 = a$b , s2 = ab$
output: 1
input: s1 = aba$a , s2 = $baaa
output: 2
In Python:
from collections import deque
def swap(s, a, b):
a, b = min(a,b), max(a,b)
if 0 <= a < b < len(s):
return s[:a] + s[b] + s[a] + s[b+1:]
def rotate(s, a, b):
a, b = min(a,b), max(a,b)
if 0<= a < b < len(s) and len(set(s[a:b+1])) == 3:
return s[:a] + s[b:a:-1] + s[a] + s[b+1:]
def push(Q, changes, s):
if s is not None:
Q.append((changes, s))
def bfs(s1, s2):
Q = deque()
Q.append((0, s1))
while Q:
changes, s = Q.popleft()
if s == s2:
return changes
pos = s.index('$')
push(Q, changes+1, swap(s, pos, pos-1))
push(Q, changes+1, swap(s, pos, pos+1))
push(Q, changes+1, rotate(s, pos, pos+2))
push(Q, changes+1, rotate(s, pos-2, pos))
print bfs('a$b', 'ab$')
print bfs('abaa$a', 'b$aaaa')
print bfs('aba$a', '$baaa')
in C++,
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
int size;
struct str
{
char a[1000];
int change;
};
int position(char a[], char b)
{
for(int i = 0; i < size; i++) {
if(a[i] == b)
return i;
}
return -1;
}
void swap(char a[], int pos, int shift)
{
int temp = a[pos];
a[pos] = a[pos + shift];
a[pos + shift] = temp;
}
int minChange(char arr[], char out[])
{
std::queue <str> q;
str i;
strcpy(i.a, arr);
i.change = 0;
q.push(i);
while(!q.empty()) {
str fin = q.front();
q.pop();
if(strcmp(out, fin.a) == 0)
return fin.change;
int pos = position(fin.a, '$');
if(pos > 0) {
str temp;
strcpy(temp.a, fin.a);
swap(temp.a, pos, -1);
temp.change = fin.change + 1;
q.push(temp);
}
if(pos < size - 1) {
str temp;
strcpy(temp.a, fin.a);
swap(temp.a, pos, 1);
temp.change = fin.change + 1;
q.push(temp);
}
if(pos > 1 && (fin.a[pos - 1] != fin.a[pos - 2])) {
str temp;
strcpy(temp.a, fin.a);
swap(temp.a, pos, -2);
temp.change = fin.change + 1;
q.push(temp);
}
if(pos < size - 2 && (fin.a[pos + 1] != fin.a[pos + 2])) {
str temp;
strcpy(temp.a, fin.a);
swap(temp.a, pos, 2);
temp.change = fin.change + 1;
q.push(temp);
}
}
}
int main()
{
size = 3;
cout<<minChange("a$b", "ab$")<<endl;
size = 6;
cout<<minChange("abaa$a", "b$aaaa")<<endl;
size = 5;
cout<<minChange("aba$a", "$baaa")<<endl;
}
The problem can be solved via breadth-first search as follows, using C#-like pseudocode syntax.
string FinalState; (to be assigned the final state)
int DistanceToFinalState(string CurrentState)
{
if (CurrentState == FinalState)
{
return 0; // end of recursion - strings match, distance is zero
}
else
{
int val1 = Infinity;
int val2 = Infinity;
int val3 = Infinity;
int val4 = Infinity;
if ($ is not at the leftmost position of CurrentState)
val1 = DistanceToFinalState(CurrentState with $ moved to the left);
if ($ is not at the rightmost position of CurrentState)
val2 = DistanceToFinalState(CurrentState with $ move to the right);
if ($ has 2 chars left to it)
val3 = DistanceToFinalState(CurrentState with $ moved 2 chars to the left with the 2 skipped characters reversed);
if ($ has 2 chars right to it)
val4 = DistanceToFinalState(CurrentState with $ moved 2 chars to the right with the 2 skipped characters reversed);
return minumum of {val1, val2, val3, val4};
}
}
The initial problem can be solved by evaluating DistanceToFinalState(InitialState).
In Java:
private static int findTime(String s1, String s2) {
Queue<String> queue = new LinkedList<>();
queue.add(s1);
Map<String, Boolean> visited = new HashMap<>();
while (!queue.isEmpty()) {
String in = queue.poll();
Boolean isVisited = visited.get(in);
if (isVisited != null && isVisited)
continue;
visited.put(in, true);
int index = in.indexOf('$');
//First case...
if ((index + 1) < in.length()) {
String in1 = in.substring(0, index) + in.charAt(index + 1) + "$";
if ((index + 2) < in.length()) {
in1 += in.substring(index + 2);
}
if (in1.equals(s2)) {
return log(visited.size() + 1, 2);
}
if (in1.length() == s2.length()) {
queue.add(in1);
}
}
if (index > 0) {
String in2 = "$" + in.charAt(index - 1) + in.substring(index + 1);
if ((index - 2) >= 0) {
in2 = in.substring(0, index - 1) + in2;
}
if (in2.equals(s2))
return log(visited.size() + 1, 2);
if (in2.length() == s2.length()) {
queue.add(in2);
}
}
//Second case...
if ((index + 2) < in.length()) {
if (in.charAt(index + 1) != in.charAt(index + 2)) {
String in1 = in.substring(0, index) + in.charAt(index + 2)
+ in.charAt(index + 1) + "$";
if ((index + 3) < in.length()) {
in1 += in.substring(index + 3);
}
if (in1.equals(s2))
return log(visited.size() + 1, 2);
if (in1.length() == s2.length()) {
queue.add(in1);
}
}
}
if (index - 1 > 0) {
if (in.charAt(index - 1) != in.charAt(index - 2)) {
String in2 = "$" + in.charAt(index - 1) + in.charAt(index - 2) +
in.substring(index + 1);
if ((index - 3) >= 0) {
in2 = in.substring(0, index - 2) + in2;
}
if (in2.equals(s2))
return log(visited.size() + 1, 2);
if (in2.length() == s2.length()) {
queue.add(in2);
}
}
}
}
return 0;
}
static int log(int x, int base) {
return (int) (Math.log(x) / Math.log(base));
}
System.out.println(findTime("a$b", "ab$"));
System.out.println(findTime("aba$a", "$baaa"));
System.out.println(findTime("abaa$a", "b$aaaa"));