Javascript onClick event in all cells
I'm learning JavaScript and I've not that much experience. But I'm making
a HTML table and I want to add in every table cell (<td>) a onClick event.
<table id="1">
<tr>
<td onClick="tes()">1</td><td onClick="tes()">2</td>
</tr>
<tr>
<td onClick="tes()">3</td><td onClick="tes()">4</td>
</tr>
</table>
Is there another way to do this event in every cell?
Thursday, 3 October 2013
Wednesday, 2 October 2013
Oh no. Upgrade interupted. Please help
Oh no. Upgrade interupted. Please help
I have decided to upgrade my Ubuntu 12.04 to 12.10. I had about 4.1GB
space left on /. NOt until the last minute during the install phase did
the upgrade manager ask me to make space on my drive. I started the
software manager and now I can't get out of it back to continuing the
upgrade. It keeps on asking me to repair the package catalogue, and has no
x bar or button to close it, nor can I alt-tab to the updater window. I am
stuck half way through an upgrade and can't get out. I have been a fan of
ubuntu for years but after today I fear I have lost confidence.... Please
someone help. How can they write software that allows this to happen.
Should they be making sure there is adequate disk space before the
upgrade.
I have decided to upgrade my Ubuntu 12.04 to 12.10. I had about 4.1GB
space left on /. NOt until the last minute during the install phase did
the upgrade manager ask me to make space on my drive. I started the
software manager and now I can't get out of it back to continuing the
upgrade. It keeps on asking me to repair the package catalogue, and has no
x bar or button to close it, nor can I alt-tab to the updater window. I am
stuck half way through an upgrade and can't get out. I have been a fan of
ubuntu for years but after today I fear I have lost confidence.... Please
someone help. How can they write software that allows this to happen.
Should they be making sure there is adequate disk space before the
upgrade.
Rollover to be loaded with the index page and disappears when iframe is loaded with content from a link
Rollover to be loaded with the index page and disappears when iframe is
loaded with content from a link
I'm having a small issue with iframe and rollover image.
What I want to achieve is when I load this index site it should display a
rollover image(or a slider later on once I know how to do it) in the
middle of the page. I have placed an iframe in the middle of this index
page. This iframe is going to be the target of the horizontal menubar...
How do I make them to co-exist, rollover to be loaded by default and
disappears once the iframe is loaded with content from a link?
I have tried to place a rollover inside the iframe and also now inside the
same div of the iframeBut the result is not good since the rollover image
is not disappearing when loading a link to the iframe:
<div><center>
<a href="recipes/casserole/Sunday Brunch Casserole Registered.htm"
onmouseout="MM_swapImgRestore()"
onmouseover="MM_swapImage('Image1','','recipes/exps10761_TH10059C8.jpg',1)"><img
src="recipes/exps1330_TH2028C39D.jpg" alt="Casserole" width="300"
height="300" id="Image1" /></a>
<iframe name="content" width="1400" height="1000" frameborder="0"
scrolling="auto"></iframe></center>
</div>
Index:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Home Of Recipes</title>
<script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
<link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet"
type="text/css" />
<script type="text/javascript">
function MM_swapImgRestore() { //v3.0
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++)
x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0;
i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document;
if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++)
x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++)
x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array;
for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc)
x.oSrc=x.src; x.src=a[i+2];}
}
</script>
</head>
<body background="food2_indx.jpg"
onload="MM_preloadImages('recipes/exps10761_TH10059C8.jpg')">
<body>
<br/>
<br/>
<div><center>
<a href="recipes/casserole/Sunday Brunch Casserole Registered.htm"
onmouseout="MM_swapImgRestore()"
onmouseover="MM_swapImage('Image1','','recipes/exps10761_TH10059C8.jpg',1)"><img
src="recipes/exps1330_TH2028C39D.jpg" alt="Casserole" width="300"
height="300" id="Image1" /></a>
<iframe name="content" width="1400" height="1000" frameborder="0"
scrolling="auto"></iframe></center>
</div>
<br/>
<br/>
</body>
</html>
loaded with content from a link
I'm having a small issue with iframe and rollover image.
What I want to achieve is when I load this index site it should display a
rollover image(or a slider later on once I know how to do it) in the
middle of the page. I have placed an iframe in the middle of this index
page. This iframe is going to be the target of the horizontal menubar...
How do I make them to co-exist, rollover to be loaded by default and
disappears once the iframe is loaded with content from a link?
I have tried to place a rollover inside the iframe and also now inside the
same div of the iframeBut the result is not good since the rollover image
is not disappearing when loading a link to the iframe:
<div><center>
<a href="recipes/casserole/Sunday Brunch Casserole Registered.htm"
onmouseout="MM_swapImgRestore()"
onmouseover="MM_swapImage('Image1','','recipes/exps10761_TH10059C8.jpg',1)"><img
src="recipes/exps1330_TH2028C39D.jpg" alt="Casserole" width="300"
height="300" id="Image1" /></a>
<iframe name="content" width="1400" height="1000" frameborder="0"
scrolling="auto"></iframe></center>
</div>
Index:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Home Of Recipes</title>
<script src="SpryAssets/SpryMenuBar.js" type="text/javascript"></script>
<link href="SpryAssets/SpryMenuBarHorizontal.css" rel="stylesheet"
type="text/css" />
<script type="text/javascript">
function MM_swapImgRestore() { //v3.0
var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++)
x.src=x.oSrc;
}
function MM_preloadImages() { //v3.0
var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0;
i<a.length; i++)
if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
function MM_findObj(n, d) { //v4.01
var p,i,x; if(!d) d=document;
if((p=n.indexOf("?"))>0&&parent.frames.length) {
d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++)
x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.layers.length;i++)
x=MM_findObj(n,d.layers[i].document);
if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function MM_swapImage() { //v3.0
var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array;
for(i=0;i<(a.length-2);i+=3)
if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc)
x.oSrc=x.src; x.src=a[i+2];}
}
</script>
</head>
<body background="food2_indx.jpg"
onload="MM_preloadImages('recipes/exps10761_TH10059C8.jpg')">
<body>
<br/>
<br/>
<div><center>
<a href="recipes/casserole/Sunday Brunch Casserole Registered.htm"
onmouseout="MM_swapImgRestore()"
onmouseover="MM_swapImage('Image1','','recipes/exps10761_TH10059C8.jpg',1)"><img
src="recipes/exps1330_TH2028C39D.jpg" alt="Casserole" width="300"
height="300" id="Image1" /></a>
<iframe name="content" width="1400" height="1000" frameborder="0"
scrolling="auto"></iframe></center>
</div>
<br/>
<br/>
</body>
</html>
TableView not showing
TableView not showing
I have a very big FXML file that I designed on JavaFx SceneBuilder. When I
try adding a TableView now, the TableView only shows in the JavaFx
SceneBuilder and SceneBuilder's "Preview in Window", but not when I run
the project from netbeans.
Everything else in the scene shows perfectly.
Has anyone ever experienced this problem during development? How do I make
the TableView show when I run the project?
Thank you all in advance.
I have a very big FXML file that I designed on JavaFx SceneBuilder. When I
try adding a TableView now, the TableView only shows in the JavaFx
SceneBuilder and SceneBuilder's "Preview in Window", but not when I run
the project from netbeans.
Everything else in the scene shows perfectly.
Has anyone ever experienced this problem during development? How do I make
the TableView show when I run the project?
Thank you all in advance.
Using SetWindowText via JNA
Using SetWindowText via JNA
Can i call winapi method SetWindowText via JNA or set window title of
external program in some other way? I can get it but i want to set my own
title.
Can i call winapi method SetWindowText via JNA or set window title of
external program in some other way? I can get it but i want to set my own
title.
Tuesday, 1 October 2013
Slider Puzzle problems
Slider Puzzle problems
This is my slider puzzle game. So far it can only do 3x3 games. When I try
and pass the variables l and w (length and width) of the board it doesn't
work. It only works when i set the variables ROWS and COLS as finals. When
I try and change it I get errors. I'm not sure what to do, any help would
be appreciated.
Currently the user can input values that can't do anything at the moment.
When the game is started, a 3x3 board is generated. The user can restart
the game with a different scrambled board but the buttons that solve the
board and the buttons that reset the board to the original state do not
work yet.
public class SlidePuzzle {
public static void main(String[] args)
{
JFrame window = new JFrame("Slide Puzzle");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String length = JOptionPane.showInputDialog("Length");
String width = JOptionPane.showInputDialog("Width");
int l = Integer.parseInt(length);
int w = Integer.parseInt(width);
window.setContentPane(new SlidePuzzleGUI());
window.pack();
window.show();
window.setResizable(false);
}
}
public class SlidePuzzleGUI extends JPanel
{
private GraphicsPanel _puzzleGraphics;
private SlidePuzzleModel _puzzleModel = new SlidePuzzleModel();
This class contains the GUI for the Slider Puzzle
public SlidePuzzleGUI() {
JButton newGameButton = new JButton("New Game");
JButton resetButton = new JButton("Reset");
JButton solveButton = new JButton("I GIVE UP :(");
resetButton.addActionListener(new ResetAction());
newGameButton.addActionListener(new NewGameAction());
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(newGameButton);
controlPanel.add(resetButton);
controlPanel.add(solveButton);
_puzzleGraphics = new GraphicsPanel();
this.setLayout(new BorderLayout());
this.add(controlPanel, BorderLayout.NORTH);
this.add(_puzzleGraphics, BorderLayout.CENTER);
}
This is the graphics panel
class GraphicsPanel extends JPanel implements MouseListener {
private static final int ROWS = 3;
private static final int COLS = 3;
private static final int CELL_SIZE = 80;
private Font _biggerFont;
public GraphicsPanel() {
_biggerFont = new Font("SansSerif", Font.BOLD, CELL_SIZE/2);
this.setPreferredSize(
new Dimension(CELL_SIZE * COLS, CELL_SIZE*ROWS));
this.setBackground(Color.black);
this.addMouseListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
int x = c * CELL_SIZE;
int y = r * CELL_SIZE;
String text = _puzzleModel.getFace(r, c);
if (text != null) {
g.setColor(Color.gray);
g.fillRect(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
g.setColor(Color.black);
g.setFont(_biggerFont);
g.drawString(text, x+20, y+(3*CELL_SIZE)/4);
}
}
}
}
public void mousePressed(MouseEvent e) {
int col = e.getX()/CELL_SIZE;
int row = e.getY()/CELL_SIZE;
if (!_puzzleModel.moveTile(row, col)) {
Toolkit.getDefaultToolkit().beep();
}
this.repaint();
}
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
}
public class NewGameAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
_puzzleModel.reset();
_puzzleGraphics.repaint();
}
}
public class ResetAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
_puzzleModel.tryAgain();
_puzzleGraphics.repaint();
}
}
public class solveAction implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
_puzzleModel.solve();
_puzzleGraphics.repaint();
}
}
}
public class SlidePuzzleModel {
private static final int ROWS = 3;
private static final int COLS = 3;
private Tile[][] _contents;
private Tile[][] _solved;
private Tile _emptyTile;
public SlidePuzzleModel() {
_contents = new Tile[ROWS][COLS];
reset();
}
String getFace(int row, int col) {
return _contents[row][col].getFace();
}
public void reset() {
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
_contents[r][c] = new Tile(r, c, "" + (r*COLS+c+1));
}
}
_emptyTile = _contents[ROWS-1][COLS-1];
_emptyTile.setFace(null);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
exchangeTiles(r, c, (int)(Math.random()*ROWS)
, (int)(Math.random()*COLS));
}
}
}
public void tryAgain()
{
}
public void solve()
{
for (int i = 1; i < ROWS+1;i++)
{
for(int j = 1; j < COLS+1;j++)
{
exchangeTiles(i, j, i, j);
}
}
}
public boolean moveTile(int r, int c) {
return checkEmpty(r, c, -1, 0) || checkEmpty(r, c, 1, 0)
|| checkEmpty(r, c, 0, -1) || checkEmpty(r, c, 0, 1);
}
private boolean checkEmpty(int r, int c, int rdelta, int cdelta) {
int rNeighbor = r + rdelta;
int cNeighbor = c + cdelta;
if (isLegalRowCol(rNeighbor, cNeighbor)
&& _contents[rNeighbor][cNeighbor] == _emptyTile) {
exchangeTiles(r, c, rNeighbor, cNeighbor);
return true;
}
return false;
}
public boolean isLegalRowCol(int r, int c) {
return r>=0 && r<ROWS && c>=0 && c<COLS;
}
private void exchangeTiles(int r1, int c1, int r2, int c2) {
Tile temp = _contents[r1][c1];
_contents[r1][c1] = _contents[r2][c2];
_contents[r2][c2] = temp;
}
public boolean isGameOver() {
for (int r=0; r<ROWS; r++) {
for (int c=0; c<ROWS; c++) {
Tile trc = _contents[r][c];
return trc.isInFinalPosition(r, c);
}
}
return true;
}
}
class Tile {
private int _row;
private int _col;
private String _face;
public Tile(int row, int col, String face) {
_row = row;
_col = col;
_face = face;
}
public void setFace(String newFace) {
_face = newFace;
}
public String getFace() {
return _face;
}
public boolean isInFinalPosition(int r, int c) {
return r==_row && c==_col;
}
}
How would I make it so that the user can specify dimensions of the game
board?
EDIT public class SlidePuzzle {
public static void main(String[] args)
{
JFrame window = new JFrame("Slide Puzzle");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String length = JOptionPane.showInputDialog("Length");
String width = JOptionPane.showInputDialog("Width");
int l = Integer.parseInt(length);
int w = Integer.parseInt(width);
window.setContentPane(new SlidePuzzleGUI());
window.pack();
window.show();
window.setResizable(false);
}
} public class SlidePuzzleGUI extends JPanel {
private GraphicsPanel _puzzleGraphics;
private SlidePuzzleModel _puzzleModel = new SlidePuzzleModel();
public SlidePuzzleGUI(int l, int w) {
JButton newGameButton = new JButton("New Game");
JButton resetButton = new JButton("Reset");
JButton solveButton = new JButton("I GIVE UP :(");
resetButton.addActionListener(new ResetAction());
newGameButton.addActionListener(new NewGameAction());
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(newGameButton);
controlPanel.add(resetButton);
controlPanel.add(solveButton);
_puzzleGraphics = new GraphicsPanel(l,w);
this.setLayout(new BorderLayout());
this.add(controlPanel, BorderLayout.NORTH);
this.add(_puzzleGraphics, BorderLayout.CENTER);
}
class GraphicsPanel extends JPanel implements MouseListener {
private int ROWS;
private int COLS;
private static final int CELL_SIZE = 80;
private Font _biggerFont;
public GraphicsPanel(int l, int w) {
_biggerFont = new Font("SansSerif", Font.BOLD, CELL_SIZE/2);
this.setPreferredSize(
new Dimension(CELL_SIZE * COLS, CELL_SIZE*ROWS));
this.setBackground(Color.black);
this.addMouseListener(this);
ROWS = l;
COLS = w;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
int x = c * CELL_SIZE;
int y = r * CELL_SIZE;
String text = _puzzleModel.getFace(r, c);
if (text != null) {
g.setColor(Color.gray);
g.fillRect(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
g.setColor(Color.black);
g.setFont(_biggerFont);
g.drawString(text, x+20, y+(3*CELL_SIZE)/4);
}
}
}
}
public void mousePressed(MouseEvent e) {
int col = e.getX()/CELL_SIZE;
int row = e.getY()/CELL_SIZE;
if (!_puzzleModel.moveTile(row, col)) {
Toolkit.getDefaultToolkit().beep();
}
this.repaint();
}
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
}
public class NewGameAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
_puzzleModel.reset();
_puzzleGraphics.repaint();
}
}
public class ResetAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
_puzzleModel.tryAgain();
_puzzleGraphics.repaint();
}
}
public class solveAction implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
_puzzleModel.solve();
_puzzleGraphics.repaint();
}
}
}
This is my slider puzzle game. So far it can only do 3x3 games. When I try
and pass the variables l and w (length and width) of the board it doesn't
work. It only works when i set the variables ROWS and COLS as finals. When
I try and change it I get errors. I'm not sure what to do, any help would
be appreciated.
Currently the user can input values that can't do anything at the moment.
When the game is started, a 3x3 board is generated. The user can restart
the game with a different scrambled board but the buttons that solve the
board and the buttons that reset the board to the original state do not
work yet.
public class SlidePuzzle {
public static void main(String[] args)
{
JFrame window = new JFrame("Slide Puzzle");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String length = JOptionPane.showInputDialog("Length");
String width = JOptionPane.showInputDialog("Width");
int l = Integer.parseInt(length);
int w = Integer.parseInt(width);
window.setContentPane(new SlidePuzzleGUI());
window.pack();
window.show();
window.setResizable(false);
}
}
public class SlidePuzzleGUI extends JPanel
{
private GraphicsPanel _puzzleGraphics;
private SlidePuzzleModel _puzzleModel = new SlidePuzzleModel();
This class contains the GUI for the Slider Puzzle
public SlidePuzzleGUI() {
JButton newGameButton = new JButton("New Game");
JButton resetButton = new JButton("Reset");
JButton solveButton = new JButton("I GIVE UP :(");
resetButton.addActionListener(new ResetAction());
newGameButton.addActionListener(new NewGameAction());
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(newGameButton);
controlPanel.add(resetButton);
controlPanel.add(solveButton);
_puzzleGraphics = new GraphicsPanel();
this.setLayout(new BorderLayout());
this.add(controlPanel, BorderLayout.NORTH);
this.add(_puzzleGraphics, BorderLayout.CENTER);
}
This is the graphics panel
class GraphicsPanel extends JPanel implements MouseListener {
private static final int ROWS = 3;
private static final int COLS = 3;
private static final int CELL_SIZE = 80;
private Font _biggerFont;
public GraphicsPanel() {
_biggerFont = new Font("SansSerif", Font.BOLD, CELL_SIZE/2);
this.setPreferredSize(
new Dimension(CELL_SIZE * COLS, CELL_SIZE*ROWS));
this.setBackground(Color.black);
this.addMouseListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
int x = c * CELL_SIZE;
int y = r * CELL_SIZE;
String text = _puzzleModel.getFace(r, c);
if (text != null) {
g.setColor(Color.gray);
g.fillRect(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
g.setColor(Color.black);
g.setFont(_biggerFont);
g.drawString(text, x+20, y+(3*CELL_SIZE)/4);
}
}
}
}
public void mousePressed(MouseEvent e) {
int col = e.getX()/CELL_SIZE;
int row = e.getY()/CELL_SIZE;
if (!_puzzleModel.moveTile(row, col)) {
Toolkit.getDefaultToolkit().beep();
}
this.repaint();
}
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
}
public class NewGameAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
_puzzleModel.reset();
_puzzleGraphics.repaint();
}
}
public class ResetAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
_puzzleModel.tryAgain();
_puzzleGraphics.repaint();
}
}
public class solveAction implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
_puzzleModel.solve();
_puzzleGraphics.repaint();
}
}
}
public class SlidePuzzleModel {
private static final int ROWS = 3;
private static final int COLS = 3;
private Tile[][] _contents;
private Tile[][] _solved;
private Tile _emptyTile;
public SlidePuzzleModel() {
_contents = new Tile[ROWS][COLS];
reset();
}
String getFace(int row, int col) {
return _contents[row][col].getFace();
}
public void reset() {
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
_contents[r][c] = new Tile(r, c, "" + (r*COLS+c+1));
}
}
_emptyTile = _contents[ROWS-1][COLS-1];
_emptyTile.setFace(null);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
exchangeTiles(r, c, (int)(Math.random()*ROWS)
, (int)(Math.random()*COLS));
}
}
}
public void tryAgain()
{
}
public void solve()
{
for (int i = 1; i < ROWS+1;i++)
{
for(int j = 1; j < COLS+1;j++)
{
exchangeTiles(i, j, i, j);
}
}
}
public boolean moveTile(int r, int c) {
return checkEmpty(r, c, -1, 0) || checkEmpty(r, c, 1, 0)
|| checkEmpty(r, c, 0, -1) || checkEmpty(r, c, 0, 1);
}
private boolean checkEmpty(int r, int c, int rdelta, int cdelta) {
int rNeighbor = r + rdelta;
int cNeighbor = c + cdelta;
if (isLegalRowCol(rNeighbor, cNeighbor)
&& _contents[rNeighbor][cNeighbor] == _emptyTile) {
exchangeTiles(r, c, rNeighbor, cNeighbor);
return true;
}
return false;
}
public boolean isLegalRowCol(int r, int c) {
return r>=0 && r<ROWS && c>=0 && c<COLS;
}
private void exchangeTiles(int r1, int c1, int r2, int c2) {
Tile temp = _contents[r1][c1];
_contents[r1][c1] = _contents[r2][c2];
_contents[r2][c2] = temp;
}
public boolean isGameOver() {
for (int r=0; r<ROWS; r++) {
for (int c=0; c<ROWS; c++) {
Tile trc = _contents[r][c];
return trc.isInFinalPosition(r, c);
}
}
return true;
}
}
class Tile {
private int _row;
private int _col;
private String _face;
public Tile(int row, int col, String face) {
_row = row;
_col = col;
_face = face;
}
public void setFace(String newFace) {
_face = newFace;
}
public String getFace() {
return _face;
}
public boolean isInFinalPosition(int r, int c) {
return r==_row && c==_col;
}
}
How would I make it so that the user can specify dimensions of the game
board?
EDIT public class SlidePuzzle {
public static void main(String[] args)
{
JFrame window = new JFrame("Slide Puzzle");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String length = JOptionPane.showInputDialog("Length");
String width = JOptionPane.showInputDialog("Width");
int l = Integer.parseInt(length);
int w = Integer.parseInt(width);
window.setContentPane(new SlidePuzzleGUI());
window.pack();
window.show();
window.setResizable(false);
}
} public class SlidePuzzleGUI extends JPanel {
private GraphicsPanel _puzzleGraphics;
private SlidePuzzleModel _puzzleModel = new SlidePuzzleModel();
public SlidePuzzleGUI(int l, int w) {
JButton newGameButton = new JButton("New Game");
JButton resetButton = new JButton("Reset");
JButton solveButton = new JButton("I GIVE UP :(");
resetButton.addActionListener(new ResetAction());
newGameButton.addActionListener(new NewGameAction());
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(newGameButton);
controlPanel.add(resetButton);
controlPanel.add(solveButton);
_puzzleGraphics = new GraphicsPanel(l,w);
this.setLayout(new BorderLayout());
this.add(controlPanel, BorderLayout.NORTH);
this.add(_puzzleGraphics, BorderLayout.CENTER);
}
class GraphicsPanel extends JPanel implements MouseListener {
private int ROWS;
private int COLS;
private static final int CELL_SIZE = 80;
private Font _biggerFont;
public GraphicsPanel(int l, int w) {
_biggerFont = new Font("SansSerif", Font.BOLD, CELL_SIZE/2);
this.setPreferredSize(
new Dimension(CELL_SIZE * COLS, CELL_SIZE*ROWS));
this.setBackground(Color.black);
this.addMouseListener(this);
ROWS = l;
COLS = w;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
int x = c * CELL_SIZE;
int y = r * CELL_SIZE;
String text = _puzzleModel.getFace(r, c);
if (text != null) {
g.setColor(Color.gray);
g.fillRect(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
g.setColor(Color.black);
g.setFont(_biggerFont);
g.drawString(text, x+20, y+(3*CELL_SIZE)/4);
}
}
}
}
public void mousePressed(MouseEvent e) {
int col = e.getX()/CELL_SIZE;
int row = e.getY()/CELL_SIZE;
if (!_puzzleModel.moveTile(row, col)) {
Toolkit.getDefaultToolkit().beep();
}
this.repaint();
}
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
}
public class NewGameAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
_puzzleModel.reset();
_puzzleGraphics.repaint();
}
}
public class ResetAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
_puzzleModel.tryAgain();
_puzzleGraphics.repaint();
}
}
public class solveAction implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
_puzzleModel.solve();
_puzzleGraphics.repaint();
}
}
}
Wait for the end of an asynchronous Javascript function to retrieve a result (Deferred ?)
Wait for the end of an asynchronous Javascript function to retrieve a
result (Deferred ?)
Ok guys, I know this topic has already been discussed multiple times, but
I can't find an answer to solve my problem.
So I'm trying to do a simple think : I'm creating a string, like :
distance is : " + CalculateDistance(position); The wanted result is
something like distance is 5kms (8min).
CalculateDistance(position) is a function calling a Google maps API called
DistanceMatrix to calculate distance between two points. The API is
documented here, and the given sample perfectly works. I adapted it like
this :
function CalculateDistance(position)
{
var service = new google.maps.DistanceMatrixService();
var destination = new google.maps.LatLng(/* some lat/lng */);
service.getDistanceMatrix(
{
origins: [position],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK)
{
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var results = response.rows[0].elements;
distanceMatrixResult = results[0].distance.text + " ( " +
results[0].duration.text + " min)";
}
Oh, by the way, distanceMatrixResult is a global variable. In fact, I just
need to get the content of results[0].distance.text (and when I print it
in the console in callback(), the value is OK) and then concatenate the
value with "Distance is". If someone have a smarter solution, it is
welcomed !
The API call is asynchronous, and in my case, distanceMatrixResult is
always empty in the result string. But when I log its value in the
console, distanceMatrixResult value became the good one AFTER the string
was created.
All I want to write is :
• Call CalculateDistance (which call callback asynchronously)
• When callback is ended, concatenate the string with the
distanceMatrixResult value.
I tried some Deferred, like $.done() and $.when().then() but I can't
success...
Can someone help me ?
Thank you !
result (Deferred ?)
Ok guys, I know this topic has already been discussed multiple times, but
I can't find an answer to solve my problem.
So I'm trying to do a simple think : I'm creating a string, like :
distance is : " + CalculateDistance(position); The wanted result is
something like distance is 5kms (8min).
CalculateDistance(position) is a function calling a Google maps API called
DistanceMatrix to calculate distance between two points. The API is
documented here, and the given sample perfectly works. I adapted it like
this :
function CalculateDistance(position)
{
var service = new google.maps.DistanceMatrixService();
var destination = new google.maps.LatLng(/* some lat/lng */);
service.getDistanceMatrix(
{
origins: [position],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
}
function callback(response, status) {
if (status == google.maps.DistanceMatrixStatus.OK)
{
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var results = response.rows[0].elements;
distanceMatrixResult = results[0].distance.text + " ( " +
results[0].duration.text + " min)";
}
Oh, by the way, distanceMatrixResult is a global variable. In fact, I just
need to get the content of results[0].distance.text (and when I print it
in the console in callback(), the value is OK) and then concatenate the
value with "Distance is". If someone have a smarter solution, it is
welcomed !
The API call is asynchronous, and in my case, distanceMatrixResult is
always empty in the result string. But when I log its value in the
console, distanceMatrixResult value became the good one AFTER the string
was created.
All I want to write is :
• Call CalculateDistance (which call callback asynchronously)
• When callback is ended, concatenate the string with the
distanceMatrixResult value.
I tried some Deferred, like $.done() and $.when().then() but I can't
success...
Can someone help me ?
Thank you !
Proof of closed sets being invariant under inverse images by continuous functions
Proof of closed sets being invariant under inverse images by continuous
functions
I am studying the below portion of the proof, part of which confuses me:
Suppose that $f: A \to \mathbb{R}^m$ is continuous. Also, suppose that $E$
is a closed subset of $\mathbb{R}^m$. Let $B = f^{-1} (E)$. Now, we show
that $\overline{B} = B$. Clearly, $f(B) = f(f^{-1}(E)) \subseteq E$.
Further, that $A$ is closed implies that the closure of any subset C of A
is contained in A $ \\ $
Thus, if $x \in \overline{B}$, then \begin{equation} f(x) \in
f(\overline{B}) \subset \overline{f(B)} \subset \overline{E} = E \nonumber
\end{equation} Thus, $x \in f^{-1} (E) = B$. Therefore, $\overline{B}
\subset B$, and by Theorem 8.32 (i), $B \subset \overline{B}$. Thus $B =
\overline{B}$. Thus, $B$ is closed.
My question is, how do we know that $f(\overline{B}) \subset
\overline{f(B)}$?
functions
I am studying the below portion of the proof, part of which confuses me:
Suppose that $f: A \to \mathbb{R}^m$ is continuous. Also, suppose that $E$
is a closed subset of $\mathbb{R}^m$. Let $B = f^{-1} (E)$. Now, we show
that $\overline{B} = B$. Clearly, $f(B) = f(f^{-1}(E)) \subseteq E$.
Further, that $A$ is closed implies that the closure of any subset C of A
is contained in A $ \\ $
Thus, if $x \in \overline{B}$, then \begin{equation} f(x) \in
f(\overline{B}) \subset \overline{f(B)} \subset \overline{E} = E \nonumber
\end{equation} Thus, $x \in f^{-1} (E) = B$. Therefore, $\overline{B}
\subset B$, and by Theorem 8.32 (i), $B \subset \overline{B}$. Thus $B =
\overline{B}$. Thus, $B$ is closed.
My question is, how do we know that $f(\overline{B}) \subset
\overline{f(B)}$?
While Checking the expiry date of newly installed ssl it showing custom errr?
While Checking the expiry date of newly installed ssl it showing custom errr?
Am fully new to this site before setting this question as duplicate or
hold read this.
I am just installing sslcertificate which is in .pem for enabling
APplePush Notification but the newly installed .pem file not seemin to be
working proper. when i check for expiry date it showing the following
error
-bash-3.2$ openssl x509 -noout -in xxxxx.pem -enddate
unable to load certificate
11458:error:0906D06C:PEM routines:PEM_read_bio:no start
line:pem_lib.c:647:Expecting: TRUSTED CERTIFICATE
And notable one .pem file doesn't generated by us it is conveted and sent
by third party so say me what could be the problem. Thanks in advance
Am fully new to this site before setting this question as duplicate or
hold read this.
I am just installing sslcertificate which is in .pem for enabling
APplePush Notification but the newly installed .pem file not seemin to be
working proper. when i check for expiry date it showing the following
error
-bash-3.2$ openssl x509 -noout -in xxxxx.pem -enddate
unable to load certificate
11458:error:0906D06C:PEM routines:PEM_read_bio:no start
line:pem_lib.c:647:Expecting: TRUSTED CERTIFICATE
And notable one .pem file doesn't generated by us it is conveted and sent
by third party so say me what could be the problem. Thanks in advance
Monday, 30 September 2013
DNS Server, DHCP Client and Server works fine, but request time out occurs when using MikroTik as an access point for a modem
DNS Server, DHCP Client and Server works fine, but request time out occurs
when using MikroTik as an access point for a modem
I use 2 Mikrotik wireless router, the first one is connected to modem and
it works perfectly (SSID: server-one (hidden)).
Second router ID:
ether1: 192.168.1.1
wlan1: dhcp-client
wlan2: 192.168.2.1
SSID: skywifi
Then, i tried to configure the second router. I set wlan1 to connect to
server-one, as a station and dhcp client and received 192.168.50.124 as
its IP, 192.168.50.254 as its gateway.
I set wlan2 as an ap-bridge, and set it as dhcp server. Then I create a
static route to 0.0.0.0/0 through 192.168.50.254.
Connection OK, DNS to device connecting skywifi works perfectly, i can
nslookup google.com. The problem is, when i tried to ping google.com, it
always give request time out reply. (Note that I also tried to ping
another host too (Wikipedia,Yahoo, etc). The result is also request time
out.
Any idea why this things happened? Thanks,
when using MikroTik as an access point for a modem
I use 2 Mikrotik wireless router, the first one is connected to modem and
it works perfectly (SSID: server-one (hidden)).
Second router ID:
ether1: 192.168.1.1
wlan1: dhcp-client
wlan2: 192.168.2.1
SSID: skywifi
Then, i tried to configure the second router. I set wlan1 to connect to
server-one, as a station and dhcp client and received 192.168.50.124 as
its IP, 192.168.50.254 as its gateway.
I set wlan2 as an ap-bridge, and set it as dhcp server. Then I create a
static route to 0.0.0.0/0 through 192.168.50.254.
Connection OK, DNS to device connecting skywifi works perfectly, i can
nslookup google.com. The problem is, when i tried to ping google.com, it
always give request time out reply. (Note that I also tried to ping
another host too (Wikipedia,Yahoo, etc). The result is also request time
out.
Any idea why this things happened? Thanks,
Intertext like command in enumerate environment=?iso-8859-1?Q?=3F_=96_tex.stackexchange.com?=
Intertext like command in enumerate environment? – tex.stackexchange.com
I would like to insert some explanatory text between two items of a
numbered list. Is there a command that can do this in the same way as the
\intertext command in an align environment?
I would like to insert some explanatory text between two items of a
numbered list. Is there a command that can do this in the same way as the
\intertext command in an align environment?
Fire a javascript function after jquery autosuggest selection made
Fire a javascript function after jquery autosuggest selection made
I have the jQuery autosuggest working. What i'd like to do though is after
the data is selected from the autosuggest, to be able to fire off a
javascript function. So the user selects the name John Smith and some
other info gets populated with ajax. I have the ajax working, I have the
autosuggest working but can't figure out how to get the autosuggest to
fire off the ajax.
I've tried putting a call in the select portion of the autosuggest.. that
didn't work. was almost as if it was getting ignored. Anyway.. I've looked
around and can't find the answer.
thanks for any help shannon
I have the jQuery autosuggest working. What i'd like to do though is after
the data is selected from the autosuggest, to be able to fire off a
javascript function. So the user selects the name John Smith and some
other info gets populated with ajax. I have the ajax working, I have the
autosuggest working but can't figure out how to get the autosuggest to
fire off the ajax.
I've tried putting a call in the select portion of the autosuggest.. that
didn't work. was almost as if it was getting ignored. Anyway.. I've looked
around and can't find the answer.
thanks for any help shannon
How to log the CPU and network utilization for Android
How to log the CPU and network utilization for Android
I want to get the CPU utilization over time and turn the records into plot
diagrams. I have surveyed some method for instant utilization, like shell
command top, dumpsys, and APPs TaskSpy.
Usage: top [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s
sort_column ] [ -t ] [ -h ]
-m num Maximum number of processes to display.
-n num Updates to show before exiting.
-d num Seconds to wait between updates.
-s col Column to sort by (cpu,vss,rss,thr).
-t Show threads instead of processes.
-h Display this help screen.
dumpsys
I want to customize the chart like TaskSpy and add some details to
analysis. It will be better to analysis on PC/MAC. Can I do these by adb
shell command?
I want to get the CPU utilization over time and turn the records into plot
diagrams. I have surveyed some method for instant utilization, like shell
command top, dumpsys, and APPs TaskSpy.
Usage: top [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s
sort_column ] [ -t ] [ -h ]
-m num Maximum number of processes to display.
-n num Updates to show before exiting.
-d num Seconds to wait between updates.
-s col Column to sort by (cpu,vss,rss,thr).
-t Show threads instead of processes.
-h Display this help screen.
dumpsys
I want to customize the chart like TaskSpy and add some details to
analysis. It will be better to analysis on PC/MAC. Can I do these by adb
shell command?
Sunday, 29 September 2013
How to check out code from local git directory
How to check out code from local git directory
I downloaded a source code package. It is nearly 3GB. But it is a empty
directory and just contains a .git directory. How can I check out code
from it?
I downloaded a source code package. It is nearly 3GB. But it is a empty
directory and just contains a .git directory. How can I check out code
from it?
A call to PInvoke function has unbalanced the stack
A call to PInvoke function has unbalanced the stack
Making a function call to .NET 4 to native code is resulting in the
following exception:
A call to PInvoke function has unbalanced the stack. This is likely
because the managed PInvoke signature does not match the unmanaged target
signature. Check that the calling convention and parameters of the PInvoke
signature match the target unmanaged signature.
Here is my definition in Native Code:
typedef void ( CALLBACK* CB_DOWNLOADING )
(
ULONG, // secs elapsed
LPARAM, // custom callback param
LPBOOL // abort?
);
FETCH_API HttpFetchW
(
LPCWSTR url,
IStream** retval,
LPCWSTR usrname = NULL,
LPCWSTR pwd = NULL,
BOOL unzip = TRUE,
CB_DOWNLOADING cb = NULL,
LPARAM cb_param = 0,
LPWSTR ctype = NULL,
ULONG ctypelen = 0
);
Here is the .NET counterpart:
[DllImport(dllPath, CharSet = CharSet.Unicode, SetLastError = true,
CallingConvention = CallingConvention.Cdecl)]
internal static extern FETCH HttpFetchW
(
[MarshalAs(UnmanagedType.LPWStr)]
string url,
out System.Runtime.InteropServices.ComTypes.IStream retval,
[MarshalAs(UnmanagedType.LPWStr)]
string usrname,
[MarshalAs(UnmanagedType.LPWStr)]
string pwd,
bool unzip,
dlgDownloadingCB cb,
IntPtr cb_param,
[MarshalAs(UnmanagedType.LPWStr)]
string ctype,
ulong ctypelen
);
Where FETCH is an enum.
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
internal delegate void dlgDownloadingCB(ulong elapsedSec, IntPtr
lParam, bool abort);
internal static void DownloadingCB(ulong elapsedSec, IntPtr lParam, bool
abort)
{
// Console.WriteLine("elapsedSec = " + elapsedSec.ToString());
}
Can anyone suggest an alternative within the .NET 4?
Thank you very much for your help.
Making a function call to .NET 4 to native code is resulting in the
following exception:
A call to PInvoke function has unbalanced the stack. This is likely
because the managed PInvoke signature does not match the unmanaged target
signature. Check that the calling convention and parameters of the PInvoke
signature match the target unmanaged signature.
Here is my definition in Native Code:
typedef void ( CALLBACK* CB_DOWNLOADING )
(
ULONG, // secs elapsed
LPARAM, // custom callback param
LPBOOL // abort?
);
FETCH_API HttpFetchW
(
LPCWSTR url,
IStream** retval,
LPCWSTR usrname = NULL,
LPCWSTR pwd = NULL,
BOOL unzip = TRUE,
CB_DOWNLOADING cb = NULL,
LPARAM cb_param = 0,
LPWSTR ctype = NULL,
ULONG ctypelen = 0
);
Here is the .NET counterpart:
[DllImport(dllPath, CharSet = CharSet.Unicode, SetLastError = true,
CallingConvention = CallingConvention.Cdecl)]
internal static extern FETCH HttpFetchW
(
[MarshalAs(UnmanagedType.LPWStr)]
string url,
out System.Runtime.InteropServices.ComTypes.IStream retval,
[MarshalAs(UnmanagedType.LPWStr)]
string usrname,
[MarshalAs(UnmanagedType.LPWStr)]
string pwd,
bool unzip,
dlgDownloadingCB cb,
IntPtr cb_param,
[MarshalAs(UnmanagedType.LPWStr)]
string ctype,
ulong ctypelen
);
Where FETCH is an enum.
[UnmanagedFunctionPointerAttribute(CallingConvention.Cdecl)]
internal delegate void dlgDownloadingCB(ulong elapsedSec, IntPtr
lParam, bool abort);
internal static void DownloadingCB(ulong elapsedSec, IntPtr lParam, bool
abort)
{
// Console.WriteLine("elapsedSec = " + elapsedSec.ToString());
}
Can anyone suggest an alternative within the .NET 4?
Thank you very much for your help.
How to implement double indexing in a 2D sparse scipy matrix?
How to implement double indexing in a 2D sparse scipy matrix?
Suppose I have a 2D sparse matrix M representing the results of 2-on-2
basketball matches. I want to use address the elements of the matrix using
double-indexing : Element M[i,j][k,l] will represent the score of the game
played by a team of players i and j against team k and l. Thus, each
column/row is specified by two numbers instead of one. Note that this is
not a 4D matrix. I'm looking for a way to do this with a sparse SciPy
matrix in order to be able to perform various matrix-related calculations
(eigenvalues/vectors, etc).
Suppose I have a 2D sparse matrix M representing the results of 2-on-2
basketball matches. I want to use address the elements of the matrix using
double-indexing : Element M[i,j][k,l] will represent the score of the game
played by a team of players i and j against team k and l. Thus, each
column/row is specified by two numbers instead of one. Note that this is
not a 4D matrix. I'm looking for a way to do this with a sparse SciPy
matrix in order to be able to perform various matrix-related calculations
(eigenvalues/vectors, etc).
converting [RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA] to [RRRRRGGGGGBBBBBA]
converting [RRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA] to [RRRRRGGGGGBBBBBA]
I am writing an ImageEncoder that writes a TGA image. I have been able to
successfully write the TGA file, but instead of ending up with
[RRRRRGGGGGBBBBBA] I get [RGBBBBBA] here is the relevant code:
int lastRow = minY + height;
for (int row = minY; row < lastRow; row += 8) {
int rows = Math.min(8, lastRow - row);
int size = rows * width * numBands;
// Grab the pixels
Raster src = im.getData(new Rectangle(minX, row, width, rows));
src.getPixels(minX, row, width, rows, pixels);
for (int i = 0; i < size; i++) {
//output.write(pixels[i] & 0xFF);
short o = (short) pixels[i];
byte[] reo = new byte[2];
reo[0] = (byte) (o & 0xff);
reo[1] = (byte) ((o >> 8) & 0xff);
output.write(reo);
}
}
I am writing an ImageEncoder that writes a TGA image. I have been able to
successfully write the TGA file, but instead of ending up with
[RRRRRGGGGGBBBBBA] I get [RGBBBBBA] here is the relevant code:
int lastRow = minY + height;
for (int row = minY; row < lastRow; row += 8) {
int rows = Math.min(8, lastRow - row);
int size = rows * width * numBands;
// Grab the pixels
Raster src = im.getData(new Rectangle(minX, row, width, rows));
src.getPixels(minX, row, width, rows, pixels);
for (int i = 0; i < size; i++) {
//output.write(pixels[i] & 0xFF);
short o = (short) pixels[i];
byte[] reo = new byte[2];
reo[0] = (byte) (o & 0xff);
reo[1] = (byte) ((o >> 8) & 0xff);
output.write(reo);
}
}
Saturday, 28 September 2013
convergence with a bounded sequence and a sequence that tends to zero
convergence with a bounded sequence and a sequence that tends to zero
how to prove that if $\sum k_n$ converges absolutely and $Lim_{n \to
+\infty}c_n = 0$ (where $c_n$ is a sequence) then $ \sum k_n c_n$
converges absolutely
how to prove that if $\sum k_n$ converges absolutely and $Lim_{n \to
+\infty}c_n = 0$ (where $c_n$ is a sequence) then $ \sum k_n c_n$
converges absolutely
Send recurring email based on date using PHP
Send recurring email based on date using PHP
I am not sure where to begin setting up an automatic recurring email
reminder app. I currently have a form that inserts data into a msyql
database.
<form method="post" action="save.php">
<p>
<label for="name">Full Name</label><br />
<input type="text" name="name" data-h5-errorid="error-name" required />
<span id="error-name" class="error">Please enter a full name</span>
</p>
<p>
<label for="address">Address (Street Address Only)</label><br />
<input type="text" name="address" data-h5-errorid="error-address"
required />
<span id="error-address" class="error">Please enter an address</span>
</p>
<p>
<label for="email">Email</label><br />
<input type="email" name="email" data-h5-errorid="error-email"
required />
<span id="error-email" class="error">Please enter a valid email
address</span>
</p>
<p>
<label for="date">Date of Service</label><br />
<input id="date" type="text" data-h5-errorid="error-service"
name="date" required />
<span id="error-service" class="error">Please choose a date</span>
</p>
<p>
<label for="reminder">Reminder</label><br />
<select name="reminder">
<option value="1">30 Days</option>
<option value="2">60 Days</option>
<option value="3">Semiannual</option>
<option value="4">Annual</option>
</select>
</p>
<p>
<label for="notes">Notes on Service</label><br />
<textarea name="notes" rows="15"></textarea>
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
I am storing all fields in the database and have that working properly
using http://medoo.in/. How do I go about creating a PHP script to send a
recurring email based on the Service Date and the selected Reminder (every
30 days, 60 days, semianually, annually)? I was thinking of using PHP
mailer to send the actual emails and running a daily cron job.
I am not sure where to begin setting up an automatic recurring email
reminder app. I currently have a form that inserts data into a msyql
database.
<form method="post" action="save.php">
<p>
<label for="name">Full Name</label><br />
<input type="text" name="name" data-h5-errorid="error-name" required />
<span id="error-name" class="error">Please enter a full name</span>
</p>
<p>
<label for="address">Address (Street Address Only)</label><br />
<input type="text" name="address" data-h5-errorid="error-address"
required />
<span id="error-address" class="error">Please enter an address</span>
</p>
<p>
<label for="email">Email</label><br />
<input type="email" name="email" data-h5-errorid="error-email"
required />
<span id="error-email" class="error">Please enter a valid email
address</span>
</p>
<p>
<label for="date">Date of Service</label><br />
<input id="date" type="text" data-h5-errorid="error-service"
name="date" required />
<span id="error-service" class="error">Please choose a date</span>
</p>
<p>
<label for="reminder">Reminder</label><br />
<select name="reminder">
<option value="1">30 Days</option>
<option value="2">60 Days</option>
<option value="3">Semiannual</option>
<option value="4">Annual</option>
</select>
</p>
<p>
<label for="notes">Notes on Service</label><br />
<textarea name="notes" rows="15"></textarea>
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
I am storing all fields in the database and have that working properly
using http://medoo.in/. How do I go about creating a PHP script to send a
recurring email based on the Service Date and the selected Reminder (every
30 days, 60 days, semianually, annually)? I was thinking of using PHP
mailer to send the actual emails and running a daily cron job.
Round a Value after While Loop in PHP
Round a Value after While Loop in PHP
Hey with the following code I am trying to round the variable $CelNum, and
since I am new to PHP I am unsure of how to do it correctly if you could
help me I would appreciate it.
<head>
<title>Temp Conversion</title>
<meta http-equiv="content-type" content="text/html;
charset=iso-8859-1" />
</head>
<body>
<?
$FarNum = 0;
$CelNum = 0;
while ($FarNum <= 100)
{
$CelNum = ($FarNum - 32)*5/9;
echo "<p>$FarNum = $CelNum</p>";
$FarNum++;
}
Hey with the following code I am trying to round the variable $CelNum, and
since I am new to PHP I am unsure of how to do it correctly if you could
help me I would appreciate it.
<head>
<title>Temp Conversion</title>
<meta http-equiv="content-type" content="text/html;
charset=iso-8859-1" />
</head>
<body>
<?
$FarNum = 0;
$CelNum = 0;
while ($FarNum <= 100)
{
$CelNum = ($FarNum - 32)*5/9;
echo "<p>$FarNum = $CelNum</p>";
$FarNum++;
}
TreeView binding from XML by ID
TreeView binding from XML by ID
I'm using WPF.(MVVM pattern) I want to make hierarchical tree using
TreeView. Data from XML. But XML structure is not hierarchical actually.
Nodes binds by ID. XML looks like the following:
<root>
<node>
<Id>1</Id>
<ParentId>-1</ParentId>
<Name>ROOT</Name>
</node>
<node>
<Id>2</Id>
<ParentId>1</ParentId>
<Name>NODE</Name>
</node>
</root>
What should i use to do this? It will be great if you show me any simple
example.
And the second question. How can i get nodes dinamically? That is when i
run the application only root is loading.
Thanks in advance.
I'm using WPF.(MVVM pattern) I want to make hierarchical tree using
TreeView. Data from XML. But XML structure is not hierarchical actually.
Nodes binds by ID. XML looks like the following:
<root>
<node>
<Id>1</Id>
<ParentId>-1</ParentId>
<Name>ROOT</Name>
</node>
<node>
<Id>2</Id>
<ParentId>1</ParentId>
<Name>NODE</Name>
</node>
</root>
What should i use to do this? It will be great if you show me any simple
example.
And the second question. How can i get nodes dinamically? That is when i
run the application only root is loading.
Thanks in advance.
Friday, 27 September 2013
Use Python's `timeit` from a program but functioning the same way as the command line?
Use Python's `timeit` from a program but functioning the same way as the
command line?
For instance, documentation says:
Note however that timeit will automatically determine the number of
repetitions only when the command-line interface is used.
Is there a way to call it from within a Python script and have the number
of repetitions be determined automatically, with only the shortest number
returned?
command line?
For instance, documentation says:
Note however that timeit will automatically determine the number of
repetitions only when the command-line interface is used.
Is there a way to call it from within a Python script and have the number
of repetitions be determined automatically, with only the shortest number
returned?
jacob - Could not initialize class com.jacob.com.ComThread
jacob - Could not initialize class com.jacob.com.ComThread
I have jacob.jar in my class path and the jar also contains
ComThread.class but when I run the application I am getting the following
exception. Any idea how to resolve this?
java.lang.NoClassDefFoundError: Could not initialize class
com.jacob.com.ComThread
at
org.apache.jsp.WEB_002dINF.view.perc.jemrreport_jsp._jspService(jemrreport_jsp.java:226)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at
org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at
org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at
org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at
org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:159)
I have jacob.jar in my class path and the jar also contains
ComThread.class but when I run the application I am getting the following
exception. Any idea how to resolve this?
java.lang.NoClassDefFoundError: Could not initialize class
com.jacob.com.ComThread
at
org.apache.jsp.WEB_002dINF.view.perc.jemrreport_jsp._jspService(jemrreport_jsp.java:226)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at
org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at
org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at
org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at
org.apache.struts2.dispatcher.ServletDispatcherResult.doExecute(ServletDispatcherResult.java:159)
Using column name when using SqlDataReader.IsDBNull
Using column name when using SqlDataReader.IsDBNull
Hello I have got this code which reads data from SQL DB.
I don't know how should I edit it so I can use original column name and
not column index.
string query = "SELECT * FROM zajezd WHERE event='" +
thisrow+ "' AND year='" + klientClass.Year() + "'";
SqlCommand cmd= new SqlCommand(query, spojeni);
spojeni.Open();
SqlDataReader read= cmd.ExecuteReader();
if (read.Read())
{
maskedTextBox2.Text = read.IsDBNull(24) ? string.Empty :
read.GetDateTime(24).ToString("MM/dd/yyyy");
Thanks in advance.
Hello I have got this code which reads data from SQL DB.
I don't know how should I edit it so I can use original column name and
not column index.
string query = "SELECT * FROM zajezd WHERE event='" +
thisrow+ "' AND year='" + klientClass.Year() + "'";
SqlCommand cmd= new SqlCommand(query, spojeni);
spojeni.Open();
SqlDataReader read= cmd.ExecuteReader();
if (read.Read())
{
maskedTextBox2.Text = read.IsDBNull(24) ? string.Empty :
read.GetDateTime(24).ToString("MM/dd/yyyy");
Thanks in advance.
PHP & SQL - get results from db where date is today
PHP & SQL - get results from db where date is today
i'm trying to do the following thing: In my Database, I have rows with
time in each one (using time() function). For example: 1380300397. Now,
I'd like to build a query that gets the rows from the current day. I've
tried this query with no success:
SELECT `id`,DATE_FORMAT(`time`, '%Y-%m-%d') FROM `facts`
WHERE `app` = 1 AND DATE(`time`) = CURDATE()
What am I doing wrong? Thanks!
i'm trying to do the following thing: In my Database, I have rows with
time in each one (using time() function). For example: 1380300397. Now,
I'd like to build a query that gets the rows from the current day. I've
tried this query with no success:
SELECT `id`,DATE_FORMAT(`time`, '%Y-%m-%d') FROM `facts`
WHERE `app` = 1 AND DATE(`time`) = CURDATE()
What am I doing wrong? Thanks!
Data Source SQL Command from Variable using default value instead of updated value
Data Source SQL Command from Variable using default value instead of
updated value
I have four dynamically assigned variables in my package. Each one is
populated using a query similar to this:
select 'SELECT * FROM SHARE_DM.MDM_ORG_CLASSIFICATIONS WHERE LAST_UPD_DATE
>= '''
+ (select convert(nvarchar(50), coalesce(max(last_upd_date),
cast('1/1/1900' as datetime)), 106) from MDM_ORG_CLASSIFICATIONS)
+ '''' sql
The default queries are defined like this:
SELECT * FROM SHARE_DM.MDM_ORG_CLASSIFICATIONS WHERE LAST_UPD_DATE >= '01
Jan 1900'
(I'm building the sql like this because I'm using Oracle data connections
and the parameter parsing doesn't work properly, where this technique has
worked before)
The output sql comes out like this:
SELECT * FROM SHARE_DM.MDM_ORG_CLASSIFICATIONS WHERE LAST_UPD_DATE >= '26
Sep 2013'
I have validated that my variables are being updated using message boxes
in script components. When I run the queries manually against Oracle, I
get very small result sets, as expected. However, when I run the package,
I get full result sets as if the default value of 1/1/1900 was being used
instead of the updated variable.
Each variable is set to EvaluateAsExpression False.
Comparing the operation in this package vs. a different package where I do
the same kind of operation, I'm not seeing any obvious differences -
except for one thing - in the other package I list each column in the
select statement, whereas in here I use select *.
Why isn't my OLE DB Source updating with the updated SQL from the variable?
Edit: Thinking maybe the select * was the issue, I updated one of them to
use explicit column names. No change.
updated value
I have four dynamically assigned variables in my package. Each one is
populated using a query similar to this:
select 'SELECT * FROM SHARE_DM.MDM_ORG_CLASSIFICATIONS WHERE LAST_UPD_DATE
>= '''
+ (select convert(nvarchar(50), coalesce(max(last_upd_date),
cast('1/1/1900' as datetime)), 106) from MDM_ORG_CLASSIFICATIONS)
+ '''' sql
The default queries are defined like this:
SELECT * FROM SHARE_DM.MDM_ORG_CLASSIFICATIONS WHERE LAST_UPD_DATE >= '01
Jan 1900'
(I'm building the sql like this because I'm using Oracle data connections
and the parameter parsing doesn't work properly, where this technique has
worked before)
The output sql comes out like this:
SELECT * FROM SHARE_DM.MDM_ORG_CLASSIFICATIONS WHERE LAST_UPD_DATE >= '26
Sep 2013'
I have validated that my variables are being updated using message boxes
in script components. When I run the queries manually against Oracle, I
get very small result sets, as expected. However, when I run the package,
I get full result sets as if the default value of 1/1/1900 was being used
instead of the updated variable.
Each variable is set to EvaluateAsExpression False.
Comparing the operation in this package vs. a different package where I do
the same kind of operation, I'm not seeing any obvious differences -
except for one thing - in the other package I list each column in the
select statement, whereas in here I use select *.
Why isn't my OLE DB Source updating with the updated SQL from the variable?
Edit: Thinking maybe the select * was the issue, I updated one of them to
use explicit column names. No change.
java.lang.IllegalStateException: System services not available to Activities before onCreate() with ArrayAdapter
java.lang.IllegalStateException: System services not available to
Activities before onCreate() with ArrayAdapter
I am trying to run a ListActivity, which takes an array of filenames,
which are to be inserted into the database. This is done by insert() in
the following code. I am getting IllegalStateException at
ArrayAdapter<String>. If I am calling the insert() function from another
class. So, I am unable to define ArrayAdapter in the onCreate() method.
Please see the following code, which is defining insert() method -
public class FileEvent extends ListActivity implements ObserverActivity{
public static final String PREFS_NAME = "MyPreferencesFile";
public String filename;
public String path;
MyFileObserver myFileObserver;
public adapter info = new adapter(this);
ArrayAdapter<String> adapter;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
listView = (ListView) findViewById(android.R.id.list);
setContentView(R.layout.fileeventlist);
Bundle bundle = getIntent().getExtras();
myFileObserver = new
MyFileObserver("/storage/sdcard/DCIM/SAMPLE_IMAGES/");
myFileObserver.registerObserver(this);
myFileObserver.startWatching();
/* String var_from_prev_intent = bundle.getString("path");
insert(var_from_prev_intent);
SharedPreferences settings = getSharedPreferences (PREFS_NAME,0);
String newpath = "";
this.path = settings.getString("name",newpath);
Log.v("New path in FileEvent : ",this.path);*/
}
protected void onPause(){
myFileObserver.stopWatching();
myFileObserver.unregisterObserver(this);
}
protected void onResume(){
myFileObserver.registerObserver(this);
myFileObserver.startWatching();
}
public void insert(String path) {
// TODO Auto-generated method stub
//try{
Log.v("FileName to insert : ",path);
Log.v("a3","a3");
this.filename = path;
Log.v("a4","a4");
int rowcount = info.getrowcountofpersons();
Log.v("a5","a5");
Log.v("rowcount in new list onCreate: ",
""+info.getrowcountofpersons()+"");
Log.v("a6","a6");
String[] values = new String[rowcount];
Log.v("a7","a7");
for(int i =1;i<=rowcount;i++)
{
values[i-1]=info.getPersonList(i);
//Toast.makeText(getApplicationContext(), values[i-1],
Toast.LENGTH_LONG).show();
System.out.println("in for loop now"+values[i-1]);
}
Log.v("a8","a8");
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
Log.v("a9","a9");
Log.v("a10","a10");
listView.setItemsCanFocus(false);
Log.v("a11","a11");
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Log.v("a12","a12");
// Assign adapter to List
setListAdapter(adapter);
// new Bullet(info).execute((Void)null);
Log.v("a13","a13");
/*}
catch (Exception e)
{
Log.v("Error in insert() definition FileEvent.java :
",e.toString());
}*/
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// try{
Log.v("a14","a14");
super.onListItemClick(l, v, position, id);
Log.v("a15","a15");
// ListView Clicked item index
int itemPosition = position;
Log.v("a16","a16");
// ListView Clicked item value
String itemValue = (String) l.getItemAtPosition(position);
Log.v("a17","a17");
// content.setText("Click : \n Position :"+itemPosition+" \n
ListItem : " +itemValue);
String personname = itemValue;
Log.v("a18","a18");
try
{
System.out.println("paths in FileEvent : "+filename);
info.insert(filename,personname);
Log.v("a19","a19");
}
catch(Exception e)
{
Log.v("a20","a20");
e.printStackTrace();
Log.v("a21","a21");
}
Log.v("a22","a22");
/* }
catch (Exception e)
{
Log.v("Error in insert() definition FileEvent.java :
",e.toString());
}
*/
}
And the following logcat I am getting, when I run the code -
09-27 06:37:23.269: A/FileObserver(2284): Unhandled exception in
FileObserver com.example.sample_fileobserver.MyFileObserver@b11955a0
09-27 06:37:23.269: A/FileObserver(2284): java.lang.IllegalStateException:
System services not available to Activities before onCreate()
09-27 06:37:23.269: A/FileObserver(2284): at
android.app.Activity.getSystemService(Activity.java:4492)
09-27 06:37:23.269: A/FileObserver(2284): at
android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
09-27 06:37:23.269: A/FileObserver(2284): at
android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
09-27 06:37:23.269: A/FileObserver(2284): at
com.example.sample_fileobserver.FileEvent.insert(FileEvent.java:76)
09-27 06:37:23.269: A/FileObserver(2284): at
com.example.sample_fileobserver.MyFileObserver.onEvent(MyFileObserver.java:59)
09-27 06:37:23.269: A/FileObserver(2284): at
android.os.FileObserver$ObserverThread.onEvent(FileObserver.java:125)
09-27 06:37:23.269: A/FileObserver(2284): at
android.os.FileObserver$ObserverThread.observe(Native Method)
09-27 06:37:23.269: A/FileObserver(2284): at
android.os.FileObserver$ObserverThread.run(FileObserver.java:88)
Please tell me where I made mistake.
Thanks in advance.
Activities before onCreate() with ArrayAdapter
I am trying to run a ListActivity, which takes an array of filenames,
which are to be inserted into the database. This is done by insert() in
the following code. I am getting IllegalStateException at
ArrayAdapter<String>. If I am calling the insert() function from another
class. So, I am unable to define ArrayAdapter in the onCreate() method.
Please see the following code, which is defining insert() method -
public class FileEvent extends ListActivity implements ObserverActivity{
public static final String PREFS_NAME = "MyPreferencesFile";
public String filename;
public String path;
MyFileObserver myFileObserver;
public adapter info = new adapter(this);
ArrayAdapter<String> adapter;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
listView = (ListView) findViewById(android.R.id.list);
setContentView(R.layout.fileeventlist);
Bundle bundle = getIntent().getExtras();
myFileObserver = new
MyFileObserver("/storage/sdcard/DCIM/SAMPLE_IMAGES/");
myFileObserver.registerObserver(this);
myFileObserver.startWatching();
/* String var_from_prev_intent = bundle.getString("path");
insert(var_from_prev_intent);
SharedPreferences settings = getSharedPreferences (PREFS_NAME,0);
String newpath = "";
this.path = settings.getString("name",newpath);
Log.v("New path in FileEvent : ",this.path);*/
}
protected void onPause(){
myFileObserver.stopWatching();
myFileObserver.unregisterObserver(this);
}
protected void onResume(){
myFileObserver.registerObserver(this);
myFileObserver.startWatching();
}
public void insert(String path) {
// TODO Auto-generated method stub
//try{
Log.v("FileName to insert : ",path);
Log.v("a3","a3");
this.filename = path;
Log.v("a4","a4");
int rowcount = info.getrowcountofpersons();
Log.v("a5","a5");
Log.v("rowcount in new list onCreate: ",
""+info.getrowcountofpersons()+"");
Log.v("a6","a6");
String[] values = new String[rowcount];
Log.v("a7","a7");
for(int i =1;i<=rowcount;i++)
{
values[i-1]=info.getPersonList(i);
//Toast.makeText(getApplicationContext(), values[i-1],
Toast.LENGTH_LONG).show();
System.out.println("in for loop now"+values[i-1]);
}
Log.v("a8","a8");
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
Log.v("a9","a9");
Log.v("a10","a10");
listView.setItemsCanFocus(false);
Log.v("a11","a11");
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Log.v("a12","a12");
// Assign adapter to List
setListAdapter(adapter);
// new Bullet(info).execute((Void)null);
Log.v("a13","a13");
/*}
catch (Exception e)
{
Log.v("Error in insert() definition FileEvent.java :
",e.toString());
}*/
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// try{
Log.v("a14","a14");
super.onListItemClick(l, v, position, id);
Log.v("a15","a15");
// ListView Clicked item index
int itemPosition = position;
Log.v("a16","a16");
// ListView Clicked item value
String itemValue = (String) l.getItemAtPosition(position);
Log.v("a17","a17");
// content.setText("Click : \n Position :"+itemPosition+" \n
ListItem : " +itemValue);
String personname = itemValue;
Log.v("a18","a18");
try
{
System.out.println("paths in FileEvent : "+filename);
info.insert(filename,personname);
Log.v("a19","a19");
}
catch(Exception e)
{
Log.v("a20","a20");
e.printStackTrace();
Log.v("a21","a21");
}
Log.v("a22","a22");
/* }
catch (Exception e)
{
Log.v("Error in insert() definition FileEvent.java :
",e.toString());
}
*/
}
And the following logcat I am getting, when I run the code -
09-27 06:37:23.269: A/FileObserver(2284): Unhandled exception in
FileObserver com.example.sample_fileobserver.MyFileObserver@b11955a0
09-27 06:37:23.269: A/FileObserver(2284): java.lang.IllegalStateException:
System services not available to Activities before onCreate()
09-27 06:37:23.269: A/FileObserver(2284): at
android.app.Activity.getSystemService(Activity.java:4492)
09-27 06:37:23.269: A/FileObserver(2284): at
android.widget.ArrayAdapter.init(ArrayAdapter.java:310)
09-27 06:37:23.269: A/FileObserver(2284): at
android.widget.ArrayAdapter.<init>(ArrayAdapter.java:128)
09-27 06:37:23.269: A/FileObserver(2284): at
com.example.sample_fileobserver.FileEvent.insert(FileEvent.java:76)
09-27 06:37:23.269: A/FileObserver(2284): at
com.example.sample_fileobserver.MyFileObserver.onEvent(MyFileObserver.java:59)
09-27 06:37:23.269: A/FileObserver(2284): at
android.os.FileObserver$ObserverThread.onEvent(FileObserver.java:125)
09-27 06:37:23.269: A/FileObserver(2284): at
android.os.FileObserver$ObserverThread.observe(Native Method)
09-27 06:37:23.269: A/FileObserver(2284): at
android.os.FileObserver$ObserverThread.run(FileObserver.java:88)
Please tell me where I made mistake.
Thanks in advance.
Thursday, 26 September 2013
how can I check which submit button was pressed?
how can I check which submit button was pressed?
I have a two submit buttons set up for form submission. I'd like to know
which submit button was clicked without applying a .click() event to each
one. One more thing I am using ASP.NET MVC 3 and want to get the clicked
button name in Controller.
Here's the setup:
<a class="anchorbutton">
<input type="submit" value="Save" id="Save" class="hrbutton"/>
</a>
<input type="submit" value="Save & Next" id="SaveNext" class="hrbutton
anchorbutton"/>
$('#form').live('submit', function (e)
{
e.preventDefault();
var form = $('#form');
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
$.ajax({
url: 'url',
dataType: "html",
success: function (data) {
$("#div").html(data);
}
});
}
});
return false;
});
[HttpPost]
public JsonResult Post(FormCollection form, string submitButton)
{
}
I have a two submit buttons set up for form submission. I'd like to know
which submit button was clicked without applying a .click() event to each
one. One more thing I am using ASP.NET MVC 3 and want to get the clicked
button name in Controller.
Here's the setup:
<a class="anchorbutton">
<input type="submit" value="Save" id="Save" class="hrbutton"/>
</a>
<input type="submit" value="Save & Next" id="SaveNext" class="hrbutton
anchorbutton"/>
$('#form').live('submit', function (e)
{
e.preventDefault();
var form = $('#form');
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
$.ajax({
url: 'url',
dataType: "html",
success: function (data) {
$("#div").html(data);
}
});
}
});
return false;
});
[HttpPost]
public JsonResult Post(FormCollection form, string submitButton)
{
}
Wednesday, 25 September 2013
In angularjs ng-change="chk(query)" call function when space is hit after typing word
In angularjs ng-change="chk(query)" call function when space is hit after
typing word
I am using following code to take input from user and search the term
the problem is that if I press any word function gets called but when I
press spacebar it is not calling the function so I want if user enters
space then also the function should get called
<input ng-model="query" ng-change="chk(query)" placeholder="Search..">
so please can anyone suggest me with the solution please
Thank you
I tried to use ng-trim="false" but not working
typing word
I am using following code to take input from user and search the term
the problem is that if I press any word function gets called but when I
press spacebar it is not calling the function so I want if user enters
space then also the function should get called
<input ng-model="query" ng-change="chk(query)" placeholder="Search..">
so please can anyone suggest me with the solution please
Thank you
I tried to use ng-trim="false" but not working
Thursday, 19 September 2013
Calling C++ method in QML Error "Cannot Call Method 'x' of null"
Calling C++ method in QML Error "Cannot Call Method 'x' of null"
I'm having some difficuly calling a method from a C++ class in QML. I keep
getting a "Cannot call method 'x' of null" error. Here is my code:
QML:
import QtQuick 2.0
import QtQuick.Controls 1.0
import QtQuick.Window 2.0
import Jane 1.0
ApplicationWindow
{
property MainWindowModel m_Model
...
Button {
id: m_PluralizeButton
text: "Pluralize"
anchors.left: parent.left
anchors.leftMargin: 10
anchors.top: m_OutputRow.bottom
anchors.topMargin: 10
onClicked: m_OutputText.text = m_Model.getPluralization();
}
}
MainWindowModel.h
class MainWindowModel : public QObject
{
Q_OBJECT
public:
MainWindowModel();
~MainWindowModel() {}
Q_INVOKABLE QString getPluralization() const;
private:
};
MainWindoModel.cpp
MainWindowModel::MainWindowModel() :
QObject()
{
}
QString MainWindowModel::getPluralization() const
{
return "Test";
}
Main.cpp
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// Need to register types prior to loading the file.
qmlRegisterType<MainWindowModel>("Jane", 1, 0, "MainWindowModel");
QQmlApplicationEngine engine(QUrl("qrc:/root/QML/MainWindowView.qml"));
QObject* topLevel = engine.rootObjects().value(0);
QQuickWindow* win = qobject_cast<QQuickWindow*>(topLevel);
if (!win)
{
qWarning("Error: not a valid window.");
return -1;
}
win->show();
return a.exec();
}
Any help will be appreciated, thanks.
I'm having some difficuly calling a method from a C++ class in QML. I keep
getting a "Cannot call method 'x' of null" error. Here is my code:
QML:
import QtQuick 2.0
import QtQuick.Controls 1.0
import QtQuick.Window 2.0
import Jane 1.0
ApplicationWindow
{
property MainWindowModel m_Model
...
Button {
id: m_PluralizeButton
text: "Pluralize"
anchors.left: parent.left
anchors.leftMargin: 10
anchors.top: m_OutputRow.bottom
anchors.topMargin: 10
onClicked: m_OutputText.text = m_Model.getPluralization();
}
}
MainWindowModel.h
class MainWindowModel : public QObject
{
Q_OBJECT
public:
MainWindowModel();
~MainWindowModel() {}
Q_INVOKABLE QString getPluralization() const;
private:
};
MainWindoModel.cpp
MainWindowModel::MainWindowModel() :
QObject()
{
}
QString MainWindowModel::getPluralization() const
{
return "Test";
}
Main.cpp
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// Need to register types prior to loading the file.
qmlRegisterType<MainWindowModel>("Jane", 1, 0, "MainWindowModel");
QQmlApplicationEngine engine(QUrl("qrc:/root/QML/MainWindowView.qml"));
QObject* topLevel = engine.rootObjects().value(0);
QQuickWindow* win = qobject_cast<QQuickWindow*>(topLevel);
if (!win)
{
qWarning("Error: not a valid window.");
return -1;
}
win->show();
return a.exec();
}
Any help will be appreciated, thanks.
keep the first part and delete the rest on a specified line using sed
keep the first part and delete the rest on a specified line using sed
I know a line number in a file, wherein I want to keep the first word and
delete the rest till the end of the line. How do I do this using sed ? So
lets say, I want to go to line no 10 in a file, which looks like this -
goodword "blah blah"\
and what i want is
goodword
I have tried this - sed 's/([a-z])./\1/'
But this does it on all the lines in a file. I want it only on one
specified line.
I know a line number in a file, wherein I want to keep the first word and
delete the rest till the end of the line. How do I do this using sed ? So
lets say, I want to go to line no 10 in a file, which looks like this -
goodword "blah blah"\
and what i want is
goodword
I have tried this - sed 's/([a-z])./\1/'
But this does it on all the lines in a file. I want it only on one
specified line.
"This version of JustMock has expired!" after purchasing a license
"This version of JustMock has expired!" after purchasing a license
I recently purchased a license for Telerik JustMock. The Telerik Control
Panel shows JustMock under my list of Purchased products. When I attempt
to run my tests in Visual Studio's Test Explorer with the JustMock Visual
Studio extension enabled I receive an exception saying:
Telerik.JustMockExpiredException : This version of JustMock has expired!
I have uninstalled all the Telerik Visual Studio extensions, uninstalled
everything Telerik via Windows Programs/Features, then re-installed the
control panel and then JustMock yet the problem persists. Of note, when I
re-installed the control panel it remembered my username/password so I'm
guessing there is a configuration file somewhere caching my information
incorrectly.
A possible root cause of this problem is that I was trialing JustMock
under my personal email address but it was purchased by my company and
assigned to my work email address. I am currently logging into the control
panel with my work address and see no other place to change that.
I recently purchased a license for Telerik JustMock. The Telerik Control
Panel shows JustMock under my list of Purchased products. When I attempt
to run my tests in Visual Studio's Test Explorer with the JustMock Visual
Studio extension enabled I receive an exception saying:
Telerik.JustMockExpiredException : This version of JustMock has expired!
I have uninstalled all the Telerik Visual Studio extensions, uninstalled
everything Telerik via Windows Programs/Features, then re-installed the
control panel and then JustMock yet the problem persists. Of note, when I
re-installed the control panel it remembered my username/password so I'm
guessing there is a configuration file somewhere caching my information
incorrectly.
A possible root cause of this problem is that I was trialing JustMock
under my personal email address but it was purchased by my company and
assigned to my work email address. I am currently logging into the control
panel with my work address and see no other place to change that.
NullPointerException when trying to send a message to a Client Socket
NullPointerException when trying to send a message to a Client Socket
I have a ServerHandler class, which creates a new PrintWriter and stores
it into a PrintWriter array, The message gets sent by giving the
selectedId integer the ID number of the client that should receive the
message. When i call the SendMessage() method inside the ServerHandler
class it sends the message without a problem, but when i try to call the
SendMessage("some message") method from the class that contains the GUI it
gives me a NullPointerException.
The posljiSporocilo() is the actual SendMessage() because some methods are
in my language
import java.net.*;
import java.io.*;
import java.awt.*;
public class ServerHandler implements Runnable{
Socket klientSocket;
static int userCounter = 0;
static int selectedId = 0;
BufferedReader reader;
static PrintWriter writer;
static PrintWriter[] writerHolder = new PrintWriter[10];
static outputHelper out = new outputHelper();
public ServerHandler(Socket klientSocket) throws IOException
{
userCounter++;
this.klientSocket = klientSocket;
writer = new PrintWriter(this.klientSocket.getOutputStream());
writerHolder[userCounter] = writer;
InputStreamReader inReader = new
InputStreamReader(this.klientSocket.getInputStream());
reader = new BufferedReader(inReader);
out.frameOutput(this.klientSocket.getInetAddress().toString(), "Server
sprejel povezavo:");
selectedId = 1;
posljiSporocilo("AutoSent");
When i call the posljiSporocilo() method in the actual class it does send
the message to the Client.
}
public ServerHandler(){
// Do not launch the main Constructor
}
public void run(){
String inMessage = null;
try{
while((inMessage = reader.readLine()) != null){
System.out.println("Server Sprejel: " + inMessage);
}
}catch(IOException ex){
ex.printStackTrace();
}
}
public void selectId(int id){
selectedId = id;
out.frameOutput("ID Changed to: " + selectedId, "ID change");
}
public void posljiSporocilo(String message){
try
{
writerHolder[selectedId].println(message);
writerHolder[selectedId].flush();
}catch(Exception ex)
{
out.frameOutput("ERROR Trying to send a message", "ERR_MESSAGE:");
ex.printStackTrace();
}
}
}
The class that contains the GUI stuff:
package homeControl;
IMPORTS
public class mainWindow extends JFrame {
private JPanel contentPane;
private JTextField messageTextField;
ServerHandler svr = new ServerHandler();
outputHelper o = new outputHelper();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainWindow frame = new mainWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public mainWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnOptions = new JMenu("Options");
menuBar.add(mnOptions);
JMenu mnId = new JMenu("ID");
menuBar.add(mnId);
JMenuItem idEnaItem = new JMenuItem("ID: 1");
mnId.add(idEnaItem);
idEnaItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(event.getActionCommand() != null){
svr.selectId(1);
setTitle("ID changed to 1");
}
}
});
JMenuItem idDvaItem = new JMenuItem("ID: 2");
mnId.add(idDvaItem);
idDvaItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(event.getActionCommand() != null){
svr.selectId(2);
setTitle("ID changed to 2");
}
}
});
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
messageTextField = new JTextField();
messageTextField.setBounds(10, 209, 292, 20);
contentPane.add(messageTextField);
messageTextField.setColumns(10);
JButton sendButton = new JButton("Send");
sendButton.setBounds(312, 208, 89, 23);
contentPane.add(sendButton);
sendButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(event.getActionCommand() != null)
{
svr.posljiSporocilo("THIS MESSAGE DOES NOT GET SENT");
}
When i call the posljiSporocilo() method from this class it gives me a
NullPointerException
}
});
}
}
i hope i gave you enough information, Thanks!
I have a ServerHandler class, which creates a new PrintWriter and stores
it into a PrintWriter array, The message gets sent by giving the
selectedId integer the ID number of the client that should receive the
message. When i call the SendMessage() method inside the ServerHandler
class it sends the message without a problem, but when i try to call the
SendMessage("some message") method from the class that contains the GUI it
gives me a NullPointerException.
The posljiSporocilo() is the actual SendMessage() because some methods are
in my language
import java.net.*;
import java.io.*;
import java.awt.*;
public class ServerHandler implements Runnable{
Socket klientSocket;
static int userCounter = 0;
static int selectedId = 0;
BufferedReader reader;
static PrintWriter writer;
static PrintWriter[] writerHolder = new PrintWriter[10];
static outputHelper out = new outputHelper();
public ServerHandler(Socket klientSocket) throws IOException
{
userCounter++;
this.klientSocket = klientSocket;
writer = new PrintWriter(this.klientSocket.getOutputStream());
writerHolder[userCounter] = writer;
InputStreamReader inReader = new
InputStreamReader(this.klientSocket.getInputStream());
reader = new BufferedReader(inReader);
out.frameOutput(this.klientSocket.getInetAddress().toString(), "Server
sprejel povezavo:");
selectedId = 1;
posljiSporocilo("AutoSent");
When i call the posljiSporocilo() method in the actual class it does send
the message to the Client.
}
public ServerHandler(){
// Do not launch the main Constructor
}
public void run(){
String inMessage = null;
try{
while((inMessage = reader.readLine()) != null){
System.out.println("Server Sprejel: " + inMessage);
}
}catch(IOException ex){
ex.printStackTrace();
}
}
public void selectId(int id){
selectedId = id;
out.frameOutput("ID Changed to: " + selectedId, "ID change");
}
public void posljiSporocilo(String message){
try
{
writerHolder[selectedId].println(message);
writerHolder[selectedId].flush();
}catch(Exception ex)
{
out.frameOutput("ERROR Trying to send a message", "ERR_MESSAGE:");
ex.printStackTrace();
}
}
}
The class that contains the GUI stuff:
package homeControl;
IMPORTS
public class mainWindow extends JFrame {
private JPanel contentPane;
private JTextField messageTextField;
ServerHandler svr = new ServerHandler();
outputHelper o = new outputHelper();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainWindow frame = new mainWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public mainWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu mnOptions = new JMenu("Options");
menuBar.add(mnOptions);
JMenu mnId = new JMenu("ID");
menuBar.add(mnId);
JMenuItem idEnaItem = new JMenuItem("ID: 1");
mnId.add(idEnaItem);
idEnaItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(event.getActionCommand() != null){
svr.selectId(1);
setTitle("ID changed to 1");
}
}
});
JMenuItem idDvaItem = new JMenuItem("ID: 2");
mnId.add(idDvaItem);
idDvaItem.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(event.getActionCommand() != null){
svr.selectId(2);
setTitle("ID changed to 2");
}
}
});
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
messageTextField = new JTextField();
messageTextField.setBounds(10, 209, 292, 20);
contentPane.add(messageTextField);
messageTextField.setColumns(10);
JButton sendButton = new JButton("Send");
sendButton.setBounds(312, 208, 89, 23);
contentPane.add(sendButton);
sendButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
if(event.getActionCommand() != null)
{
svr.posljiSporocilo("THIS MESSAGE DOES NOT GET SENT");
}
When i call the posljiSporocilo() method from this class it gives me a
NullPointerException
}
});
}
}
i hope i gave you enough information, Thanks!
PHP function inside another.
PHP function inside another.
I'm trying to write a PHP loop which pulls all posts from a certain
category, and this category slug is pulled through another php function,
but the code doesn't seem to be doing anything.
Any help would be appreciated.
<?php
query_posts(array('category_name' => '<?php
echo(types_render_field("category-slug-to-pull", array())); ?>'));
if(have_posts()) :
while(have_posts()) : the_post();
?>
<li>
<h2><a href="<?php the_permalink() ?>"><?php the_title();
?></a></h2>
</li>
<?php
endwhile;
endif;
wp_reset_query();
?>
I'm trying to write a PHP loop which pulls all posts from a certain
category, and this category slug is pulled through another php function,
but the code doesn't seem to be doing anything.
Any help would be appreciated.
<?php
query_posts(array('category_name' => '<?php
echo(types_render_field("category-slug-to-pull", array())); ?>'));
if(have_posts()) :
while(have_posts()) : the_post();
?>
<li>
<h2><a href="<?php the_permalink() ?>"><?php the_title();
?></a></h2>
</li>
<?php
endwhile;
endif;
wp_reset_query();
?>
retrieving data from 2 table based on given empid in (oracle) javaservlet
retrieving data from 2 table based on given empid in (oracle) javaservlet
am trying to retrieve a data from 2 table then it is not possible to
retrieved.my main intence is for a given id number dis is not possible.am
entered a empid that id is not going interact with the query if i give the
id directly in query this will be executed. my code is int s1 =
Integer.parseInt(req.getParameter("empid"));
pstmt.setInt(1,s1);
pstmt=con.prepareStatement("SELECT * FROM saldetails Natural Join
empdetails where empid=s1");
pstmt.executeUpdate();
rs = pstmt.executeQuery() ;
...................please help me(servlets)
am trying to retrieve a data from 2 table then it is not possible to
retrieved.my main intence is for a given id number dis is not possible.am
entered a empid that id is not going interact with the query if i give the
id directly in query this will be executed. my code is int s1 =
Integer.parseInt(req.getParameter("empid"));
pstmt.setInt(1,s1);
pstmt=con.prepareStatement("SELECT * FROM saldetails Natural Join
empdetails where empid=s1");
pstmt.executeUpdate();
rs = pstmt.executeQuery() ;
...................please help me(servlets)
boost asio async_read_some does not capture inotify events
boost asio async_read_some does not capture inotify events
I am using inotify in conjunction with boost asio aync_read_some. I am
adding a folder to be monitored and then I delete it. I would expect
IN_DELETE_SELF to be raised by inotify and be read from my
async_read_some. But I do not see IN_DELETE_SELF raised. Please help me
find what is being missed here? Ofcourse during inotify_add_watch I am
registering for IN_DELETE_SELF. Note, I have tried both READ_BUFFER_SIZE
to be of 1024 bytes as well as (1024*(EVENT_SIZE + 16)), but in either
case IN_DELETE_SELF is not captured by my code.
#define EVENT_SIZE (sizeof (struct inotify_event))
#define READ_BUFFER_SIZE (1024*(EVENT_SIZE + 16))
//I even tried #define READ_BUFFER_SIZE 1024
void IHandler::init()
{
inotifyFd_ = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if(inotifyFd_ < 0)
//Error
else
{
inotifyStream_ = inotifyStreamPointer(new
boost::asio::posix::stream_descriptor(CORE::Utils::Thread::SingletonIOService::Instance(),
inotifyFd_));
doRead();
}
}
void IHandler::doRead()
{
inotifyStream_->async_read_some(
boost::asio::buffer(readBuffer_, READ_BUFFER_SIZE),
std::bind(&IHandler::readInotifyEvent,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2));
}
void IHandler::readInotifyEvent(boost::system::error_code ec, size_t
bytes_recvd)
{
if(!ec)
{
if(bytes_recvd)
{
char *ptr = NULL;
ptr = readBuffer_;
while (ptr < readBuffer_ + bytes_recvd)
{
struct inotify_event* event = (struct inotify_event *) ptr;
ptr += sizeof (struct inotify_event) +event->len;
processInotifyEvent(event); //Events would be handled here
}
}
inotifyStream_->async_read_some(
boost::asio::buffer(readBuffer_, READ_BUFFER_SIZE),
std::bind(&IHandler::readInotifyEvent,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2));
}
else
//Error
}
Thanks, Sandeep
I am using inotify in conjunction with boost asio aync_read_some. I am
adding a folder to be monitored and then I delete it. I would expect
IN_DELETE_SELF to be raised by inotify and be read from my
async_read_some. But I do not see IN_DELETE_SELF raised. Please help me
find what is being missed here? Ofcourse during inotify_add_watch I am
registering for IN_DELETE_SELF. Note, I have tried both READ_BUFFER_SIZE
to be of 1024 bytes as well as (1024*(EVENT_SIZE + 16)), but in either
case IN_DELETE_SELF is not captured by my code.
#define EVENT_SIZE (sizeof (struct inotify_event))
#define READ_BUFFER_SIZE (1024*(EVENT_SIZE + 16))
//I even tried #define READ_BUFFER_SIZE 1024
void IHandler::init()
{
inotifyFd_ = inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if(inotifyFd_ < 0)
//Error
else
{
inotifyStream_ = inotifyStreamPointer(new
boost::asio::posix::stream_descriptor(CORE::Utils::Thread::SingletonIOService::Instance(),
inotifyFd_));
doRead();
}
}
void IHandler::doRead()
{
inotifyStream_->async_read_some(
boost::asio::buffer(readBuffer_, READ_BUFFER_SIZE),
std::bind(&IHandler::readInotifyEvent,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2));
}
void IHandler::readInotifyEvent(boost::system::error_code ec, size_t
bytes_recvd)
{
if(!ec)
{
if(bytes_recvd)
{
char *ptr = NULL;
ptr = readBuffer_;
while (ptr < readBuffer_ + bytes_recvd)
{
struct inotify_event* event = (struct inotify_event *) ptr;
ptr += sizeof (struct inotify_event) +event->len;
processInotifyEvent(event); //Events would be handled here
}
}
inotifyStream_->async_read_some(
boost::asio::buffer(readBuffer_, READ_BUFFER_SIZE),
std::bind(&IHandler::readInotifyEvent,
shared_from_this(),
std::placeholders::_1,
std::placeholders::_2));
}
else
//Error
}
Thanks, Sandeep
Wednesday, 18 September 2013
Passing calculation result to JSP page
Passing calculation result to JSP page
Index.jsp takes two input number and after submit the request go to
Operation.java. It has a radio button to select Operation. Both inputs and
radio button are submitted to Operation.java.
<form action="Operation">
First number::<input type="text" name="firstno"></input>
Second number::<input type="text" name="Secondno"></input>
<input type="radio" name="option" value="add">Add</input>
<input type="radio" name="option" value="substract">Subtract</input>
<input type="radio" name="option" value="mul">Multiply</input>
<input type="radio" name="option" value="divide">Divide</input>
<input type="submit" value="submit">
</form>
Operation.java(Servlet) takes value from input button and do calculation
based on the radio button click. It will calculate the result.
int result1=0;
int n1=Integer.parseInt(request.getParameter("firstno"));
int n2=Integer.parseInt(request.getParameter("Secondno"));
String radio=request.getParameter("option");
if(radio.equals("add"))
{
result1=n1+n2;
}
else if(radio.equals("substract"))
{
result1=n1-n2;
}
else if(radio.equals("mul"))
{
result1=n1*n2;
}
After calculation I want to show the result on the index.jsp. How can I do
that?
Index.jsp takes two input number and after submit the request go to
Operation.java. It has a radio button to select Operation. Both inputs and
radio button are submitted to Operation.java.
<form action="Operation">
First number::<input type="text" name="firstno"></input>
Second number::<input type="text" name="Secondno"></input>
<input type="radio" name="option" value="add">Add</input>
<input type="radio" name="option" value="substract">Subtract</input>
<input type="radio" name="option" value="mul">Multiply</input>
<input type="radio" name="option" value="divide">Divide</input>
<input type="submit" value="submit">
</form>
Operation.java(Servlet) takes value from input button and do calculation
based on the radio button click. It will calculate the result.
int result1=0;
int n1=Integer.parseInt(request.getParameter("firstno"));
int n2=Integer.parseInt(request.getParameter("Secondno"));
String radio=request.getParameter("option");
if(radio.equals("add"))
{
result1=n1+n2;
}
else if(radio.equals("substract"))
{
result1=n1-n2;
}
else if(radio.equals("mul"))
{
result1=n1*n2;
}
After calculation I want to show the result on the index.jsp. How can I do
that?
cannot load such file -- shoulda/context (LoadError) error ruby 1.9 rails 3.2
cannot load such file -- shoulda/context (LoadError) error ruby 1.9 rails 3.2
I am getting this error when trying to run or migrate my rails app.
ruby-1.9.3-p448/gems/shoulda-3.4.0/lib/shoulda.rb:3:in `require': cannot
load such file -- shoulda/context (LoadError)
I am getting this error when trying to run or migrate my rails app.
ruby-1.9.3-p448/gems/shoulda-3.4.0/lib/shoulda.rb:3:in `require': cannot
load such file -- shoulda/context (LoadError)
Getting jquery to work with MVC4
Getting jquery to work with MVC4
It's not happening. I tried linking the scripts normally in _Layout.cshtml
with <script src='@Content.Url("..., installing Web Optimization and using
bundles, and putting @Scripts.Render() in the head/body/bottom of
_Layout.cshtml and before the <script> tag on the relevant page. What am I
missing?
Directory structure
Views
Shared
Js
jquery-1.10.2.js
jquery.color-2.1.2.min.js
BundleConfig.cs
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Views/Shared/Js/jquery-{version}.js",
"~/Views/Shared/Js/jquery.color-{version}.js")
);
}
Global.asax.cs
protected void Application_Start()
{
// blah, etc, then:
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
_Layout.cshtml
@Scripts.Render("~/bundles/jquery");
I can run the actual javascript/jquery code on JsFiddle, so the validity
of what I've written there isn't the problem.
It's not happening. I tried linking the scripts normally in _Layout.cshtml
with <script src='@Content.Url("..., installing Web Optimization and using
bundles, and putting @Scripts.Render() in the head/body/bottom of
_Layout.cshtml and before the <script> tag on the relevant page. What am I
missing?
Directory structure
Views
Shared
Js
jquery-1.10.2.js
jquery.color-2.1.2.min.js
BundleConfig.cs
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Views/Shared/Js/jquery-{version}.js",
"~/Views/Shared/Js/jquery.color-{version}.js")
);
}
Global.asax.cs
protected void Application_Start()
{
// blah, etc, then:
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
_Layout.cshtml
@Scripts.Render("~/bundles/jquery");
I can run the actual javascript/jquery code on JsFiddle, so the validity
of what I've written there isn't the problem.
Entity Framework 5, switch from code first to database first?
Entity Framework 5, switch from code first to database first?
I've already created a database using code first. It worked well. Many
changes have since been made to the database outside Visual Studio. So
many that any attempt at migration generates errors. So my question is, is
there a way to switch a solution from code first to database first?
I've already created a database using code first. It worked well. Many
changes have since been made to the database outside Visual Studio. So
many that any attempt at migration generates errors. So my question is, is
there a way to switch a solution from code first to database first?
function select with autocomplete jquery does not work
function select with autocomplete jquery does not work
I use function "autocomplete" of jquery.here is my code below, the problem
that the select function does not work
$(function () {
var productId = 0;
var productLabel;
$("#autocompleteInput").autocomplete({
source: function (req, add) {
$.getJSON(urlresourceproduct, req, function (data) {
add($.map(data.data, function (item) {
return {
label: item.tuttiProdottis,
val: item.id
};
}));
});
},
minLength: 2,
select: function (event, ui) {
productId = ui.item.val;
productLabel = ui.item.label;
},
close: function (event, ui) {
alert(productId);
drawChart();
return false;
}
}).focus(function () {
$("#autocompleteInput").val("");
return false;
});
});
});
I use function "autocomplete" of jquery.here is my code below, the problem
that the select function does not work
$(function () {
var productId = 0;
var productLabel;
$("#autocompleteInput").autocomplete({
source: function (req, add) {
$.getJSON(urlresourceproduct, req, function (data) {
add($.map(data.data, function (item) {
return {
label: item.tuttiProdottis,
val: item.id
};
}));
});
},
minLength: 2,
select: function (event, ui) {
productId = ui.item.val;
productLabel = ui.item.label;
},
close: function (event, ui) {
alert(productId);
drawChart();
return false;
}
}).focus(function () {
$("#autocompleteInput").val("");
return false;
});
});
});
Call function directly after constructor: new Object()->callFunction()
Call function directly after constructor: new Object()->callFunction()
As you might have seen in the title, my programming background is Java. In
Java you can do stuff like this
new Object().callSomeMethod();
without assigning the created Object to a variable, very useful and clear
coding if you only need this Object once.
Now in PHP i try to do the same
new Object()->callSomeMethod();
but here i get a 'Parse error: syntax error, unexpected '->'
(T_OBJECT_OPERATOR)'.
Is there a way to do this in PHP ?
As you might have seen in the title, my programming background is Java. In
Java you can do stuff like this
new Object().callSomeMethod();
without assigning the created Object to a variable, very useful and clear
coding if you only need this Object once.
Now in PHP i try to do the same
new Object()->callSomeMethod();
but here i get a 'Parse error: syntax error, unexpected '->'
(T_OBJECT_OPERATOR)'.
Is there a way to do this in PHP ?
Use custom powershell module in C#
Use custom powershell module in C#
I wrote fuction PowerShell module like that:
Function docConvert2{
param ([string]$sourceFile, [string]$sourceFilePath)
....
....
}
I've imported module successfuly
And i can use module in powershell cmdlet
When i try call function in c#, i got exception like that
The term 'docConvert2' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try
again.
C# code
PowerShell pShell = PowerShell.Create();
pShell.AddCommand("docConvert2");
pShell.AddParameter("sourceFile", "'addendum no-3_PREP.doc'");
pShell.AddParameter("sourceFilePath", @"'D:\New\wordler'");
pShell.Invoke();
What is my mistake?
Thanks for advices.
I wrote fuction PowerShell module like that:
Function docConvert2{
param ([string]$sourceFile, [string]$sourceFilePath)
....
....
}
I've imported module successfuly
And i can use module in powershell cmdlet
When i try call function in c#, i got exception like that
The term 'docConvert2' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try
again.
C# code
PowerShell pShell = PowerShell.Create();
pShell.AddCommand("docConvert2");
pShell.AddParameter("sourceFile", "'addendum no-3_PREP.doc'");
pShell.AddParameter("sourceFilePath", @"'D:\New\wordler'");
pShell.Invoke();
What is my mistake?
Thanks for advices.
show loading dialog for multiple ajax request
show loading dialog for multiple ajax request
I am making two ajax call asynchronously, on each call I am showing a
loading dialog box like this,
jQuery('#msg_writter').show();
on success of each request I will hide the loading dialog like this,
jQuery('#msg_writter').fadeOut(1000);
my html code for loading dialog:
<div id="msg_writter" class="msgWritter">
<img src="/images/loading.gif"/>
</div>
when the first request is done, the loading dialog gets disappear so
loading dialog is not showing for the second request.
How could I modify the code to show the loading dialog from the first
request till the success of last request.
I am making two ajax call asynchronously, on each call I am showing a
loading dialog box like this,
jQuery('#msg_writter').show();
on success of each request I will hide the loading dialog like this,
jQuery('#msg_writter').fadeOut(1000);
my html code for loading dialog:
<div id="msg_writter" class="msgWritter">
<img src="/images/loading.gif"/>
</div>
when the first request is done, the loading dialog gets disappear so
loading dialog is not showing for the second request.
How could I modify the code to show the loading dialog from the first
request till the success of last request.
Tuesday, 17 September 2013
Layout in a Scroll View
Layout in a Scroll View
I want to create a design that will be look like this image Image Link.I
am not able design this layout.Please help me to create this layout .this
is what i tried to create this but unfortunately i am not getting this how
i will set this image and text.Please help
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ItinearyPage" >
<ScrollView
android:id="@+id/main_ScrollView_Container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="@+id/main_Inside_ScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/itin_Section_First"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/travel_Itenary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginTop="5dp"
android:text="@string/tarvelItinaryText"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:id="@+id/itin_Section_Second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/itin_Section_First"
android:layout_toRightOf="@+id/itin_Section_First"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="268dp"
android:layout_height="40dp"
android:layout_marginLeft="13dp"
android:layout_marginRight="13dp"
android:layout_marginTop="15dp"
android:src="@drawable/logo_demo" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
Please help me to get this it's my first assignment.I am stucked in this
from last 2 days .I read my many tutorials and website but still i am not
able to get this
I want to create a design that will be look like this image Image Link.I
am not able design this layout.Please help me to create this layout .this
is what i tried to create this but unfortunately i am not getting this how
i will set this image and text.Please help
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ItinearyPage" >
<ScrollView
android:id="@+id/main_ScrollView_Container"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="@+id/main_Inside_ScrollView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<LinearLayout
android:id="@+id/itin_Section_First"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/travel_Itenary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="6dp"
android:layout_marginTop="5dp"
android:text="@string/tarvelItinaryText"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:id="@+id/itin_Section_Second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/itin_Section_First"
android:layout_toRightOf="@+id/itin_Section_First"
android:orientation="vertical" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="268dp"
android:layout_height="40dp"
android:layout_marginLeft="13dp"
android:layout_marginRight="13dp"
android:layout_marginTop="15dp"
android:src="@drawable/logo_demo" />
</LinearLayout>
</RelativeLayout>
</ScrollView>
</RelativeLayout>
Please help me to get this it's my first assignment.I am stucked in this
from last 2 days .I read my many tutorials and website but still i am not
able to get this
IndentationError in Google App Engine Sample
IndentationError in Google App Engine Sample
Error (From Log Console):
File "D:\dev\gamerofprogrammer\guessbook\main.py", line 62
greeting = greetings_query.fetch(10)
IndentationError: unexpected indent
My code
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write('<html><body>')
guestbook_name = self.request.get('guestbook_name',
DEFAULT_GUESTBOOK_NAME)
greetings_query =
Greeting.query(ancestor=guestbook_key(guestbook_name)).order(Greeting.date)
greeting = greetings_query.fetch(10)
for greeting in greetings:
if greeting.author:
self.response.write('<b> </b> wrote: ' %
greeting.author.nickname())
else:
self.response.write('An anonymous person wrote:')
self.response.write('<blockquote> %s </blockquote>' %
cgi.escape(greeting.content))
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
else:
url = users.create_login_url(self.request.uri)
url_linktext = 'logout'
sign_query_params = urllib.urlencode({'guestbook_name': guestbook_name})
self.response.write(MAIN_PAGE_FOOTER_TEMPLATE % (sign_query_params,
cgi.escape(GUESTBOOK_NAME), url, url_linktext))
all theses codes can be found in Google App Engine What is the trouble
with my Indentation ?
Error (From Log Console):
File "D:\dev\gamerofprogrammer\guessbook\main.py", line 62
greeting = greetings_query.fetch(10)
IndentationError: unexpected indent
My code
class MainPage(webapp2.RequestHandler):
def get(self):
self.response.write('<html><body>')
guestbook_name = self.request.get('guestbook_name',
DEFAULT_GUESTBOOK_NAME)
greetings_query =
Greeting.query(ancestor=guestbook_key(guestbook_name)).order(Greeting.date)
greeting = greetings_query.fetch(10)
for greeting in greetings:
if greeting.author:
self.response.write('<b> </b> wrote: ' %
greeting.author.nickname())
else:
self.response.write('An anonymous person wrote:')
self.response.write('<blockquote> %s </blockquote>' %
cgi.escape(greeting.content))
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
else:
url = users.create_login_url(self.request.uri)
url_linktext = 'logout'
sign_query_params = urllib.urlencode({'guestbook_name': guestbook_name})
self.response.write(MAIN_PAGE_FOOTER_TEMPLATE % (sign_query_params,
cgi.escape(GUESTBOOK_NAME), url, url_linktext))
all theses codes can be found in Google App Engine What is the trouble
with my Indentation ?
4 Bit Adder using port maps
4 Bit Adder using port maps
So I am trying to do a 4 bit adder and have ran into an error I can't seem
to figure out.
Error (10430): VHDL Primary Unit Declaration error at adder1.vhd(3):
primary unit "Adder1Vhd" already exists in library "work"
I have a project called 4 bit adder and inside that project folder is the
.vhd file for Adder1.vhd. Here is the codes I have, if somebody could help
me figure this out it would be greatly appreciated.
Adder4.vhd:
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
ENTITY Adder4 IS
GENERIC(CONSTANT N: INTEGER := 4);
PORT(
a, b: IN STD_LOGIC_VECTOR(N-1 DOWNTO 0); -- Input SW[7..4]: a[3..0] inputs,
-- SW[3..0]: b[3..0]
cIn: in std_logic;
sum: OUT STD_LOGIC_VECTOR(N-1 DOWNTO 0); -- Output LEDR[3..0]
cOut: OUT STD_LOGIC -- Output LEDR[4]
);
END Adder4;
ARCHITECTURE imp OF Adder4 IS
COMPONENT Adder1
PORT(
a, b, cIn : in STD_LOGIC;
sum, cOut : out STD_LOGIC);
END COMPONENT;
SIGNAL carry_sig: std_logic_vector(N-1 DOWNTO 0);
BEGIN
A1: Adder1 port map (a(0), b(0), cIn, sum(0), carry_sig(0));
A2: Adder1 port map (a(1), b(1), carry_sig(0), sum(1), carry_sig(1));
A3: Adder1 port map (a(2), b(2), carry_sig(1), sum(2), carry_sig(2));
A4: Adder1 port map (a(3), b(3), carry_sig(2), sum(3), cOut);
END imp;
Adder1.vhd(the file inside the Adder4 project folder):
library ieee;
use ieee.std_logic_1164.all;
entity Adder1Vhd is
port(
a, b, cIn : in std_logic;
sum, cOut : out std_logic);
end Adder1Vhd;
architecture imp of Adder1Vhd is
begin
-- Add two lines (one for sum and the other for cOut) of VHDL code here
sum <= (a xor b) xor cIn;
cOut <= (a and b) or (cIn and (a xor b));
end imp;
So I am trying to do a 4 bit adder and have ran into an error I can't seem
to figure out.
Error (10430): VHDL Primary Unit Declaration error at adder1.vhd(3):
primary unit "Adder1Vhd" already exists in library "work"
I have a project called 4 bit adder and inside that project folder is the
.vhd file for Adder1.vhd. Here is the codes I have, if somebody could help
me figure this out it would be greatly appreciated.
Adder4.vhd:
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
ENTITY Adder4 IS
GENERIC(CONSTANT N: INTEGER := 4);
PORT(
a, b: IN STD_LOGIC_VECTOR(N-1 DOWNTO 0); -- Input SW[7..4]: a[3..0] inputs,
-- SW[3..0]: b[3..0]
cIn: in std_logic;
sum: OUT STD_LOGIC_VECTOR(N-1 DOWNTO 0); -- Output LEDR[3..0]
cOut: OUT STD_LOGIC -- Output LEDR[4]
);
END Adder4;
ARCHITECTURE imp OF Adder4 IS
COMPONENT Adder1
PORT(
a, b, cIn : in STD_LOGIC;
sum, cOut : out STD_LOGIC);
END COMPONENT;
SIGNAL carry_sig: std_logic_vector(N-1 DOWNTO 0);
BEGIN
A1: Adder1 port map (a(0), b(0), cIn, sum(0), carry_sig(0));
A2: Adder1 port map (a(1), b(1), carry_sig(0), sum(1), carry_sig(1));
A3: Adder1 port map (a(2), b(2), carry_sig(1), sum(2), carry_sig(2));
A4: Adder1 port map (a(3), b(3), carry_sig(2), sum(3), cOut);
END imp;
Adder1.vhd(the file inside the Adder4 project folder):
library ieee;
use ieee.std_logic_1164.all;
entity Adder1Vhd is
port(
a, b, cIn : in std_logic;
sum, cOut : out std_logic);
end Adder1Vhd;
architecture imp of Adder1Vhd is
begin
-- Add two lines (one for sum and the other for cOut) of VHDL code here
sum <= (a xor b) xor cIn;
cOut <= (a and b) or (cIn and (a xor b));
end imp;
Have Swing GUI elements, without large spaces
Have Swing GUI elements, without large spaces
My issue is, rather than the elements being on top of each other neatly,
there are huge blocks of space unnecessarily in between each element of
the gui that I use in the program.
I'm trying to have it like this:
label
textfield, button
textarea
But instead it's coming out like
label
(blotch of space)
textfield, button
(blotch of space)
textarea
when I run it. Any help is appreciated, I've really been trying to figure
it out by myself. package guiprojj;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import javax.swing.*;
import com.eclipsesource.json.JsonObject;
import com.google.gson.JsonParser;
import com.json.parsers.JSONParser;
import com.json.parsers.JsonParserFactory;
public class gui {
public static void main(String[] args)
{
JFrame maingui = new JFrame("Gui");
JButton enter = new JButton("Enter");
final JTextArea movieinfo = new JTextArea(5,20);
final JTextField movietext = new JTextField(16);
final JScrollPane scrolll = new JScrollPane(movieinfo);
final JLabel titlee = new JLabel("Enter movie name here:");
JPanel pangui = new JPanel();
JPanel pangui2 = new JPanel();
maingui.setLayout(new GridLayout(3, 0));
maingui.add(titlee);
pangui.add(movietext);
pangui.add(enter);
pangui2.add(scrolll);
//scrolll.add(movieinfo);
//pangui.add(movieinfo);
maingui.setResizable(false);
maingui.setVisible(true);
movieinfo.setLineWrap(true);
movieinfo.setWrapStyleWord(true);
movieinfo.setEditable(false);
maingui.add(pangui);
maingui.add(pangui2);
scrolll.getPreferredSize();
//pangui.setPreferredSize(new Dimension(300, 150));
//pangui.add(scrolll, BorderLayout.CENTER);
//movieinfo.add(scrolll);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println(Test.getMovieInfo(movietext.getText()));
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map
jsonData=parser.parseJson(Test.getMovieInfo(movietext.getText()));
String Title = (String)jsonData.get("Title");
String Year = (String)jsonData.get("Year");
String Plot = (String)jsonData.get("Plot");
movieinfo.setText("Title: "+Title+"\nYear: "+ Year
+"\nPlot: "+Plot);
}
});
}
}
My issue is, rather than the elements being on top of each other neatly,
there are huge blocks of space unnecessarily in between each element of
the gui that I use in the program.
I'm trying to have it like this:
label
textfield, button
textarea
But instead it's coming out like
label
(blotch of space)
textfield, button
(blotch of space)
textarea
when I run it. Any help is appreciated, I've really been trying to figure
it out by myself. package guiprojj;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import javax.swing.*;
import com.eclipsesource.json.JsonObject;
import com.google.gson.JsonParser;
import com.json.parsers.JSONParser;
import com.json.parsers.JsonParserFactory;
public class gui {
public static void main(String[] args)
{
JFrame maingui = new JFrame("Gui");
JButton enter = new JButton("Enter");
final JTextArea movieinfo = new JTextArea(5,20);
final JTextField movietext = new JTextField(16);
final JScrollPane scrolll = new JScrollPane(movieinfo);
final JLabel titlee = new JLabel("Enter movie name here:");
JPanel pangui = new JPanel();
JPanel pangui2 = new JPanel();
maingui.setLayout(new GridLayout(3, 0));
maingui.add(titlee);
pangui.add(movietext);
pangui.add(enter);
pangui2.add(scrolll);
//scrolll.add(movieinfo);
//pangui.add(movieinfo);
maingui.setResizable(false);
maingui.setVisible(true);
movieinfo.setLineWrap(true);
movieinfo.setWrapStyleWord(true);
movieinfo.setEditable(false);
maingui.add(pangui);
maingui.add(pangui2);
scrolll.getPreferredSize();
//pangui.setPreferredSize(new Dimension(300, 150));
//pangui.add(scrolll, BorderLayout.CENTER);
//movieinfo.add(scrolll);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println(Test.getMovieInfo(movietext.getText()));
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map
jsonData=parser.parseJson(Test.getMovieInfo(movietext.getText()));
String Title = (String)jsonData.get("Title");
String Year = (String)jsonData.get("Year");
String Plot = (String)jsonData.get("Plot");
movieinfo.setText("Title: "+Title+"\nYear: "+ Year
+"\nPlot: "+Plot);
}
});
}
}
Ajax - Lazy load random elements without repeating
Ajax - Lazy load random elements without repeating
I have a database of, lets say 10,000 records. I have a webpage where I
want to display each record in a list, in random order. Because there are
so many records, I want to initially load only 100 records on the page,
and as you get to the bottom of the page, another 100 is added via AJAX,
then as you scroll to the bottom, 100 more, etc...
The trick is that overall, I want the order of the displayed records to be
random, but also, they cannot repeat. So just doing an AJAX call to pull
in 100 random records isn't going to work since some of those records may
have already been displayed on the page.
Is there a certain trick to doing this?
I was thinking maybe keeping track of the record id's that have been
displayed already and sending this in the AJAX call and then fetch 100
random records who's ID's have not already been displayed... But I'm
afraid for a high traffic website, this would get pretty slow as you can't
cache that too easily, without recreating the same thing using cached
arrays.
What is the best approach to this?
I have a database of, lets say 10,000 records. I have a webpage where I
want to display each record in a list, in random order. Because there are
so many records, I want to initially load only 100 records on the page,
and as you get to the bottom of the page, another 100 is added via AJAX,
then as you scroll to the bottom, 100 more, etc...
The trick is that overall, I want the order of the displayed records to be
random, but also, they cannot repeat. So just doing an AJAX call to pull
in 100 random records isn't going to work since some of those records may
have already been displayed on the page.
Is there a certain trick to doing this?
I was thinking maybe keeping track of the record id's that have been
displayed already and sending this in the AJAX call and then fetch 100
random records who's ID's have not already been displayed... But I'm
afraid for a high traffic website, this would get pretty slow as you can't
cache that too easily, without recreating the same thing using cached
arrays.
What is the best approach to this?
Customer view for Team Foundation Service
Customer view for Team Foundation Service
My team recently migrated from onsite to the cloud Team Foundation Service
2012.
We had also maintained a separate SharePoint portal with extranet
capabilities to list projects/tasks etc. for external customers
Seeing that we're now online, I was wondering if there is a means to
restrict a view to PBIs/Certain properties of tasks [Time Elapsed, Time
Remaining] for certain accounts.
Alternatively, I recall seeing SSRS capabilities in the on site version.
Is there a means to configure reports (scheduled/manual) using the Team
Foundation Service?
My team recently migrated from onsite to the cloud Team Foundation Service
2012.
We had also maintained a separate SharePoint portal with extranet
capabilities to list projects/tasks etc. for external customers
Seeing that we're now online, I was wondering if there is a means to
restrict a view to PBIs/Certain properties of tasks [Time Elapsed, Time
Remaining] for certain accounts.
Alternatively, I recall seeing SSRS capabilities in the on site version.
Is there a means to configure reports (scheduled/manual) using the Team
Foundation Service?
Sunday, 15 September 2013
Is there a way to determine if a parameter is a literal string?
Is there a way to determine if a parameter is a literal string?
My question is:
Is there a way to determine whether a parameter is a literal string or not?
template<class T>
bool IsLiteral(T arg)
{
// How to implement?
}
or
template<class T>
struct IsLiteral { enum { value = ??? }; };
So that we can write the following code:
char* p = "Hello";
assert(IsLiteral(p)); // fail.
assert(IsLiteral("Hello")); // never fail.
My question is:
Is there a way to determine whether a parameter is a literal string or not?
template<class T>
bool IsLiteral(T arg)
{
// How to implement?
}
or
template<class T>
struct IsLiteral { enum { value = ??? }; };
So that we can write the following code:
char* p = "Hello";
assert(IsLiteral(p)); // fail.
assert(IsLiteral("Hello")); // never fail.
CheckBox in C# Windows App
CheckBox in C# Windows App
I have 3 checkboxes and I am able to turn two of them off if one is
checked. But I want that if the 3rd one is checked then the first two
should be turned off. how can I do that?
This is what I am trying.
private void chkResFoodVeg_CheckedChanged(object sender, EventArgs e)
{
//disables the other checkbox if one is checked
this.chkResFoodNveg.Enabled = !this.chkResFoodVeg.Checked;
}
private void chkResFoodNveg_CheckedChanged(object sender, EventArgs e)
{
this.chkResFoodVeg.Enabled = !this.chkResFoodNveg.Checked;
}
private void chkResFoodBoth_CheckedChanged(object sender, EventArgs e)
{
this.chkResFoodBoth.Enabled = !this.chkResFoodNveg.Checked &&
!this.chkResFoodVeg.Checked;
}
The last part of code doesn't work. It should turn off the first two
checkboxes.
Thanks
I have 3 checkboxes and I am able to turn two of them off if one is
checked. But I want that if the 3rd one is checked then the first two
should be turned off. how can I do that?
This is what I am trying.
private void chkResFoodVeg_CheckedChanged(object sender, EventArgs e)
{
//disables the other checkbox if one is checked
this.chkResFoodNveg.Enabled = !this.chkResFoodVeg.Checked;
}
private void chkResFoodNveg_CheckedChanged(object sender, EventArgs e)
{
this.chkResFoodVeg.Enabled = !this.chkResFoodNveg.Checked;
}
private void chkResFoodBoth_CheckedChanged(object sender, EventArgs e)
{
this.chkResFoodBoth.Enabled = !this.chkResFoodNveg.Checked &&
!this.chkResFoodVeg.Checked;
}
The last part of code doesn't work. It should turn off the first two
checkboxes.
Thanks
Is there a way to control thread count, affinity and creation time in Intels Threading Building Blocks?
Is there a way to control thread count, affinity and creation time in
Intels Threading Building Blocks?
Currently I use Intels TBB to parallelize some work using
tbb::parallel_for. It seems that the amount of threads and the point in
time when they are started is controlled by TBB in the background. Looking
through the User Guide and Reference Documentation I could not find any
hint on whether there are any control options or modules. I would like to
be able to modify the amount of threads and, if possible, decide when the
thread pool is created.
Intels Threading Building Blocks?
Currently I use Intels TBB to parallelize some work using
tbb::parallel_for. It seems that the amount of threads and the point in
time when they are started is controlled by TBB in the background. Looking
through the User Guide and Reference Documentation I could not find any
hint on whether there are any control options or modules. I would like to
be able to modify the amount of threads and, if possible, decide when the
thread pool is created.
c# two object in class dont work thread
c# two object in class dont work thread
this normal working :
private readonly List<Thread> thr = new List<Thread>();
class
public void testthr(object xxx)
{
......
}
button
for (Int32 i = 0; i < textBox8.Lines.Length; i++)
{
var thr1 = new Thread(testthr);
thr1.Start(textBox8.Lines[i].Trim());
thr.Add(threadz);
}
how to ;
public void testthr(object xxx, string yyy)
{
......
}
this class in thread start ?
this normal working :
private readonly List<Thread> thr = new List<Thread>();
class
public void testthr(object xxx)
{
......
}
button
for (Int32 i = 0; i < textBox8.Lines.Length; i++)
{
var thr1 = new Thread(testthr);
thr1.Start(textBox8.Lines[i].Trim());
thr.Add(threadz);
}
how to ;
public void testthr(object xxx, string yyy)
{
......
}
this class in thread start ?
Using non-ASCII characters in cmd batch file
Using non-ASCII characters in cmd batch file
I'm working on a .bat program and the program is written in Finnish. The
problem is that CMD doesn't know these "special" letters such as : Ä, Ö,
Å.
Is there a way to make those work? I'd also like it if the user could use
those letters too.
I'm working on a .bat program and the program is written in Finnish. The
problem is that CMD doesn't know these "special" letters such as : Ä, Ö,
Å.
Is there a way to make those work? I'd also like it if the user could use
those letters too.
UICollectionView Cells and Rasterizing
UICollectionView Cells and Rasterizing
I recentlty discovered that by adding this before returning my collection
view cell improves scrolling animation performance (smoothness).
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
If my cell contains, multiple buttons do I need to rasterize those
individually, or will that be taken care of automatically?... or should I
ever bother?
I have added the buttons via Interface Builder.
I recentlty discovered that by adding this before returning my collection
view cell improves scrolling animation performance (smoothness).
cell.layer.shouldRasterize = YES;
cell.layer.rasterizationScale = [UIScreen mainScreen].scale;
If my cell contains, multiple buttons do I need to rasterize those
individually, or will that be taken care of automatically?... or should I
ever bother?
I have added the buttons via Interface Builder.
Why changes to the outer data-source is not reflected, while they show-up for the inner data-source?
Why changes to the outer data-source is not reflected, while they show-up
for the inner data-source?
Why changes to the outer data-source is not reflected, while they show-up
for the inner data-source?? Pls help
public static void MyMethod(char[] inputDS1, char[] inputDS2)
{
Console.WriteLine("\n'from' clause - Display all possible
combinations of a-b-c-d.");
//query syntax
IEnumerable<ChrPair> resultset = from res1 in inputDS1
from res2 in inputDS2
select new ChrPair(res1, res2);
//Write result-set
Console.WriteLine("\n\nOutput list -->");
displayList(resultset);
//swap positions
//obs: changes to the first ds is not reflected in the resultset.
char[] temp = inputDS1;
inputDS1 = inputDS2;
inputDS2 = temp;
//run query again
displayList(resultset);
Console.WriteLine("\n------------------------------------------");
}
Input:
('a','b'), ('c','d')
Output:
ac, ad, bc, bd, **aa. ab, ba, bb**
I expected all possible combinations (ac, ad, bc, bd, ca, cb, da, db) as I
swapped the Data-sources before the second Write. When I do a ToList()
before the second Write, I get the expected result, so is it because that
Select is lazy? Please explain.
for the inner data-source?
Why changes to the outer data-source is not reflected, while they show-up
for the inner data-source?? Pls help
public static void MyMethod(char[] inputDS1, char[] inputDS2)
{
Console.WriteLine("\n'from' clause - Display all possible
combinations of a-b-c-d.");
//query syntax
IEnumerable<ChrPair> resultset = from res1 in inputDS1
from res2 in inputDS2
select new ChrPair(res1, res2);
//Write result-set
Console.WriteLine("\n\nOutput list -->");
displayList(resultset);
//swap positions
//obs: changes to the first ds is not reflected in the resultset.
char[] temp = inputDS1;
inputDS1 = inputDS2;
inputDS2 = temp;
//run query again
displayList(resultset);
Console.WriteLine("\n------------------------------------------");
}
Input:
('a','b'), ('c','d')
Output:
ac, ad, bc, bd, **aa. ab, ba, bb**
I expected all possible combinations (ac, ad, bc, bd, ca, cb, da, db) as I
swapped the Data-sources before the second Write. When I do a ToList()
before the second Write, I get the expected result, so is it because that
Select is lazy? Please explain.
Saturday, 14 September 2013
How to resolve kCFErrorHTTPSProxyConnectionFailure = 310?
How to resolve kCFErrorHTTPSProxyConnectionFailure = 310?
I am getting error as followed
Error Domain=kCFErrorDomainCFNetwork Code=310 "There was a problem
communicating with the secure web proxy server (HTTPS)."
My Code is
NSString *urlString = [NSString
stringWithFormat:@"https://hostname/DEMOService/DEMO.asmx/VerifyLogin?username=duaan@companyname.ae&password=1234&AuthenticationKey=A53d3W3456dd2wdeat"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError];
NSLog(@"ERROR %@", requestError);
What is error and how can I resolve it?
Thanks
I am getting error as followed
Error Domain=kCFErrorDomainCFNetwork Code=310 "There was a problem
communicating with the secure web proxy server (HTTPS)."
My Code is
NSString *urlString = [NSString
stringWithFormat:@"https://hostname/DEMOService/DEMO.asmx/VerifyLogin?username=duaan@companyname.ae&password=1234&AuthenticationKey=A53d3W3456dd2wdeat"];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10];
NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response1 = [NSURLConnection sendSynchronousRequest:request
returningResponse:&urlResponse error:&requestError];
NSLog(@"ERROR %@", requestError);
What is error and how can I resolve it?
Thanks
substring dynamic number of characters
substring dynamic number of characters
I'm working with 2 sets of data that were merged together, but they're
inconsistent in their format. Some are 10 characters, all numbers. Others
may have a separator : at position 4. I need to substring the first 4
characters. But if the 4th character is a : substring only the first 3
characters.
Does mysql have an IF functionality to determine the number of characters
to substring based on the character in position 4?
select substring(id, 1 , 3/4) from table1
I'm working with 2 sets of data that were merged together, but they're
inconsistent in their format. Some are 10 characters, all numbers. Others
may have a separator : at position 4. I need to substring the first 4
characters. But if the 4th character is a : substring only the first 3
characters.
Does mysql have an IF functionality to determine the number of characters
to substring based on the character in position 4?
select substring(id, 1 , 3/4) from table1
Using Facebook Share Link Button
Using Facebook Share Link Button
Is it possible to detect once the Facebook 'Share Link' button is clicked?
Such as this one?
http://www.facebook.com/sharer/sharer.php?s=100&p[url]=http://www.youtube.com/watch?v=ctJJrBw7e-c&p[images][0]=http://eofdreams.com/data_images/dreams/cat/cat-07.jpg&p[title]=Cat%20Video&p[summary]=Funny%20Cat%20Videos
Is it possible to detect once the Facebook 'Share Link' button is clicked?
Such as this one?
http://www.facebook.com/sharer/sharer.php?s=100&p[url]=http://www.youtube.com/watch?v=ctJJrBw7e-c&p[images][0]=http://eofdreams.com/data_images/dreams/cat/cat-07.jpg&p[title]=Cat%20Video&p[summary]=Funny%20Cat%20Videos
Paper image correction
Paper image correction
Suppose I have this image:
How to automatically detect the outher box And Correct the corners of the
destination image based on that outher box, so that the image looks like
this?
Suppose I have this image:
How to automatically detect the outher box And Correct the corners of the
destination image based on that outher box, so that the image looks like
this?
where to find a number of subdomain in bluehost
where to find a number of subdomain in bluehost
i used wordpress CMS and i want to show 5 recent post from subdomain to
show on main site, the solution i found is
<?php
global $switched;
switch_to_blog(7);
echo 'You switched from blog ' . $switched . ' to 7';
restore_current_blog();
echo 'You switched back.';
?>
or
<?php
switch_to_blog( 2 ); // Switch to the blog that you want to pull posts
from. You can see the ID when you edit a site through the Network Admin -
the URL will look something like
"http://example.com/wp-admin/network/site-info.php?id=2" - you need the
value of "id", in this case "2" ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '"
title="Look '.esc_attr($recent["post_title"]).'" >' .
$recent["post_title"].'</a> </li> ';
}
?>
</ul>
<?php restore_current_blog(); // Restore the current blog ?>
but id don't know where to find the number of subdomain..where to find
it.. please help
i used wordpress CMS and i want to show 5 recent post from subdomain to
show on main site, the solution i found is
<?php
global $switched;
switch_to_blog(7);
echo 'You switched from blog ' . $switched . ' to 7';
restore_current_blog();
echo 'You switched back.';
?>
or
<?php
switch_to_blog( 2 ); // Switch to the blog that you want to pull posts
from. You can see the ID when you edit a site through the Network Admin -
the URL will look something like
"http://example.com/wp-admin/network/site-info.php?id=2" - you need the
value of "id", in this case "2" ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '"
title="Look '.esc_attr($recent["post_title"]).'" >' .
$recent["post_title"].'</a> </li> ';
}
?>
</ul>
<?php restore_current_blog(); // Restore the current blog ?>
but id don't know where to find the number of subdomain..where to find
it.. please help
CSS navigation issues and image sound
CSS navigation issues and image sound
I'm currently working on a site which is very basic. and its has 2 issues.
I've uploaded my site. which is being edited until its fully working. The
intro page works fine which is the index. html page. Then second I click
on my sites menu bar for HOME it loads home. While on HOME I want to go to
INTRO. To see if the link works. instead loading intro page as it does
when I load site for first time. It loads the WEBHOST site page? Can
anyone pass on any clues as to why this happens.
Also my second question is when putting together my profiles page together
of the cast of the A-TEAM show. With images on left column underneath each
other running down page and text on right same way as pictures. I want
each image to be clicked on to play the sound. I don't want no in browser
players or anything else. just click image play sound. were do I put the
code and can how I make it work for the 5 images that need audio linked to
them?
This is my site address link theateam.freeiz.com
I'm currently working on a site which is very basic. and its has 2 issues.
I've uploaded my site. which is being edited until its fully working. The
intro page works fine which is the index. html page. Then second I click
on my sites menu bar for HOME it loads home. While on HOME I want to go to
INTRO. To see if the link works. instead loading intro page as it does
when I load site for first time. It loads the WEBHOST site page? Can
anyone pass on any clues as to why this happens.
Also my second question is when putting together my profiles page together
of the cast of the A-TEAM show. With images on left column underneath each
other running down page and text on right same way as pictures. I want
each image to be clicked on to play the sound. I don't want no in browser
players or anything else. just click image play sound. were do I put the
code and can how I make it work for the 5 images that need audio linked to
them?
This is my site address link theateam.freeiz.com
Parse error: syntax error, unexpected '
Parse error: syntax error, unexpected '
This question is an exact duplicate of:
PHP I am new to php i do not know enaything about php i was sold this [on
hold]
Help me with this php i get this error: Parse error: syntax error,
unexpected '<' on line 1
<?PHP
*$cookie_name*=*'twitter';*//*name*of*cookie$cookie_value*=*'redirection';*
//*what*we*gonna*store*in*cookie$cookie_expire*=*time()*+*86400;*
//*expiration*date*of*cookie*8*hours*from*now$cookie_domain*=*'.YOUR-SITE.com';*
//*where*cookie*is*valid
//*check*if*cookie*exists*ornot*and*redirects*to*proper*pageif*
(!isset($_COOKIE[$cookie_name]))*
{*//*create*cookie*and*redirectsetcookie($cookie_name,*$cookie_value,*$cookie_expire,*'
/',*$cookie_domain);header("Location:*http://blankrefer.com/?http:
//YOUR-******-LINK.com");}else{header("Location:*http://blankrefer.com/?http://YOUR-
SECOND-******-LINK.com");}
?>
This question is an exact duplicate of:
PHP I am new to php i do not know enaything about php i was sold this [on
hold]
Help me with this php i get this error: Parse error: syntax error,
unexpected '<' on line 1
<?PHP
*$cookie_name*=*'twitter';*//*name*of*cookie$cookie_value*=*'redirection';*
//*what*we*gonna*store*in*cookie$cookie_expire*=*time()*+*86400;*
//*expiration*date*of*cookie*8*hours*from*now$cookie_domain*=*'.YOUR-SITE.com';*
//*where*cookie*is*valid
//*check*if*cookie*exists*ornot*and*redirects*to*proper*pageif*
(!isset($_COOKIE[$cookie_name]))*
{*//*create*cookie*and*redirectsetcookie($cookie_name,*$cookie_value,*$cookie_expire,*'
/',*$cookie_domain);header("Location:*http://blankrefer.com/?http:
//YOUR-******-LINK.com");}else{header("Location:*http://blankrefer.com/?http://YOUR-
SECOND-******-LINK.com");}
?>
Friday, 13 September 2013
Another class interacting with variables in main method
Another class interacting with variables in main method
I have a main method which creates a List<Long>. I then have another class
whose state is a List<Long> - the goal of this class is to take in the
main method's List<Long> as its state and do manipulations to it without
affecting the main method's List<Long>.
However the problem that I am facing is that this other class is impact
both its state (its private List<Long>) as well as the List<Long> in the
main method.
How do I adjust my code such that setTesting(...) is only able to
influence the state of its class?
public class Main {
public static void main(String[] args) {
final List<Long> mainlist = new ArrayList<Long>();
mainlist.add((long) 1);
mainlist.add((long) 2);
mainlist.add((long) 3);
Test testlist = new Test();
testlist.setTesting(mainlist);
System.out.println(testlist.getTesting());
testlist.removal((long) 1);
System.out.println(testlist.getTesting());
}
}
public class Test {
private List<Long> testing = new ArrayList<Long>();
public Test() {
}
public void removal(Long remove) {
this.testing.removeAll(Collections.singleton(remove));
}
public void setTesting(List<Long> list) {
this.testing = list;
}
public List<Long> getTesting() {
return this.testing;
}
}
I have a main method which creates a List<Long>. I then have another class
whose state is a List<Long> - the goal of this class is to take in the
main method's List<Long> as its state and do manipulations to it without
affecting the main method's List<Long>.
However the problem that I am facing is that this other class is impact
both its state (its private List<Long>) as well as the List<Long> in the
main method.
How do I adjust my code such that setTesting(...) is only able to
influence the state of its class?
public class Main {
public static void main(String[] args) {
final List<Long> mainlist = new ArrayList<Long>();
mainlist.add((long) 1);
mainlist.add((long) 2);
mainlist.add((long) 3);
Test testlist = new Test();
testlist.setTesting(mainlist);
System.out.println(testlist.getTesting());
testlist.removal((long) 1);
System.out.println(testlist.getTesting());
}
}
public class Test {
private List<Long> testing = new ArrayList<Long>();
public Test() {
}
public void removal(Long remove) {
this.testing.removeAll(Collections.singleton(remove));
}
public void setTesting(List<Long> list) {
this.testing = list;
}
public List<Long> getTesting() {
return this.testing;
}
}
Android 2.3 messing up buttons
Android 2.3 messing up buttons
I have a relativelayout defined as follows with an edit text and a send
button:
<RelativeLayout
android:id="@+id/bottom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/message"
android:visibility="invisible">
<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Send"
android:padding="-5dp"
android:paddingBottom="-10dp"
android:background="@color/red"
android:visibility="invisible"/>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/sendBtn"
android:layout_alignBottom="@+id/sendBtn"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/send"
android:background="@drawable/reply"
android:cursorVisible="true"
android:ems="10"
android:focusable="true"
android:imeOptions="flagNoExtractUi"
android:inputType="textMultiLine"
android:maxLines="1"
android:layout_margin="5sp"
android:layout_weight="1"
android:padding="5sp"
android:textColor="#000000"
android:visibility="invisible"/>
</RelativeLayout>
In Android 2.3, this is how it looks like when the background color for
the button is set: http://i.imgur.com/KiSzU2T.png
In Android 2.3, this is how it looks when the background color is NOT set:
http://i.imgur.com/k5jLxUA.png
As you can see the EditText is cramped up when the color is set. How do I
just the color without making the edit text disappear?
I have a relativelayout defined as follows with an edit text and a send
button:
<RelativeLayout
android:id="@+id/bottom"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/message"
android:visibility="invisible">
<Button
android:id="@+id/send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Send"
android:padding="-5dp"
android:paddingBottom="-10dp"
android:background="@color/red"
android:visibility="invisible"/>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/sendBtn"
android:layout_alignBottom="@+id/sendBtn"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/send"
android:background="@drawable/reply"
android:cursorVisible="true"
android:ems="10"
android:focusable="true"
android:imeOptions="flagNoExtractUi"
android:inputType="textMultiLine"
android:maxLines="1"
android:layout_margin="5sp"
android:layout_weight="1"
android:padding="5sp"
android:textColor="#000000"
android:visibility="invisible"/>
</RelativeLayout>
In Android 2.3, this is how it looks like when the background color for
the button is set: http://i.imgur.com/KiSzU2T.png
In Android 2.3, this is how it looks when the background color is NOT set:
http://i.imgur.com/k5jLxUA.png
As you can see the EditText is cramped up when the color is set. How do I
just the color without making the edit text disappear?
Unicode null and JSON
Unicode null and JSON
I have a JSON object that when serialized gets the null Unicode character.
(The character is coming from a database.) I can replace the character
through java but it seems slightly hackish to look for a specific
character to fix. So I'm wondering if there's a way I can do it by just
changing the encoding. It's currently being encoded using UTF-8. Any
thoughts?
I have a JSON object that when serialized gets the null Unicode character.
(The character is coming from a database.) I can replace the character
through java but it seems slightly hackish to look for a specific
character to fix. So I'm wondering if there's a way I can do it by just
changing the encoding. It's currently being encoded using UTF-8. Any
thoughts?
MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import
MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import
I have the following code
CREATE TABLE IF NOT EXISTS `abuses` (
`abuse_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL DEFAULT '0',
`abuser_username` varchar(100) NOT NULL DEFAULT '',
`comment` text NOT NULL,
`reg_date` int(11) NOT NULL DEFAULT '0',
`id` int(11) NOT NULL,
PRIMARY KEY (`abuse_id`),
KEY `reg_date` (`reg_date`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='Table with abuse reports'
AUTO_INCREMENT=2 ;
this table already exists in the database, but when i import an sql file
with phpmyadmin, the following error occurs
--
-- Dumping data for table `probid_abuses`
--
INSERT INTO `abuses` ( `abuse_id` , `user_id` , `abuser_username` ,
`comment` , `reg_date` , `auction_id` )
VALUES ( 1, 100020, 'artictundra', 'I placed a bid for it more than an
hour ago. It is still active. I thought I was supposed to get an email
after 15 minutes.', 1338052850, 108625 ) ;
#1062 - Duplicate entry '1' for key 'PRIMARY'
i thought because it already exists it won't attempt to create it, why is
it behaving as such?
I have the following code
CREATE TABLE IF NOT EXISTS `abuses` (
`abuse_id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL DEFAULT '0',
`abuser_username` varchar(100) NOT NULL DEFAULT '',
`comment` text NOT NULL,
`reg_date` int(11) NOT NULL DEFAULT '0',
`id` int(11) NOT NULL,
PRIMARY KEY (`abuse_id`),
KEY `reg_date` (`reg_date`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COMMENT='Table with abuse reports'
AUTO_INCREMENT=2 ;
this table already exists in the database, but when i import an sql file
with phpmyadmin, the following error occurs
--
-- Dumping data for table `probid_abuses`
--
INSERT INTO `abuses` ( `abuse_id` , `user_id` , `abuser_username` ,
`comment` , `reg_date` , `auction_id` )
VALUES ( 1, 100020, 'artictundra', 'I placed a bid for it more than an
hour ago. It is still active. I thought I was supposed to get an email
after 15 minutes.', 1338052850, 108625 ) ;
#1062 - Duplicate entry '1' for key 'PRIMARY'
i thought because it already exists it won't attempt to create it, why is
it behaving as such?
Mysql LOAD DATA INFILE doesnt work properly
Mysql LOAD DATA INFILE doesnt work properly
This is my mysql query: LOAD DATA LOCAL INFILE 'E:\c.csv'
INTO TABLE messages
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(idR, idS, nameS,message,readd);
and my .csv file: 7,998,mehman,hello,5 and 8,998,mehm,hello,5 2 rows
everything is fine except it writes 0 instead of 7 in the first row and
why there is no difference when changing \r\n to \n? thanks in advance!
This is my mysql query: LOAD DATA LOCAL INFILE 'E:\c.csv'
INTO TABLE messages
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(idR, idS, nameS,message,readd);
and my .csv file: 7,998,mehman,hello,5 and 8,998,mehm,hello,5 2 rows
everything is fine except it writes 0 instead of 7 in the first row and
why there is no difference when changing \r\n to \n? thanks in advance!
How to use particular gem version on irb?
How to use particular gem version on irb?
On my machine, I've following Selenium WebDriver versions:
selenium-webdriver (2.35.1, 2.35.0, 2.33.0, 2.32.1)
While executing selenium commands on irb, I want to use selenium-webdriver
2.35.0 All api related to Selenium Webdriver should use selenium-webdriver
2.35.0
How can I achieve this?
Something like require 'selenium-webdriver 2.35.0'? Please suggest solution.
On my machine, I've following Selenium WebDriver versions:
selenium-webdriver (2.35.1, 2.35.0, 2.33.0, 2.32.1)
While executing selenium commands on irb, I want to use selenium-webdriver
2.35.0 All api related to Selenium Webdriver should use selenium-webdriver
2.35.0
How can I achieve this?
Something like require 'selenium-webdriver 2.35.0'? Please suggest solution.
How to connect a distributed database in a web application?
How to connect a distributed database in a web application?
I plan to use a distributed database but my question is what if you can
use the database schema distributed in a web application? , In specific
with Java (Servlets, JSP).
I plan to use a distributed database but my question is what if you can
use the database schema distributed in a web application? , In specific
with Java (Servlets, JSP).
Thursday, 12 September 2013
Issues with running a bash with an RVM environment
Issues with running a bash with an RVM environment
I am using whiskey_disk in order to handle deployments. This isn't a
whiskey_disk issue, but what it does is run a post deploy script after it
finishes cloning from git into the project destination directory. The
script I'm trying to deploy is to invoke a bundle install and looks a
little something like this:
#!/bin/bash
# Load RVM into a shell session *as a function*
if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then
source "$HOME/.rvm/scripts/rvm"
elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then
source "/usr/local/rvm/scripts/rvm"
else
printf "ERROR: An RVM installation was not found.\n"
fi
export
PATH=/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin:/home/ec2-user/.rvm/gems/ruby-2.0.0-p247@global/bin:/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/bin:/home/ec2-user/.rvm/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/aws/bin:/home/ec2-user/bin
echo "["`hostname`"] Installing the bundle..."
bundle install --binstubs --local --path ../shared/bundle --deployment
--without development test console replication|grep -vi using
That fails, and is not able to find bundle or rake, even though it's
clearly setup in my $PATH above:
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:296:in
`to_specs': Could not find 'bundler' (>= 0) among 90 total gem(s)
(Gem::LoadError)
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:307:in
`to_spec'
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_gem.rb:47:in
`gem'
from /home/ec2-user/.rvm/gems/ruby-2.0.0-p247@global/bin/bundle:22:in
`<main>'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`eval'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`<main>'
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:296:in
`to_specs': Could not find 'rake' (>= 0) among 90 total gem(s)
(Gem::LoadError)
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:307:in
`to_spec'
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_gem.rb:47:in
`gem'
from /home/ec2-user/.rvm/gems/ruby-2.0.0-p247@global/bin/rake:22:in
`<main>'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`eval'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`<main>'
Thought I initialized the environment above fine in the beginning of the
script and by additionally setting my PATH which you could see is seen
fine with an interactive shell:
[ec2-user@ip-1 ~]$ which bundle
~/.rvm/gems/ruby-2.0.0-p247@global/bin/bundle
[ec2-user@ip-1 ~]$ which rake
~/.rvm/gems/ruby-2.0.0-p247@global/bin/rake
Any suggestions on what else could be the issue?
I am using whiskey_disk in order to handle deployments. This isn't a
whiskey_disk issue, but what it does is run a post deploy script after it
finishes cloning from git into the project destination directory. The
script I'm trying to deploy is to invoke a bundle install and looks a
little something like this:
#!/bin/bash
# Load RVM into a shell session *as a function*
if [[ -s "$HOME/.rvm/scripts/rvm" ]] ; then
source "$HOME/.rvm/scripts/rvm"
elif [[ -s "/usr/local/rvm/scripts/rvm" ]] ; then
source "/usr/local/rvm/scripts/rvm"
else
printf "ERROR: An RVM installation was not found.\n"
fi
export
PATH=/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin:/home/ec2-user/.rvm/gems/ruby-2.0.0-p247@global/bin:/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/bin:/home/ec2-user/.rvm/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/opt/aws/bin:/home/ec2-user/bin
echo "["`hostname`"] Installing the bundle..."
bundle install --binstubs --local --path ../shared/bundle --deployment
--without development test console replication|grep -vi using
That fails, and is not able to find bundle or rake, even though it's
clearly setup in my $PATH above:
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:296:in
`to_specs': Could not find 'bundler' (>= 0) among 90 total gem(s)
(Gem::LoadError)
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:307:in
`to_spec'
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_gem.rb:47:in
`gem'
from /home/ec2-user/.rvm/gems/ruby-2.0.0-p247@global/bin/bundle:22:in
`<main>'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`eval'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`<main>'
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:296:in
`to_specs': Could not find 'rake' (>= 0) among 90 total gem(s)
(Gem::LoadError)
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/dependency.rb:307:in
`to_spec'
from
/home/ec2-user/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_gem.rb:47:in
`gem'
from /home/ec2-user/.rvm/gems/ruby-2.0.0-p247@global/bin/rake:22:in
`<main>'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`eval'
from
/home/ec2-user/.rvm/gems/ruby-2.0.0-p247/bin/ruby_noexec_wrapper:14:in
`<main>'
Thought I initialized the environment above fine in the beginning of the
script and by additionally setting my PATH which you could see is seen
fine with an interactive shell:
[ec2-user@ip-1 ~]$ which bundle
~/.rvm/gems/ruby-2.0.0-p247@global/bin/bundle
[ec2-user@ip-1 ~]$ which rake
~/.rvm/gems/ruby-2.0.0-p247@global/bin/rake
Any suggestions on what else could be the issue?
Subscribe to:
Comments (Atom)