Conditional operator successfully compiled in windows but gives error in
Linux
Please help me reason out for the error I am getting with this statement,
in Linux environment.
p_pAphErrorMessage->getSvc()?l_AphUpdateMessage->setSvc(p_pAphErrorMessage->getSvc()):0;
p_pAphErrorMessage->getObj()?l_AphUpdateMessage->setObj(p_pAphErrorMessage->getObj()):0;
This code is successfully compiled in windows but its giving error in
Linux enviroment.
src/aph.cpp:7320: error:
âl_AphUpdateMessage->AphMessage::setSvc(((AphUpdateMessage*)p_pAphErrorMessage)->AphUpdateMessage::<anonymous>.AphFidValuesMessage::<anonymous>.AphMessage::getSvc())â
has type âvoidâ and is not a throw-expression
src/aph.cpp:7321: error:
âl_AphUpdateMessage->AphMessage::setObj(((AphUpdateMessage*)p_pAphErrorMessage)->AphUpdateMessage::<anonymous>.AphFidValuesMessage::<anonymous>.AphMessage::getObj())â
has type âvoidâ and is not a throw-expression
I investigated this a bit and suspect returning 0; could be the reason for
it. Can we use conditional operator in such a way to use it just for if
not for else, eg,
c= a?a:/*DO NOTHING*/;
But, this way I am not getting any success in compilation. Any other
recommended way to achieve it.
Thursday, 3 October 2013
Wednesday, 2 October 2013
Switching workspaces with dual monitors
Switching workspaces with dual monitors
I'm working on Ubuntu 13.04 and have a second monitor connected with a
VGA. I currently have the second monitor as an extended screen. I was
wondering if there was a way that I could set it up so I could put a
window on my second monitor, switch workspaces on my main display and the
second monitor display wouldn't change?
I think it was a thing in the past, but I haven't found a solution. I just
want my second monitor to be consistent while my main workspace remains
dynamic.
I'm working on Ubuntu 13.04 and have a second monitor connected with a
VGA. I currently have the second monitor as an extended screen. I was
wondering if there was a way that I could set it up so I could put a
window on my second monitor, switch workspaces on my main display and the
second monitor display wouldn't change?
I think it was a thing in the past, but I haven't found a solution. I just
want my second monitor to be consistent while my main workspace remains
dynamic.
Excel VBA: How to obtain a reference to a Shape from the ChartObject
Excel VBA: How to obtain a reference to a Shape from the ChartObject
I am trying to obtain a reference to a Shape in a Worksheet, corresponding
to a ChartObject. I found no certain way of doing this. The only
approximation, by trial-and-error and simply tested in a few cases, is
assuming that the ZOrder of a ChartObject is the same as the
ZOrderPosition of the corresponding Shape:
Function chobj2shape(ByRef cho As ChartObject) As Shape
' It appears that the ZOrder of a ChartObject is the same as the
ZOrderPosition of the corresponding Shape
Dim zo As Long
Dim ws As Worksheet
Dim shc As Shapes
Dim sh As Shape
zo = cho.ZOrder
Set ws = cho.Parent
Set shc = ws.Shapes
Set sh = shc.Item(zo)
Set chobj2shape = sh
'Set sh = Nothing
End Function
(a slight excess of defined variables is used for debugging purposes).
Is there any more certain way of doing this?
I am trying to obtain a reference to a Shape in a Worksheet, corresponding
to a ChartObject. I found no certain way of doing this. The only
approximation, by trial-and-error and simply tested in a few cases, is
assuming that the ZOrder of a ChartObject is the same as the
ZOrderPosition of the corresponding Shape:
Function chobj2shape(ByRef cho As ChartObject) As Shape
' It appears that the ZOrder of a ChartObject is the same as the
ZOrderPosition of the corresponding Shape
Dim zo As Long
Dim ws As Worksheet
Dim shc As Shapes
Dim sh As Shape
zo = cho.ZOrder
Set ws = cho.Parent
Set shc = ws.Shapes
Set sh = shc.Item(zo)
Set chobj2shape = sh
'Set sh = Nothing
End Function
(a slight excess of defined variables is used for debugging purposes).
Is there any more certain way of doing this?
fluidsynth noteon doesn't produce sound
fluidsynth noteon doesn't produce sound
In a Linux terminal I am running:
fluidsynth -a alsa Tim.sf2
in the fluidsynth shell I try to play a note
noteon 0 60 30
But nothing plays. What am I missing?
In a Linux terminal I am running:
fluidsynth -a alsa Tim.sf2
in the fluidsynth shell I try to play a note
noteon 0 60 30
But nothing plays. What am I missing?
yGuard Obfuscate code in case insensitive file system as Windows
yGuard Obfuscate code in case insensitive file system as Windows
I try to obfuscase my JAR file in Windows by yGuard but classes in the
same package are renamed to the same name (ignored case).
Ex.: MyCookieUtils.class => A.class MyFormatterUtils.class => a.class
Windows can recognize only one file with name A.class or a.class in a
folder, the other is overrided. So it cannot run after obfuscation code :(
Anyone can help? Thanks
I try to obfuscase my JAR file in Windows by yGuard but classes in the
same package are renamed to the same name (ignored case).
Ex.: MyCookieUtils.class => A.class MyFormatterUtils.class => a.class
Windows can recognize only one file with name A.class or a.class in a
folder, the other is overrided. So it cannot run after obfuscation code :(
Anyone can help? Thanks
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();
}
}
}
Oracle EXISTS clause Vs ROWNUM = 1
Oracle EXISTS clause Vs ROWNUM = 1
For a long time, I have been using the EXISTS clause to determine if at
least one record exists in a given table for a given condition. for
example - if I wanted to see if an employee by lastname = 'smith' exists
in the "employee" table, I used the following query
select 1 into v_exists_flag from dual where exists ( select 1 from
employee where lastname = 'smith' )
This is definitely more efficient than using the count(*) clause.
select count(*) into v_count from employee where lastname = 'smith'
if v_count > 0 then....
But, recently someone mentioned that using ROWNUM = 1 has better
performance than using the EXISTS clause as shown below
select 1 into v_count from employee where lastname = 'smith' and rownum = 1
Is this correct? Can someone confirm this.
Thanks in advance
For a long time, I have been using the EXISTS clause to determine if at
least one record exists in a given table for a given condition. for
example - if I wanted to see if an employee by lastname = 'smith' exists
in the "employee" table, I used the following query
select 1 into v_exists_flag from dual where exists ( select 1 from
employee where lastname = 'smith' )
This is definitely more efficient than using the count(*) clause.
select count(*) into v_count from employee where lastname = 'smith'
if v_count > 0 then....
But, recently someone mentioned that using ROWNUM = 1 has better
performance than using the EXISTS clause as shown below
select 1 into v_count from employee where lastname = 'smith' and rownum = 1
Is this correct? Can someone confirm this.
Thanks in advance
Find maximum number of egdes of a graph.
Find maximum number of egdes of a graph.
Find the maximum number of egdes in a graph with n vertices s.t.
(a)the graph has no odd cycle . (b)the graph has no even cycle .
Find the maximum number of egdes in a graph with n vertices s.t.
(a)the graph has no odd cycle . (b)the graph has no even cycle .
What's the coin in the curosity rover=?iso-8859-1?Q?=3F_=96_space.stackexchange.com?=
What's the coin in the curosity rover? – space.stackexchange.com
In the image below was taken from the curiosity rover(i hope). But there
is coin in the image. Is that really a coin or some kind of button. If so
what kind of function it has ? Is that really ...
In the image below was taken from the curiosity rover(i hope). But there
is coin in the image. Is that really a coin or some kind of button. If so
what kind of function it has ? Is that really ...
Monday, 30 September 2013
Uninstalled server 2008 now router won't handle DHCP
Uninstalled server 2008 now router won't handle DHCP
My set up is this. server behind router, router has a server and switch
connected to it with multiple computers. router used to serve DHCP and
DNS, a couple of days ago installed AD, DNS and DHCP on the server, and
the server gave out IP's.
For various reasons we had to uninstall the domain on our server. I
removed AD, DHCP and DNS from the roles and set the router back to serving
DHCP and DNS. Now I can't get computers on the network. I reset my router
back to factory defaults, and if I plug a computer directly into the
router I can get a IP address, but all the computers behind the switch
can't get an IP address and can't see the router. All my computers say
unidentified network, and if I ping the router it says host is
unreachable.
On the other hand, my wireless devices are just fine and connect no
problem. But for desktops, ipconfig /release doesn't release anything and
/renew can't find a server to renew on. My router log shows several FIN
scans but they are from innocuous websites (google, netgear) and it shows
a couple of smurf attacks but they are all from my external IP. Any ideas?
the server isn't even connected to the route right now, and all the
computers are set for dynamic IP addresses.. I don't know what else to
try? Any help?
My set up is this. server behind router, router has a server and switch
connected to it with multiple computers. router used to serve DHCP and
DNS, a couple of days ago installed AD, DNS and DHCP on the server, and
the server gave out IP's.
For various reasons we had to uninstall the domain on our server. I
removed AD, DHCP and DNS from the roles and set the router back to serving
DHCP and DNS. Now I can't get computers on the network. I reset my router
back to factory defaults, and if I plug a computer directly into the
router I can get a IP address, but all the computers behind the switch
can't get an IP address and can't see the router. All my computers say
unidentified network, and if I ping the router it says host is
unreachable.
On the other hand, my wireless devices are just fine and connect no
problem. But for desktops, ipconfig /release doesn't release anything and
/renew can't find a server to renew on. My router log shows several FIN
scans but they are from innocuous websites (google, netgear) and it shows
a couple of smurf attacks but they are all from my external IP. Any ideas?
the server isn't even connected to the route right now, and all the
computers are set for dynamic IP addresses.. I don't know what else to
try? Any help?
Guidelines for typesetting fractions tex.stackexchange.com
Guidelines for typesetting fractions – tex.stackexchange.com
I realize that this question is to some extent subjective. However, I
suspect that there are some common standards regarding how fractions ought
to be typeset in mathematics. The guide Mathematical …
I realize that this question is to some extent subjective. However, I
suspect that there are some common standards regarding how fractions ought
to be typeset in mathematics. The guide Mathematical …
Emmet plugin in Sublime Text 2 with Soy Templates
Emmet plugin in Sublime Text 2 with Soy Templates
Has anyone gotten the Emmet plugin to work with Soy Templates in Sublime
Text 2? I tried following the recommendation here:
http://docs.emmet.io/customization/syntax-profiles/ and added a
syntaxProfiles.json file with the following:
{ "SoyTemplate": "html" }
but that didn't do anything.
Any advice would be tremendously appreciated. Thank you.
Has anyone gotten the Emmet plugin to work with Soy Templates in Sublime
Text 2? I tried following the recommendation here:
http://docs.emmet.io/customization/syntax-profiles/ and added a
syntaxProfiles.json file with the following:
{ "SoyTemplate": "html" }
but that didn't do anything.
Any advice would be tremendously appreciated. Thank you.
UIPopoverViewController in ios7?
UIPopoverViewController in ios7?
In iOS 6 UIPopoverView have border with black translucent colour but iOS 7
do not have border because iOS 7 become transparent. how to add border
with black translucent in iOS 7.
Can anyone know please help me to solve this problem?
In iOS 6 UIPopoverView have border with black translucent colour but iOS 7
do not have border because iOS 7 become transparent. how to add border
with black translucent in iOS 7.
Can anyone know please help me to solve this problem?
Sunday, 29 September 2013
What is the convenience method to compare two NSNumbers with float values using limited precision?
What is the convenience method to compare two NSNumbers with float values
using limited precision?
What is the Objective-C convenience method for comparing a couple of
NSNumbers with float values to see if they are roughly equivalent (two
decimal places of precision is fine)?
I would use something other than floats if there was an option that did
not change the number around randomly. But anyway I'm already using floats
so... .
I imagine there must be something like:
[myNumber isEqualTo:myOtherNumber withPrecision:2];
But actually, amazingly I can't find such a convenience method. What am I
missing here?
Would it help to cast the two numbers to NSDecimal or something?
using limited precision?
What is the Objective-C convenience method for comparing a couple of
NSNumbers with float values to see if they are roughly equivalent (two
decimal places of precision is fine)?
I would use something other than floats if there was an option that did
not change the number around randomly. But anyway I'm already using floats
so... .
I imagine there must be something like:
[myNumber isEqualTo:myOtherNumber withPrecision:2];
But actually, amazingly I can't find such a convenience method. What am I
missing here?
Would it help to cast the two numbers to NSDecimal or something?
Connecting to host from Android via USB
Connecting to host from Android via USB
Okay so here is the background of this problem. I commute a lot on the
train and build a lot of PHP web apps optimized for mobile devices. I
would like to develop code on a netbook (Running Ubuntu Server) with no
GUI. All development done using Vim directly on the netbook.
I would like to connect up my Nexus 4 to the netbook via USB and "connect"
to the netbooks web server in the chrome browser. I can only use USB for
this since I won't be having any reliable internet access.
I understand that using adb from the Android SDK, you can forward a port
from the netbook to the phone. However, I need to do it the other way
around.
For example:
Run a web server on the netbook on port 4000
Connect phone via USB
Somehow forward port 4000 on the phone to port 4000 on the netbook
Open chrome browser on phone and go to localhost:4000.
I am aware of the "reverse port forwarding" method that is described in
the Google docs at
https://developers.google.com/chrome-developer-tools/docs/remote-debugging.
However, this requires an installation of chrome on the netbook. I don't
want to have to install an entire GUI just for this.
Okay so here is the background of this problem. I commute a lot on the
train and build a lot of PHP web apps optimized for mobile devices. I
would like to develop code on a netbook (Running Ubuntu Server) with no
GUI. All development done using Vim directly on the netbook.
I would like to connect up my Nexus 4 to the netbook via USB and "connect"
to the netbooks web server in the chrome browser. I can only use USB for
this since I won't be having any reliable internet access.
I understand that using adb from the Android SDK, you can forward a port
from the netbook to the phone. However, I need to do it the other way
around.
For example:
Run a web server on the netbook on port 4000
Connect phone via USB
Somehow forward port 4000 on the phone to port 4000 on the netbook
Open chrome browser on phone and go to localhost:4000.
I am aware of the "reverse port forwarding" method that is described in
the Google docs at
https://developers.google.com/chrome-developer-tools/docs/remote-debugging.
However, this requires an installation of chrome on the netbook. I don't
want to have to install an entire GUI just for this.
Python method with *args and **args
Python method with *args and **args
I am trying to understand a method that uses *args, **kwargs,
Here is the complete details of the method,
Help on method open in module pyaudio:
open(self, *args, **kwargs) method of pyaudio.PyAudio instance
Open a new stream. See constructor for
:py:func:`Stream.__init__` for parameter details.
:returns: A new :py:class:`Stream`
..
class pyaudio.Stream(PA_manager, rate, channels, format, input=False,
output=False, input_device_index=None, output_device_index=None,
frames_per_buffer=1024, start=True,
input_host_api_specific_stream_info=None,
output_host_api_specific_stream_info=None, stream_callback=None)
PortAudio Stream Wrapper.
Use PyAudio.open() to make a new Stream.
__init__(PA_manager, rate, channels, format, input=False, output=False,
input_device_index=None, output_device_index=None, frames_per_buffer=1024,
start=True, input_host_api_specific_stream_info=None,
output_host_api_specific_stream_info=None, stream_callback=None)
Initialize a stream; this should be called by PyAudio.open(). A stream can
either be input, output, or both.
What I want to do is to use
PyAudio.open()
method and set the value of input_device_index= to 1
But I couldn't understand how to pass the arguments in this function as I
have no idea how these *args and **kwargs works.
I am trying to understand a method that uses *args, **kwargs,
Here is the complete details of the method,
Help on method open in module pyaudio:
open(self, *args, **kwargs) method of pyaudio.PyAudio instance
Open a new stream. See constructor for
:py:func:`Stream.__init__` for parameter details.
:returns: A new :py:class:`Stream`
..
class pyaudio.Stream(PA_manager, rate, channels, format, input=False,
output=False, input_device_index=None, output_device_index=None,
frames_per_buffer=1024, start=True,
input_host_api_specific_stream_info=None,
output_host_api_specific_stream_info=None, stream_callback=None)
PortAudio Stream Wrapper.
Use PyAudio.open() to make a new Stream.
__init__(PA_manager, rate, channels, format, input=False, output=False,
input_device_index=None, output_device_index=None, frames_per_buffer=1024,
start=True, input_host_api_specific_stream_info=None,
output_host_api_specific_stream_info=None, stream_callback=None)
Initialize a stream; this should be called by PyAudio.open(). A stream can
either be input, output, or both.
What I want to do is to use
PyAudio.open()
method and set the value of input_device_index= to 1
But I couldn't understand how to pass the arguments in this function as I
have no idea how these *args and **kwargs works.
Entity Framework 5 Model first code generation
Entity Framework 5 Model first code generation
I'm using Entity Framwork 5.0 and visual studio 2010. The entities,
contexts codes are generated in one file, I saw so many tutorials with VS
2012 which the generated codes are separated. How could I do this with VS
2010?
I'm using Entity Framwork 5.0 and visual studio 2010. The entities,
contexts codes are generated in one file, I saw so many tutorials with VS
2012 which the generated codes are separated. How could I do this with VS
2010?
Saturday, 28 September 2013
Error 404 on Symfony2
Error 404 on Symfony2
I have 3 symfony2 apps, 2 wors fine, but the third just works for the
default page. The rest of the routes throw a 404 error. Environment is:
Ubunto 12.04 VirtualBox, apache 2, php 5.3.10, Mongobd.
This is de VHost content: DocumentRoot
/home/adminuser/webs/servergrove/web ServerName servergrove.local ErrorLog
/var/log/apache2/servergrove-error.log CustomLog
/var/log/apache2/servergrove-access.log combined AllowOverride All
This is the routing.yml:
homepage: pattern: / defaults: { _controller:
SGLiveChatBundle:Default:index }
sglc_chat_homepage: pattern: /sglivechat defaults: { _controller:
SGLiveChatBundle:Chat:index }
sglc_chat_invite: pattern: /sglivechat/{sessId}/invite defaults: {
_controller: SGLiveChatBundle:Chat:invite }
... and so on.
The following url works fine: http://servergrove.local/
The following (and any other) doesn't: http://servergrove.local/sglivechat
Not Found The requested URL /sglivechat was not found on this server.
Apache/2.2.22 (Ubuntu) Server at servergrove.local Port 80
I have very little experience with symfony. I'd think is related with
rewrite engine, but the other two projects works ok.
I've got the following on the command line:
adminuser@adminuser-VirtualBox-073n:~/webs/servergrove$ php app/console
router:debug [router] Current routes Name Method Pattern homepage ANY /
sglc_admin_index GET /admin/sglivechat prueba ANY /prueba
adminuser@adminuser-VirtualBox-073n:~/webs/servergrove$ php app/console
router:dump-apache RewriteCond %{PATH_INFO} ^/$ RewriteRule .* app.php
[QSA,L,E=ROUTING_route:homepage,E=ROUTING_controller:ServerGrove\SGLiveChatBundle\Controller\DefaultController::indexAction]
RewriteCond %{REQUEST_METHOD} ^(get) [NC] RewriteCond %{PATH_INFO}
^/admin/sglivechat$ RewriteRule .* app.php
[QSA,L,E=ROUTING_route:sglc_admin_index,E=ROUTING_controller:ServerGrove\SGLiveChatBundle\Controller\AdminController::indexAction]
RewriteCond %{PATH_INFO} ^/prueba$ RewriteRule .* app.php
[QSA,L,E=ROUTING_route:prueba,E=ROUTING_controller:ServerGrove\SGLiveChatBundle\Controller\DefaultController::pruebaAction]
Any idea of what can be wrong?
I have 3 symfony2 apps, 2 wors fine, but the third just works for the
default page. The rest of the routes throw a 404 error. Environment is:
Ubunto 12.04 VirtualBox, apache 2, php 5.3.10, Mongobd.
This is de VHost content: DocumentRoot
/home/adminuser/webs/servergrove/web ServerName servergrove.local ErrorLog
/var/log/apache2/servergrove-error.log CustomLog
/var/log/apache2/servergrove-access.log combined AllowOverride All
This is the routing.yml:
homepage: pattern: / defaults: { _controller:
SGLiveChatBundle:Default:index }
sglc_chat_homepage: pattern: /sglivechat defaults: { _controller:
SGLiveChatBundle:Chat:index }
sglc_chat_invite: pattern: /sglivechat/{sessId}/invite defaults: {
_controller: SGLiveChatBundle:Chat:invite }
... and so on.
The following url works fine: http://servergrove.local/
The following (and any other) doesn't: http://servergrove.local/sglivechat
Not Found The requested URL /sglivechat was not found on this server.
Apache/2.2.22 (Ubuntu) Server at servergrove.local Port 80
I have very little experience with symfony. I'd think is related with
rewrite engine, but the other two projects works ok.
I've got the following on the command line:
adminuser@adminuser-VirtualBox-073n:~/webs/servergrove$ php app/console
router:debug [router] Current routes Name Method Pattern homepage ANY /
sglc_admin_index GET /admin/sglivechat prueba ANY /prueba
adminuser@adminuser-VirtualBox-073n:~/webs/servergrove$ php app/console
router:dump-apache RewriteCond %{PATH_INFO} ^/$ RewriteRule .* app.php
[QSA,L,E=ROUTING_route:homepage,E=ROUTING_controller:ServerGrove\SGLiveChatBundle\Controller\DefaultController::indexAction]
RewriteCond %{REQUEST_METHOD} ^(get) [NC] RewriteCond %{PATH_INFO}
^/admin/sglivechat$ RewriteRule .* app.php
[QSA,L,E=ROUTING_route:sglc_admin_index,E=ROUTING_controller:ServerGrove\SGLiveChatBundle\Controller\AdminController::indexAction]
RewriteCond %{PATH_INFO} ^/prueba$ RewriteRule .* app.php
[QSA,L,E=ROUTING_route:prueba,E=ROUTING_controller:ServerGrove\SGLiveChatBundle\Controller\DefaultController::pruebaAction]
Any idea of what can be wrong?
jQuery: hide/ show + change text clicking the same class
jQuery: hide/ show + change text clicking the same class
I have a group of words that on click should show and hide elements. In
addition, I need to change that first group of words. So if it gets
clicked, it shows the container with content + gets changed to hide. In
alternative, when it is clicked again, it should hide the content and
become 'show' again.
<div class="hide-show-button">Click Here to <span
id="hide-show-changed">Show</span></div>
<div class="hide-show">
.... content
</div>
<script>
$('.hide-show').hide();
$('.hide-show-button').click(function(){
$('.hide-show').show();
$('#hide-show-changed').text('Hide');
}, function() {
$('.hide-show').hide();
$('#hide-show-changed').text('Show');
});
</script>
Thanks
I have a group of words that on click should show and hide elements. In
addition, I need to change that first group of words. So if it gets
clicked, it shows the container with content + gets changed to hide. In
alternative, when it is clicked again, it should hide the content and
become 'show' again.
<div class="hide-show-button">Click Here to <span
id="hide-show-changed">Show</span></div>
<div class="hide-show">
.... content
</div>
<script>
$('.hide-show').hide();
$('.hide-show-button').click(function(){
$('.hide-show').show();
$('#hide-show-changed').text('Hide');
}, function() {
$('.hide-show').hide();
$('#hide-show-changed').text('Show');
});
</script>
Thanks
Not able to use custom layout in ArrayAdapter
Not able to use custom layout in ArrayAdapter
I'm new to android, I want to use my custom layout file instead of
simple_list_item_1 but its not allowing to do so. I want to add an
backgroud image(which is defined in layout->custom_view.xml) to each items
in the list OR help me to set the backgroud for the whole page, In the
below code where should I use the setContentView Method. Also let me know
if any changes are to be made in the below .xml file.
public class Planet extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
//setContentView(R.layout.custom_view); Tried to set the view from
here but the application is crashing...
String[] planet_names = new String[]
{"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Sun"};
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
planet_names);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view,
int position, long id) {
if(position == 0)
{
Intent myIntent = new
Intent(Planet.this, Galaxy.class);
startActivityForResult(myIntent, 0);
}
}
});
}
custom_view.xml file is as follows,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<ListView
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
I'm new to android, I want to use my custom layout file instead of
simple_list_item_1 but its not allowing to do so. I want to add an
backgroud image(which is defined in layout->custom_view.xml) to each items
in the list OR help me to set the backgroud for the whole page, In the
below code where should I use the setContentView Method. Also let me know
if any changes are to be made in the below .xml file.
public class Planet extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState)
{super.onCreate(savedInstanceState);
//setContentView(R.layout.custom_view); Tried to set the view from
here but the application is crashing...
String[] planet_names = new String[]
{"Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune","Sun"};
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
planet_names);
setListAdapter(adapter);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view,
int position, long id) {
if(position == 0)
{
Intent myIntent = new
Intent(Planet.this, Galaxy.class);
startActivityForResult(myIntent, 0);
}
}
});
}
custom_view.xml file is as follows,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<ListView
android:id="@+id/listView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Cannot print full url text when there is slash in URL
Cannot print full url text when there is slash in URL
I have made a form where when i send values with a slash, in the same page
i read the url value sent by my form input and prints it from $_POST
request value. But something strange happens, if the sentence does not
contain slashes it reads it all.If it contains one slash it reads the
request until the slash and the rest part is not printed. I have used
urldecode and stripslashes but always the rest part after slash is not
printed.
<form autocomplete='off' style='margin-left:8px;' method='POST'
name='form'>
<input type='hidden' value='$parameters2' name='de'>
<input type='hidden' value='$parameters' name='ef'>
<input type='hidden' value='$parameters4' name='dee'>
<input autocomplete='off' id='text' type='text' name='query_string'
size='17' class='BodyCopy' style='border: none; width:89%;
font-family:monospace; font-size:12px;' autofocus></form>
$parameters = $_POST['query_string'];
$parameters3 = $_POST['de'];
$parameters4 = $_POST['ef'];
$parameters5 = $_POST['dee'];
echo $parameters;
echo $parameters3;
echo $parameters4;
echo $parameters5;
I have made a form where when i send values with a slash, in the same page
i read the url value sent by my form input and prints it from $_POST
request value. But something strange happens, if the sentence does not
contain slashes it reads it all.If it contains one slash it reads the
request until the slash and the rest part is not printed. I have used
urldecode and stripslashes but always the rest part after slash is not
printed.
<form autocomplete='off' style='margin-left:8px;' method='POST'
name='form'>
<input type='hidden' value='$parameters2' name='de'>
<input type='hidden' value='$parameters' name='ef'>
<input type='hidden' value='$parameters4' name='dee'>
<input autocomplete='off' id='text' type='text' name='query_string'
size='17' class='BodyCopy' style='border: none; width:89%;
font-family:monospace; font-size:12px;' autofocus></form>
$parameters = $_POST['query_string'];
$parameters3 = $_POST['de'];
$parameters4 = $_POST['ef'];
$parameters5 = $_POST['dee'];
echo $parameters;
echo $parameters3;
echo $parameters4;
echo $parameters5;
Friday, 27 September 2013
Writing a CakePHP find Join
Writing a CakePHP find Join
I have a SQL query that I'm trying to convert into a CakePHP find, but I'm
not sure how to structure it... could someone please provide a little
assistance?
SELECT texts.*, people.id, people.first_name, people.last_name FROM texts
NATURAL JOIN (
SELECT person_id, MAX(id) AS id
FROM texts
WHERE texts.status = 'received'
GROUP BY person_id
) t RIGHT JOIN people ON people.id = t.person_id
WHERE texts.body is not null
AND texts.created > '$since'
AND person.counselor_id = '2'
ORDER BY texts.created DESC
Thank you!
I have a SQL query that I'm trying to convert into a CakePHP find, but I'm
not sure how to structure it... could someone please provide a little
assistance?
SELECT texts.*, people.id, people.first_name, people.last_name FROM texts
NATURAL JOIN (
SELECT person_id, MAX(id) AS id
FROM texts
WHERE texts.status = 'received'
GROUP BY person_id
) t RIGHT JOIN people ON people.id = t.person_id
WHERE texts.body is not null
AND texts.created > '$since'
AND person.counselor_id = '2'
ORDER BY texts.created DESC
Thank you!
Finding the first point of great circle Intersection
Finding the first point of great circle Intersection
I have a problem I've been trying to solve and I cannot come up with the
answer. I have written a function in Matlab which, given two lat/lon
points and two bearings, will return the two great circle points of
intersection.
However, what I really need is the first great circle point of
intersection along the two initial headings. I.e. if two airplanes begin
at lat/lon points 1 and 2, with initial bearings of bearing1 and bearing2,
which of the two great circle intersection points is the first one they
encounter? There are many solutions (using haversine) which will give me
the closer of the two points, but I don't actually care about which is
closer, I care about which I will encounter first given specific start
points and headings. There are many cases where the closer of the two
intersections is actually the second intersection encountered.
Now, I realize I could do this with lots of conditional statements for
handling the different cases, but I figure there's got to be a way to
handle it with regard to the order I take all my cross products (function
code given below), but I simply can't come up with the right solution! I
should also mention that this function is going to be used in a large
computationally intensive model, and so I'm thinking the solution to this
problem needs to be rather elegant/speedy. Can anyone help me with this
problem?
The following is not my function code (I can't list that here), but it is
the pseudo code that my function was based off of:
%Given inputs of lat1,lon1,Bearing1,lat2,lon2,Bearing2:
%Calculate arbitrary secondary point along same initial bearing from first
%point
dAngle = 45;
lat3 = asind( sind(lat1)*cosd(dAngle) +
cosd(lat1)*sind(dAngle)*cosd(Bearing1));
lon3 = lon1 + atan2( sind(Bearing1)*sind(dAngle)*cosd(lat1),
cosd(dAngle)-sind(lat1)*sind(lat3) )*180/pi;
lat4 = asind( sind(lat2)*cosd(dAngle) +
cosd(lat2)*sind(dAngle)*cosd(Bearing2));
lon4 = lon2 + atan2( sind(Bearing2)*sind(dAngle)*cosd(lat2),
cosd(dAngle)-sind(lat2)*sind(lat4) )*180/pi;
%% Calculate unit vectors
% We now have two points defining each of the two great circles. We need
% to calculate unit vectors from the center of the Earth to each of these
% points
[Uvec1(1),Uvec1(2),Uvec1(3)] = sph2cart(lon1*pi/180,lat1*pi/180,1);
[Uvec2(1),Uvec2(2),Uvec2(3)] = sph2cart(lon2*pi/180,lat2*pi/180,1);
[Uvec3(1),Uvec3(2),Uvec3(3)] = sph2cart(lon3*pi/180,lat3*pi/180,1);
[Uvec4(1),Uvec4(2),Uvec4(3)] = sph2cart(lon4*pi/180,lat4*pi/180,1);
%% Cross product
%Need to calculate the the "plane normals" for each of the two great
%circles
N1 = cross(Uvec1,Uvec3);
N2 = cross(Uvec2,Uvec4);
%% Plane of intersecting line
%With two plane normals, the cross prodcut defines their intersecting line
L = cross(N1,N2);
L = L./norm(L);
L2 = -L;
L2 = L2./norm(L2);
%% Convert normalized intersection line to geodetic coordinates
[lonRad,latRad,~]=cart2sph(L(1),L(2),L(3));
lonDeg = lonRad*180/pi;
latDeg = latRad*180/pi;
[lonRad,latRad,~]=cart2sph(L2(1),L2(2),L2(3));
lonDeg2 = lonRad*180/pi;
latDeg2 = latRad*180/pi;
I have a problem I've been trying to solve and I cannot come up with the
answer. I have written a function in Matlab which, given two lat/lon
points and two bearings, will return the two great circle points of
intersection.
However, what I really need is the first great circle point of
intersection along the two initial headings. I.e. if two airplanes begin
at lat/lon points 1 and 2, with initial bearings of bearing1 and bearing2,
which of the two great circle intersection points is the first one they
encounter? There are many solutions (using haversine) which will give me
the closer of the two points, but I don't actually care about which is
closer, I care about which I will encounter first given specific start
points and headings. There are many cases where the closer of the two
intersections is actually the second intersection encountered.
Now, I realize I could do this with lots of conditional statements for
handling the different cases, but I figure there's got to be a way to
handle it with regard to the order I take all my cross products (function
code given below), but I simply can't come up with the right solution! I
should also mention that this function is going to be used in a large
computationally intensive model, and so I'm thinking the solution to this
problem needs to be rather elegant/speedy. Can anyone help me with this
problem?
The following is not my function code (I can't list that here), but it is
the pseudo code that my function was based off of:
%Given inputs of lat1,lon1,Bearing1,lat2,lon2,Bearing2:
%Calculate arbitrary secondary point along same initial bearing from first
%point
dAngle = 45;
lat3 = asind( sind(lat1)*cosd(dAngle) +
cosd(lat1)*sind(dAngle)*cosd(Bearing1));
lon3 = lon1 + atan2( sind(Bearing1)*sind(dAngle)*cosd(lat1),
cosd(dAngle)-sind(lat1)*sind(lat3) )*180/pi;
lat4 = asind( sind(lat2)*cosd(dAngle) +
cosd(lat2)*sind(dAngle)*cosd(Bearing2));
lon4 = lon2 + atan2( sind(Bearing2)*sind(dAngle)*cosd(lat2),
cosd(dAngle)-sind(lat2)*sind(lat4) )*180/pi;
%% Calculate unit vectors
% We now have two points defining each of the two great circles. We need
% to calculate unit vectors from the center of the Earth to each of these
% points
[Uvec1(1),Uvec1(2),Uvec1(3)] = sph2cart(lon1*pi/180,lat1*pi/180,1);
[Uvec2(1),Uvec2(2),Uvec2(3)] = sph2cart(lon2*pi/180,lat2*pi/180,1);
[Uvec3(1),Uvec3(2),Uvec3(3)] = sph2cart(lon3*pi/180,lat3*pi/180,1);
[Uvec4(1),Uvec4(2),Uvec4(3)] = sph2cart(lon4*pi/180,lat4*pi/180,1);
%% Cross product
%Need to calculate the the "plane normals" for each of the two great
%circles
N1 = cross(Uvec1,Uvec3);
N2 = cross(Uvec2,Uvec4);
%% Plane of intersecting line
%With two plane normals, the cross prodcut defines their intersecting line
L = cross(N1,N2);
L = L./norm(L);
L2 = -L;
L2 = L2./norm(L2);
%% Convert normalized intersection line to geodetic coordinates
[lonRad,latRad,~]=cart2sph(L(1),L(2),L(3));
lonDeg = lonRad*180/pi;
latDeg = latRad*180/pi;
[lonRad,latRad,~]=cart2sph(L2(1),L2(2),L2(3));
lonDeg2 = lonRad*180/pi;
latDeg2 = latRad*180/pi;
what does ">>>" mean in java?
what does ">>>" mean in java?
I found this code to find duplicates in SO post here. but I dont
understand what this line means int mid = (low + high) >>> 1;
private static int findDuplicate(int[] array) {
int low = 0;
int high = array.length - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
System.out.println(mid);
int midVal = array[mid];
if (midVal == mid)
low = mid + 1;
else
high = mid - 1;
}
return high;
}
I found this code to find duplicates in SO post here. but I dont
understand what this line means int mid = (low + high) >>> 1;
private static int findDuplicate(int[] array) {
int low = 0;
int high = array.length - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
System.out.println(mid);
int midVal = array[mid];
if (midVal == mid)
low = mid + 1;
else
high = mid - 1;
}
return high;
}
What exactly SignalR is ??
What exactly SignalR is ??
I want to SignalR. Can someone please tell me the future of this technology?
What exactly Signal R is? Please do not give me bookish defination If
someone can give me pratical example I am very thankful.
Thanks in advance.
Regards, Sahil
I want to SignalR. Can someone please tell me the future of this technology?
What exactly Signal R is? Please do not give me bookish defination If
someone can give me pratical example I am very thankful.
Thanks in advance.
Regards, Sahil
Call a php function with a name that's partially a variable
Call a php function with a name that's partially a variable
I'd like to ask you a simple question,
I have a class with functions called:
somethingModule()
someotherthingModule()
otherthingsModule()
How can I call these functions based on a pattern? I mean something like:
$call = $class->{$modulename}Module($params);
I'd like to ask you a simple question,
I have a class with functions called:
somethingModule()
someotherthingModule()
otherthingsModule()
How can I call these functions based on a pattern? I mean something like:
$call = $class->{$modulename}Module($params);
Insert html if div contains number over 'x'
Insert html if div contains number over 'x'
I'm trying to create a free delivery banner if the price of a product is
over £50.
My attempt:
$(function() {
if( $('.num').filter(function(index){
return parseInt(this.innerHTML) > 50.00;})) {
$(document.createElement('div')).attr('id',
'freeDelivery').appendTo('.imgoffer');
$('#freeDelivery').append('<img id="freeDeliveryImage" alt="Free delivery
on this item" src="https://location_of_image.png" width="70"
height="70">');
}
});
My code inserts the free delivery element even if the amount isn't over
'x'. Any suggestions?
I'm trying to create a free delivery banner if the price of a product is
over £50.
My attempt:
$(function() {
if( $('.num').filter(function(index){
return parseInt(this.innerHTML) > 50.00;})) {
$(document.createElement('div')).attr('id',
'freeDelivery').appendTo('.imgoffer');
$('#freeDelivery').append('<img id="freeDeliveryImage" alt="Free delivery
on this item" src="https://location_of_image.png" width="70"
height="70">');
}
});
My code inserts the free delivery element even if the amount isn't over
'x'. Any suggestions?
Thursday, 26 September 2013
How to know the degree of rotation of the fabric js object?
How to know the degree of rotation of the fabric js object?
If an Object is added on the canvas and is rotated to right or left .How
to know the degree of rotation of the fabric js object ?
If an Object is added on the canvas and is rotated to right or left .How
to know the degree of rotation of the fabric js object ?
Wednesday, 25 September 2013
Old data gets wiped from POST when I use GET
Old data gets wiped from POST when I use GET
So I am having an issue. I used POST to send data to a new page. I use get
to send data to a function but it seems the POST data get wiped. Here some
code to help explain.
POST CODE to send to form vieworder (works perfect!)
<form method="post" action="vieworder.php">
<input type="hidden" name ="user_id" value="<?php echo
$_SESSION['user_id']; ?>">
<input type="hidden" name ="id" value="<?php echo $data1[$x]['id']; ?>">
<input type="submit" name="submit" value="View"> </td>
</form>
So on the vieworder page I want used to be able to update the data using
this form. This form works as well except i need that value "id" from the
orginal post. It works and the "id"has the data until I use this form.
<form name="approveform" method="get" action="">
Index Number*: <input type="text" name="IndexNum">
<input type="submit" value="Approve" action="">
</form>
I would also prefer to use the POST method but using GET was my first
solution to no deleting the data from POST.
Anyways I then just send the data to a function to update two fields.
Any way to get correct the code?
So I am having an issue. I used POST to send data to a new page. I use get
to send data to a function but it seems the POST data get wiped. Here some
code to help explain.
POST CODE to send to form vieworder (works perfect!)
<form method="post" action="vieworder.php">
<input type="hidden" name ="user_id" value="<?php echo
$_SESSION['user_id']; ?>">
<input type="hidden" name ="id" value="<?php echo $data1[$x]['id']; ?>">
<input type="submit" name="submit" value="View"> </td>
</form>
So on the vieworder page I want used to be able to update the data using
this form. This form works as well except i need that value "id" from the
orginal post. It works and the "id"has the data until I use this form.
<form name="approveform" method="get" action="">
Index Number*: <input type="text" name="IndexNum">
<input type="submit" value="Approve" action="">
</form>
I would also prefer to use the POST method but using GET was my first
solution to no deleting the data from POST.
Anyways I then just send the data to a function to update two fields.
Any way to get correct the code?
Thursday, 19 September 2013
Pressing a button within another application in the loop
Pressing a button within another application in the loop
I was thinking some one will be able to help me out to do a simple thing,
but for some reason I can not get my head around it. I am trying to press
a button within another application and do it in the loop, loop should
break when the pressed button is gone, I had successfully accomplished
task of pressing button, but I can not do a loop, as soon as I press
button to start loop my application hangs. Thank you in advance.
private void btnCloseCalc_Click(object sender, System.EventArgs e)
{
int hwnd=0;
IntPtr hwndChild = IntPtr.Zero;
//Get a handle for the Application main window
hwnd = FindWindow(null, "Desired MessageBox");
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "OK");
//send system message
if (hwnd != 0)
{
SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);
}
else
{
MessageBox.Show("Button Could Not Be Found!", "Warning",
MessageBoxButtons.OK);
}
}
I was thinking some one will be able to help me out to do a simple thing,
but for some reason I can not get my head around it. I am trying to press
a button within another application and do it in the loop, loop should
break when the pressed button is gone, I had successfully accomplished
task of pressing button, but I can not do a loop, as soon as I press
button to start loop my application hangs. Thank you in advance.
private void btnCloseCalc_Click(object sender, System.EventArgs e)
{
int hwnd=0;
IntPtr hwndChild = IntPtr.Zero;
//Get a handle for the Application main window
hwnd = FindWindow(null, "Desired MessageBox");
hwndChild = FindWindowEx((IntPtr)hwnd, IntPtr.Zero, "Button", "OK");
//send system message
if (hwnd != 0)
{
SendMessage((int)hwndChild, BN_CLICKED, 0, IntPtr.Zero);
}
else
{
MessageBox.Show("Button Could Not Be Found!", "Warning",
MessageBoxButtons.OK);
}
}
Should I use Cucumber for an AngularJS single page application?
Should I use Cucumber for an AngularJS single page application?
I'm fairly new to both Cucumber and Angular. I have a rails application
that is a single page application. Should I bother with Cucumber or should
I just use AngularJS's e2e testing?
Any insight and past experience is appreciated!
I'm fairly new to both Cucumber and Angular. I have a rails application
that is a single page application. Should I bother with Cucumber or should
I just use AngularJS's e2e testing?
Any insight and past experience is appreciated!
Is this a javascript method or property?
Is this a javascript method or property?
I'm having the hardest time getting my terminology right. In the following
code:
Notes.NotesController = Ember.ArrayController.extend({
newNoteName: null,
actions: {
createNewNote: function() {
var content = this.get('content');
var newNoteName = this.get('newNoteName');
var unique = newNoteName != null && newNoteName.length > 1;
content.forEach(function(note) {
if (newNoteName === note.get('name')) {
unique = false; return;
}
});
if (unique) {
var newNote = this.store.createRecord('note');
newNote.set('id', newNoteName);
newNote.set('name', newNoteName);
newNote.save();
this.set('newNoteName', null);
} else {
alert('Note must have a unique name of at least 2 characters!');
}
}
}
});
What is 'newNoteName:', 'actions:', and 'createNewNote:'?
Are they methods or properties or hooks? What are the differences? And
does 'createNewNote' being nested inside of 'actions:' make 'actions'
something altogether different?
What is the difference between ember 'hooks' and methods/properties that
you create and name yourself and how they're used?
Thank you.'
I'm having the hardest time getting my terminology right. In the following
code:
Notes.NotesController = Ember.ArrayController.extend({
newNoteName: null,
actions: {
createNewNote: function() {
var content = this.get('content');
var newNoteName = this.get('newNoteName');
var unique = newNoteName != null && newNoteName.length > 1;
content.forEach(function(note) {
if (newNoteName === note.get('name')) {
unique = false; return;
}
});
if (unique) {
var newNote = this.store.createRecord('note');
newNote.set('id', newNoteName);
newNote.set('name', newNoteName);
newNote.save();
this.set('newNoteName', null);
} else {
alert('Note must have a unique name of at least 2 characters!');
}
}
}
});
What is 'newNoteName:', 'actions:', and 'createNewNote:'?
Are they methods or properties or hooks? What are the differences? And
does 'createNewNote' being nested inside of 'actions:' make 'actions'
something altogether different?
What is the difference between ember 'hooks' and methods/properties that
you create and name yourself and how they're used?
Thank you.'
Debugging into Source Code in Eclipse
Debugging into Source Code in Eclipse
In Eclipse, I have created a 'DemoApp' in Android. Also, I have Android
platform source code in Eclipse 'PlatformCode'.
While debugging DemoApp, I want it to use 'PlatformCode' which i have
built using 'make'. I mentioned the name of my source code project in
'Project References' of app project. But, it is not working. How would I
achieve it? 'PlatformCode' is a Java project and it is not having the
conventional Java Project structure in Eclipse like - src folder and other
references, maybe that's why it is showing red exclamation sign on it.
In Eclipse, I have created a 'DemoApp' in Android. Also, I have Android
platform source code in Eclipse 'PlatformCode'.
While debugging DemoApp, I want it to use 'PlatformCode' which i have
built using 'make'. I mentioned the name of my source code project in
'Project References' of app project. But, it is not working. How would I
achieve it? 'PlatformCode' is a Java project and it is not having the
conventional Java Project structure in Eclipse like - src folder and other
references, maybe that's why it is showing red exclamation sign on it.
Android - App Update Manifest Version Code and Name
Android - App Update Manifest Version Code and Name
my Android Manifest File :
my existing Version Code = 1
also
my existing Version Number = 1
I want to update my App and I know that have to change my Version Number
e.g. to 1.1 but what does the Version Code mean?
Should it stay at 1?
Or do i have to change it also? Maybe be to 2? oder anything else?
Thx for ur help!
my Android Manifest File :
my existing Version Code = 1
also
my existing Version Number = 1
I want to update my App and I know that have to change my Version Number
e.g. to 1.1 but what does the Version Code mean?
Should it stay at 1?
Or do i have to change it also? Maybe be to 2? oder anything else?
Thx for ur help!
HTML to PDF using PHP library
HTML to PDF using PHP library
I have a welcome letter which has create from ck editor and saved to
db(mysql). I am Printing the letter in a pdf, I have use tcpdf. DOMpdf,
mpdf but no where I got perfect pdf as html. The dom pdf has made exactly
as in the editor but can not add custom header and footer, can any one say
which library give the the perfect pdf, which will support each css,
pagebrake, custom header and footer
I have a welcome letter which has create from ck editor and saved to
db(mysql). I am Printing the letter in a pdf, I have use tcpdf. DOMpdf,
mpdf but no where I got perfect pdf as html. The dom pdf has made exactly
as in the editor but can not add custom header and footer, can any one say
which library give the the perfect pdf, which will support each css,
pagebrake, custom header and footer
Hyperlink tag inside paragraph and text-align:center
Hyperlink tag inside paragraph and text-align:center
<div style="width:400px">
<p style="text-align:center">
<a>
<img src"..." />
</a>
Some text..
</p>
</div>
So the goal here is to center the image inside the div. Text-align:center
works on the images that are not inside the hyperlink tag, but once they
are, it doesn't affect them, just the text.
I don't want to go with display:block and margin-left/right auto, simply
because we'll need to align some pictures to the left and right using
float.
Any ideas why the hyperlink prevents text-align to work?
<div style="width:400px">
<p style="text-align:center">
<a>
<img src"..." />
</a>
Some text..
</p>
</div>
So the goal here is to center the image inside the div. Text-align:center
works on the images that are not inside the hyperlink tag, but once they
are, it doesn't affect them, just the text.
I don't want to go with display:block and margin-left/right auto, simply
because we'll need to align some pictures to the left and right using
float.
Any ideas why the hyperlink prevents text-align to work?
Wednesday, 18 September 2013
Which platform does not allow multiple FileWriters to open on a file
Which platform does not allow multiple FileWriters to open on a file
JAVA docs for FileWriter say
Whether or not a file is available or may be created depends upon the *
underlying platform. *Some platforms, in particular, allow a file to be *
opened for writing by only one* FileWriter (or other file-writing *
object) at a time. In such situations the constructors in this class *
will fail if the file involved is already open."
I need to know what are the platforms which does not allow multiple
FIleWriter on a file.
Thanks
JAVA docs for FileWriter say
Whether or not a file is available or may be created depends upon the *
underlying platform. *Some platforms, in particular, allow a file to be *
opened for writing by only one* FileWriter (or other file-writing *
object) at a time. In such situations the constructors in this class *
will fail if the file involved is already open."
I need to know what are the platforms which does not allow multiple
FIleWriter on a file.
Thanks
How to check in python if I'm in certain range of times of the day?
How to check in python if I'm in certain range of times of the day?
I want to check in python if the current time is between two endpoints
(say, 8:30 a.m. and 3:00 p.m.), irrespective of the actual date. As in, I
don't care what the full date is; just the hour. When I created datetime
objects using strptime to specify a time, it threw in a dummy date (I
think the year 1900?) which is not what I want. What's the easiest and
most pythonic way to accomplish this?
Extending a bit further, what I'd really like is something that will tell
me if it's between that range of hours, and that it's a weekday. Of course
I can just use 0 <= weekday() <= 4 to hack this, but there might be a
better way.
I want to check in python if the current time is between two endpoints
(say, 8:30 a.m. and 3:00 p.m.), irrespective of the actual date. As in, I
don't care what the full date is; just the hour. When I created datetime
objects using strptime to specify a time, it threw in a dummy date (I
think the year 1900?) which is not what I want. What's the easiest and
most pythonic way to accomplish this?
Extending a bit further, what I'd really like is something that will tell
me if it's between that range of hours, and that it's a weekday. Of course
I can just use 0 <= weekday() <= 4 to hack this, but there might be a
better way.
How can I catch a EOF error in my calculator program
How can I catch a EOF error in my calculator program
I am trying to create a calculator. Why can't I catch the EOF error? My
program crashes when I input more than one special characters. e.g. 2++
How is this problem normally solved?
Thanks in advance!
def calcfieldcheck(input):
return re.match("^[0-9\.\-\/\*\+\%]+$",input)
#uitzoeken hoe regex nesten
def calculate(input):
print "Wat moet ik berekenen?"
counter=0
while not calcfieldcheck(input):
if counter > 0:
print "Je kan alleen getallen en expressies berekenen!"
input=raw_input("> ")
else:
print
input=raw_input("> ")
counter=counter+1
print
print "je hebt het volgende ingevoerd: ",input
try:
print "het resultaat is:", eval(input)
except EOFError:
print "EOFError, je calculatie klopt niet."
input=raw_input("> ")
print
print
counter=0
I am trying to create a calculator. Why can't I catch the EOF error? My
program crashes when I input more than one special characters. e.g. 2++
How is this problem normally solved?
Thanks in advance!
def calcfieldcheck(input):
return re.match("^[0-9\.\-\/\*\+\%]+$",input)
#uitzoeken hoe regex nesten
def calculate(input):
print "Wat moet ik berekenen?"
counter=0
while not calcfieldcheck(input):
if counter > 0:
print "Je kan alleen getallen en expressies berekenen!"
input=raw_input("> ")
else:
input=raw_input("> ")
counter=counter+1
print "je hebt het volgende ingevoerd: ",input
try:
print "het resultaat is:", eval(input)
except EOFError:
print "EOFError, je calculatie klopt niet."
input=raw_input("> ")
counter=0
Sharing OpenGL objects between contexts on Linux
Sharing OpenGL objects between contexts on Linux
To share OpenGL objects between different contexts (presumably running in
different threads) we use wglShareLists() on Windows.How is it done for
Linux?Has glx an API to do this kind of things?Any pointers to the related
docs will be welcomed.
To share OpenGL objects between different contexts (presumably running in
different threads) we use wglShareLists() on Windows.How is it done for
Linux?Has glx an API to do this kind of things?Any pointers to the related
docs will be welcomed.
PHP Class for creating RAR Archives
PHP Class for creating RAR Archives
I need to create password protected zip/rar archives in my applicaiton.
ZIP files are my preference as they're more popular, but there wasn't any
method or option for encryption. And it's the same deal with RAR archives.
I was wondering if there is any single function/class for creating
password protected RAR/ZIP archives via php?
I need to create password protected zip/rar archives in my applicaiton.
ZIP files are my preference as they're more popular, but there wasn't any
method or option for encryption. And it's the same deal with RAR archives.
I was wondering if there is any single function/class for creating
password protected RAR/ZIP archives via php?
Python Threading with win32ui DDE module
Python Threading with win32ui DDE module
Running Python2.7 32 bit Windows. It would appear that the dde module (or
the way I am using it?) does not play nicely with threads.
Here's stripped down code to demonstrate:
This Works:
(I.E. Doesn't fail epically.)
import win32ui
import dde
import threading
class Conversation(threading.Thread):
def __init__(self, server, first, second, tag)
self.tag = tag #string
self.first = first #string
self.second = second #string
self.server = server #dde server object
self.conversation = dde.CreateConversation(server)
#The focus of the problem. Here it works.
self.conversation.ConnectTo(self.first, self.second)
def run(self):
print ""
def main():
machine = "Irrelevant_MachineName"
tag = "Irrelevant_Tagname"
server = dde.CreateServer()
server.Create("Irrelevant_ServerName")
t = Conversation(server, "Irrelevant_Name", machine, tag)
t.start()
main()
This doesn't:
class Conversation(threading.Thread):
def __init__(self, server, first, second, tag):
self.tag = tag #string
self.first = first #string
self.second = second #string
self.server = server #dde server object
def run(self):
self.conversation = dde.CreateConversation(server)
#Focus of problem.
#Inside here it does not work.
self.conversation.ConnectTo(self.name1, self.name2)
def main():
machine = "Irrelevant_MachineName"
tag = "Irrelevant_Tagname"
server = dde.CreateServer()
server.Create("Irrelevant_ServerName")
t = Conversation(server, "Irrelevant_Name", machine, tag)
t.start()
main()
When it fails, I get this error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "c:\Python27\lib\threading.py", line 808, in __bootstrap_inner
self.run()
File "DDE.py", line 28 in run
self.conversation.ConnectTo(self.first, self.second)
error: ConnectTo failed
Which corresponds, as one might expect, to Why would this be? This is
going to be my first multithreaded program, so I'm not sure if I'm doing
something stupid here.
But to me it seems perfectly reasonable that I should be able to call the
dde.server.conversation object's ConnectTo method from within the
threading module's "run()" method.
I'd looked into multiprocessing, but I don't think that's as applicable to
my situation.
So, any ideas? I would greatly appreciate the help!!!
Running Python2.7 32 bit Windows. It would appear that the dde module (or
the way I am using it?) does not play nicely with threads.
Here's stripped down code to demonstrate:
This Works:
(I.E. Doesn't fail epically.)
import win32ui
import dde
import threading
class Conversation(threading.Thread):
def __init__(self, server, first, second, tag)
self.tag = tag #string
self.first = first #string
self.second = second #string
self.server = server #dde server object
self.conversation = dde.CreateConversation(server)
#The focus of the problem. Here it works.
self.conversation.ConnectTo(self.first, self.second)
def run(self):
print ""
def main():
machine = "Irrelevant_MachineName"
tag = "Irrelevant_Tagname"
server = dde.CreateServer()
server.Create("Irrelevant_ServerName")
t = Conversation(server, "Irrelevant_Name", machine, tag)
t.start()
main()
This doesn't:
class Conversation(threading.Thread):
def __init__(self, server, first, second, tag):
self.tag = tag #string
self.first = first #string
self.second = second #string
self.server = server #dde server object
def run(self):
self.conversation = dde.CreateConversation(server)
#Focus of problem.
#Inside here it does not work.
self.conversation.ConnectTo(self.name1, self.name2)
def main():
machine = "Irrelevant_MachineName"
tag = "Irrelevant_Tagname"
server = dde.CreateServer()
server.Create("Irrelevant_ServerName")
t = Conversation(server, "Irrelevant_Name", machine, tag)
t.start()
main()
When it fails, I get this error:
Exception in thread Thread-1:
Traceback (most recent call last):
File "c:\Python27\lib\threading.py", line 808, in __bootstrap_inner
self.run()
File "DDE.py", line 28 in run
self.conversation.ConnectTo(self.first, self.second)
error: ConnectTo failed
Which corresponds, as one might expect, to Why would this be? This is
going to be my first multithreaded program, so I'm not sure if I'm doing
something stupid here.
But to me it seems perfectly reasonable that I should be able to call the
dde.server.conversation object's ConnectTo method from within the
threading module's "run()" method.
I'd looked into multiprocessing, but I don't think that's as applicable to
my situation.
So, any ideas? I would greatly appreciate the help!!!
Polymorphic call through non-virtual method
Polymorphic call through non-virtual method
I have a little problem with polymorphism. My simple code:
Animal.h
class Animal {
public:
Animal();
Animal(const Animal& orig);
virtual ~Animal();
virtual void get();
};
Animal.cpp
#include "Animal.h"
#include <iostream>
using namespace std;
Animal::Animal() {
cout << "Animal is born" << endl;
}
void Animal::get() {
cout << "get() from an Animal!" << endl;
}
Bird.h
class Bird : public Animal {
public:
Bird();
Bird(const Bird& orig);
virtual ~Bird();
void get();
};
Bird.cpp
#include "Bird.h"
#include <iostream>
using namespace std;
Bird::Bird() {
cout << "Bird is born" << endl;
}
void Bird::get() {
cout << "get() from a Bird!" << endl;
}
Chicken.h
#include "Bird.h"
class Chicken : public Bird {
public:
Chicken();
Chicken(const Chicken& orig);
virtual ~Chicken();
void get();
};
Chicken.cpp
#include "Chicken.h"
#include <iostream>
using namespace std;
Chicken::Chicken() {
cout << "Chicken is born" << endl;
}
void Chicken::get() {
cout << "get() from a Chicken!" << endl;
}
There is also a factory method returning an Animal* pointer to the
concrete implementation based on input:
Factory.h
#include "Animal.h"
#include "Bird.h"
class Factory {
public:
Factory();
Factory(const Factory& orig);
virtual ~Factory();
Animal* generateAnimal();
Bird* generateBird();
};
Factory.cpp
#include "Factory.h"
#include "Animal.h"
#include "Bird.h"
#include "Chicken.h"
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
Animal* Factory::generateAnimal() {
string choice;
cout << "What do you want? 1-Animal, 2-Bird, 3-Chicken" << endl;
cin >> choice;
Animal* animal;
if (choice.at(0) == '1') {
cout << "You chose Animal" << endl;
animal = new Animal();
return animal;
} else if (choice.at(0) == '2') {
cout << "You chose Bird" << endl;
animal = new Bird();
return animal;
} else if (choice.at(0) == '3') {
cout << "You chose Chicken" << endl;
animal = new Chicken();
return animal;
} else {
cout << "Wrong input" << endl;
exit(1);
}
}
Bird* Factory::generateBird() {
string choice;
cout << "What do you want? 1-Animal, 2-Bird, 3-Chicken" << endl;
cin >> choice;
Bird* bird;
if (choice.at(0) == '2') {
cout << "You chose Bird" << endl;
bird = new Bird();
return bird;
} else if (choice.at(0) == '3') {
cout << "You chose Chicken" << endl;
bird = new Chicken();
return bird;
} else {
cout << "Wrong input" << endl;
exit(1);
}
}
I omitted ctors & dtors.
main.cpp
#include <cstdlib>
#include <iostream>
#include "Factory.h"
#include "Animal.h"
#include "Bird.h"
#include "Chicken.h"
using namespace std;
int main(int argc, char** argv) {
Factory factory;
Animal* animal = factory.generateAnimal();
animal->get();
return 0;
}
The concrete implementation of an Animal class is resolved during runtime.
It's obvious, that removing the virtual keyword from Animal class results
in calling Animal implementation of get() method, whether animal* points
to Bird or Chicken.
What do you want? 1-Animal, 2-Bird, 3-Chicken
3
You chose Chicken
Animal is born
Bird is born
Chicken is born
get() from an Animal!
It's also obvious, that calling the virtual get() method results in
polymorphic call to the concrete subclass. What concerns me is this
situation: Instead of
Animal* animal = factory.generateAnimal();
animal->get();
we have
Bird* bird = factory.generateBird();
bird->get();
We have a pointer to Bird class, in which the get() method is NOT virtual.
The output is:
What do you want? 1-Animal, 2-Bird, 3-Chicken
3
You chose Chicken
Animal is born
Bird is born
Chicken is born
get() from a Chicken!
How does it happen, that call to non-virtual function results in virtual
call to the subclass? Is "virtualism" inherited? If it is, is it somehow
possible to perform a non-virtual call to the pointer class, instead of
implementation class?
I have a little problem with polymorphism. My simple code:
Animal.h
class Animal {
public:
Animal();
Animal(const Animal& orig);
virtual ~Animal();
virtual void get();
};
Animal.cpp
#include "Animal.h"
#include <iostream>
using namespace std;
Animal::Animal() {
cout << "Animal is born" << endl;
}
void Animal::get() {
cout << "get() from an Animal!" << endl;
}
Bird.h
class Bird : public Animal {
public:
Bird();
Bird(const Bird& orig);
virtual ~Bird();
void get();
};
Bird.cpp
#include "Bird.h"
#include <iostream>
using namespace std;
Bird::Bird() {
cout << "Bird is born" << endl;
}
void Bird::get() {
cout << "get() from a Bird!" << endl;
}
Chicken.h
#include "Bird.h"
class Chicken : public Bird {
public:
Chicken();
Chicken(const Chicken& orig);
virtual ~Chicken();
void get();
};
Chicken.cpp
#include "Chicken.h"
#include <iostream>
using namespace std;
Chicken::Chicken() {
cout << "Chicken is born" << endl;
}
void Chicken::get() {
cout << "get() from a Chicken!" << endl;
}
There is also a factory method returning an Animal* pointer to the
concrete implementation based on input:
Factory.h
#include "Animal.h"
#include "Bird.h"
class Factory {
public:
Factory();
Factory(const Factory& orig);
virtual ~Factory();
Animal* generateAnimal();
Bird* generateBird();
};
Factory.cpp
#include "Factory.h"
#include "Animal.h"
#include "Bird.h"
#include "Chicken.h"
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
Animal* Factory::generateAnimal() {
string choice;
cout << "What do you want? 1-Animal, 2-Bird, 3-Chicken" << endl;
cin >> choice;
Animal* animal;
if (choice.at(0) == '1') {
cout << "You chose Animal" << endl;
animal = new Animal();
return animal;
} else if (choice.at(0) == '2') {
cout << "You chose Bird" << endl;
animal = new Bird();
return animal;
} else if (choice.at(0) == '3') {
cout << "You chose Chicken" << endl;
animal = new Chicken();
return animal;
} else {
cout << "Wrong input" << endl;
exit(1);
}
}
Bird* Factory::generateBird() {
string choice;
cout << "What do you want? 1-Animal, 2-Bird, 3-Chicken" << endl;
cin >> choice;
Bird* bird;
if (choice.at(0) == '2') {
cout << "You chose Bird" << endl;
bird = new Bird();
return bird;
} else if (choice.at(0) == '3') {
cout << "You chose Chicken" << endl;
bird = new Chicken();
return bird;
} else {
cout << "Wrong input" << endl;
exit(1);
}
}
I omitted ctors & dtors.
main.cpp
#include <cstdlib>
#include <iostream>
#include "Factory.h"
#include "Animal.h"
#include "Bird.h"
#include "Chicken.h"
using namespace std;
int main(int argc, char** argv) {
Factory factory;
Animal* animal = factory.generateAnimal();
animal->get();
return 0;
}
The concrete implementation of an Animal class is resolved during runtime.
It's obvious, that removing the virtual keyword from Animal class results
in calling Animal implementation of get() method, whether animal* points
to Bird or Chicken.
What do you want? 1-Animal, 2-Bird, 3-Chicken
3
You chose Chicken
Animal is born
Bird is born
Chicken is born
get() from an Animal!
It's also obvious, that calling the virtual get() method results in
polymorphic call to the concrete subclass. What concerns me is this
situation: Instead of
Animal* animal = factory.generateAnimal();
animal->get();
we have
Bird* bird = factory.generateBird();
bird->get();
We have a pointer to Bird class, in which the get() method is NOT virtual.
The output is:
What do you want? 1-Animal, 2-Bird, 3-Chicken
3
You chose Chicken
Animal is born
Bird is born
Chicken is born
get() from a Chicken!
How does it happen, that call to non-virtual function results in virtual
call to the subclass? Is "virtualism" inherited? If it is, is it somehow
possible to perform a non-virtual call to the pointer class, instead of
implementation class?
Hit OutOfMemoryError when load large blob column from mysql
Hit OutOfMemoryError when load large blob column from mysql
One of my table contains one blob column, and sometimes the size of the
column value would be more than 500M, which is larger than the defalut max
heap size, e.g. -XMX is setting as 512M in my Application Server. In my
code, I have set the fetch size of PreparedSTatement to Integer.MIN_VALUE
to utilize the Mysql Stream support. Also, I add "useServerPrepStmts=true"
into the database url. With these settings, I can insert record with large
column (>500M) successfully, but when I trying to get the record, I always
hit OutOfMemoryError when calling ResultSet.next(). Note: execute query
can pass, checked with the heap size change, execute seems don't load any
real record data. ResultRet rs = Prestatement.execute(...). rs.next();
The mysql driver I'm using is 5.1.17.
Below is the exception stack. It looks like the driver tries to load the
whole column value into memory, which cause OutOfMemoryError here.
13-09-18 13:18:00,169 ERROR [STDERR] Caused by:
java.lang.OutOfMemoryError: Java heap space
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.Buffer.ensureCapacity(Buffer.java:156)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.Buffer.writeBytesNoNull(Buffer.java:514)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.readRemainingMultiPackets(MysqlIO.java:3219)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3077)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2979)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3520)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:935)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.nextRow(MysqlIO.java:1433)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.RowDataDynamic.nextRecord(RowDataDynamic.java:416)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.RowDataDynamic.next(RowDataDynamic.java:395)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7165)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.commons.dbcp.DelegatingResultSet.next(DelegatingResultSet.java:169)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.commons.dbcp.DelegatingResultSet.next(DelegatingResultSet.java:169)
2013-09-18 13:18:00,169 ERROR [STDERR] at
sun.reflect.GeneratedMethodAccessor86.invoke(Unknown Source)
2013-09-18 13:18:00,169 ERROR [STDERR] at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
2013-09-18 13:18:00,169 ERROR [STDERR] at
java.lang.reflect.Method.invoke(Method.java:597)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.jackrabbit.core.util.db.ResultSetWrapper.invoke(ResultSetWrapper.java:66)
2013-09-18 13:18:00,169 ERROR [STDERR] at $Proxy68.next(Unknown Source)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.jackrabbit.core.data.db.DbDataStore.openStream(DbDataStore.java:542)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.jackrabbit.core.data.db.DbInputStream.openStream(DbInputStream.java:68)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.jackrabbit.core.data.db.DbInputStream.read(DbInputStream.java:110)
One of my table contains one blob column, and sometimes the size of the
column value would be more than 500M, which is larger than the defalut max
heap size, e.g. -XMX is setting as 512M in my Application Server. In my
code, I have set the fetch size of PreparedSTatement to Integer.MIN_VALUE
to utilize the Mysql Stream support. Also, I add "useServerPrepStmts=true"
into the database url. With these settings, I can insert record with large
column (>500M) successfully, but when I trying to get the record, I always
hit OutOfMemoryError when calling ResultSet.next(). Note: execute query
can pass, checked with the heap size change, execute seems don't load any
real record data. ResultRet rs = Prestatement.execute(...). rs.next();
The mysql driver I'm using is 5.1.17.
Below is the exception stack. It looks like the driver tries to load the
whole column value into memory, which cause OutOfMemoryError here.
13-09-18 13:18:00,169 ERROR [STDERR] Caused by:
java.lang.OutOfMemoryError: Java heap space
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.Buffer.ensureCapacity(Buffer.java:156)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.Buffer.writeBytesNoNull(Buffer.java:514)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.readRemainingMultiPackets(MysqlIO.java:3219)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3077)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2979)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3520)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:935)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.MysqlIO.nextRow(MysqlIO.java:1433)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.RowDataDynamic.nextRecord(RowDataDynamic.java:416)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.RowDataDynamic.next(RowDataDynamic.java:395)
2013-09-18 13:18:00,169 ERROR [STDERR] at
com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7165)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.commons.dbcp.DelegatingResultSet.next(DelegatingResultSet.java:169)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.commons.dbcp.DelegatingResultSet.next(DelegatingResultSet.java:169)
2013-09-18 13:18:00,169 ERROR [STDERR] at
sun.reflect.GeneratedMethodAccessor86.invoke(Unknown Source)
2013-09-18 13:18:00,169 ERROR [STDERR] at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
2013-09-18 13:18:00,169 ERROR [STDERR] at
java.lang.reflect.Method.invoke(Method.java:597)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.jackrabbit.core.util.db.ResultSetWrapper.invoke(ResultSetWrapper.java:66)
2013-09-18 13:18:00,169 ERROR [STDERR] at $Proxy68.next(Unknown Source)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.jackrabbit.core.data.db.DbDataStore.openStream(DbDataStore.java:542)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.jackrabbit.core.data.db.DbInputStream.openStream(DbInputStream.java:68)
2013-09-18 13:18:00,169 ERROR [STDERR] at
org.apache.jackrabbit.core.data.db.DbInputStream.read(DbInputStream.java:110)
Tuesday, 17 September 2013
Connect to an action in a namespaced controller that isn't a collection or member
Connect to an action in a namespaced controller that isn't a collection or
member
I want to have a url like this:
/admin/providers/connect
that a 3rd party can post to. It isn't a restful resource. Its just a url.
I'd like it to map to the connect method in my providers controller in the
admin namespace.
How can i do that?
here is what i have:
namespace :admin do
get '/admin/providers/connect', to: 'providers#connect'
end
which is just redirecting to the dashboard.
member
I want to have a url like this:
/admin/providers/connect
that a 3rd party can post to. It isn't a restful resource. Its just a url.
I'd like it to map to the connect method in my providers controller in the
admin namespace.
How can i do that?
here is what i have:
namespace :admin do
get '/admin/providers/connect', to: 'providers#connect'
end
which is just redirecting to the dashboard.
Why isn't my function appending a key-value to the dictionary?
Why isn't my function appending a key-value to the dictionary?
So I defined this function that queries you about the name of a country
and then gives you a fun fact about it. It's supposed to ask you if you
want to add the country you asked about to the dictionary (if it doesn't
already know it). I think the code is just fine. But it doesn't really add
the new country-fact to the dictionary after it asks you :/ Can someone
please identify the problem?
def countries():
param = input("please enter the country you'd like a fun fact about")
listofcountries = {"Kuwait": "has 10% of the world's oil reserves.",
"UAE": "has the world's highest free-standing structrure, Burj
Khalifa.", "Qatar": "is hosting the FIFA 2022 world cup.", "Saudi
Arabia": "is the largest GCC country.", "Bahrain": "held the Dilmun
civilization, one of the world's oldest civilizations.", "Oman": "is
known for its beautiful green mountains."}
if (param in listofcountries):
print ("I know something about", param)
print (param, listofcountries[param])
else:
print ("I don't know anything about", param)
add_yesorno = input("Would you like to add something to the list?
(yes or no)")
if add_yesorno == 'yes':
country_name = input("What's its name again?")
add_yes = input("please finish this sentence. This country...")
print ("Thanks a lot for contributing to the list!")
listofcountries[country_name] = add_yes
else:
print ("Thanks then! See you later.")
So I defined this function that queries you about the name of a country
and then gives you a fun fact about it. It's supposed to ask you if you
want to add the country you asked about to the dictionary (if it doesn't
already know it). I think the code is just fine. But it doesn't really add
the new country-fact to the dictionary after it asks you :/ Can someone
please identify the problem?
def countries():
param = input("please enter the country you'd like a fun fact about")
listofcountries = {"Kuwait": "has 10% of the world's oil reserves.",
"UAE": "has the world's highest free-standing structrure, Burj
Khalifa.", "Qatar": "is hosting the FIFA 2022 world cup.", "Saudi
Arabia": "is the largest GCC country.", "Bahrain": "held the Dilmun
civilization, one of the world's oldest civilizations.", "Oman": "is
known for its beautiful green mountains."}
if (param in listofcountries):
print ("I know something about", param)
print (param, listofcountries[param])
else:
print ("I don't know anything about", param)
add_yesorno = input("Would you like to add something to the list?
(yes or no)")
if add_yesorno == 'yes':
country_name = input("What's its name again?")
add_yes = input("please finish this sentence. This country...")
print ("Thanks a lot for contributing to the list!")
listofcountries[country_name] = add_yes
else:
print ("Thanks then! See you later.")
MS Access Row locking/Page Locking issue
MS Access Row locking/Page Locking issue
The database is used by multiple users and each user has their own file. I
have changed all possible settings but seems like "edit lock" is still
locking the whole page and not the edited row. Does anyone know the
possible solution? Also the database is split into front and back end.
The database is used by multiple users and each user has their own file. I
have changed all possible settings but seems like "edit lock" is still
locking the whole page and not the edited row. Does anyone know the
possible solution? Also the database is split into front and back end.
SQL Server Allocation of amount in bill
SQL Server Allocation of amount in bill
I have the following tables
LINEID BILL Total Amount Allocated Amount
1 1 100
2 1 200
3 2 250
PAYID BILL Paid Amount
1 1 250
2 2 100
I need to allocate the Paid amoount on the first table based on the bill.
I know that I can use the cursor with WHILE loop and allocate - is there a
better way to do this?
Result should be
LINEID BILL Total Amount Allocated Amount
1 1 100 100
2 1 200 150
3 2 250 100
I have the following tables
LINEID BILL Total Amount Allocated Amount
1 1 100
2 1 200
3 2 250
PAYID BILL Paid Amount
1 1 250
2 2 100
I need to allocate the Paid amoount on the first table based on the bill.
I know that I can use the cursor with WHILE loop and allocate - is there a
better way to do this?
Result should be
LINEID BILL Total Amount Allocated Amount
1 1 100 100
2 1 200 150
3 2 250 100
Can the new DriveApp parameters be used to search a specific folder?
Can the new DriveApp parameters be used to search a specific folder?
I am looking for a way to search a specific folder using DriveApp in
Google Apps Script. Here is what I have tried:
var folders = DriveApp.getFolderById('searchedFolderId');
var results = folders.searchFolders( "title contains '"+searchTerm+"'");
while (results.hasNext()) {
var folder = results.next();
// do something with search results here
}
Whenever I try this method, I only get the first folder found returned in
the folder iterator even though there are many other results.
I have also tried:
var results = DriveApp.searchFolders( "'searchedFolderId' in parents and
title contains '"+searchTerm+"'");
Now, whenever I try this method, I sometimes get more than one found
folder returned in the folder iterator. Is there a way to search a
specific folder using the DriveApp API...am I doing something wrong?
Thanks!
I am looking for a way to search a specific folder using DriveApp in
Google Apps Script. Here is what I have tried:
var folders = DriveApp.getFolderById('searchedFolderId');
var results = folders.searchFolders( "title contains '"+searchTerm+"'");
while (results.hasNext()) {
var folder = results.next();
// do something with search results here
}
Whenever I try this method, I only get the first folder found returned in
the folder iterator even though there are many other results.
I have also tried:
var results = DriveApp.searchFolders( "'searchedFolderId' in parents and
title contains '"+searchTerm+"'");
Now, whenever I try this method, I sometimes get more than one found
folder returned in the folder iterator. Is there a way to search a
specific folder using the DriveApp API...am I doing something wrong?
Thanks!
how to add grid on top of image which is used as panel in google app script?
how to add grid on top of image which is used as panel in google app script?
I am creating a panel having grid with controls like text box,label etc.
which should appear on image.
For that I have main panel
var mainPanel =
app.createVerticalPanel().setId("mainPanel").setVisible(false);
on this main panel I have added an image
var file =getFileFromFolder(existedFileName);
var fileID = file.getId();
var url = 'http://....;
mainPanel.add(mainImage);
Now on this image I need to add some controls so I have done something
like this...
var requiredGrid = app.createGrid(1,
2).setVisible(false).setId("requiredGrid");
mainPanel.add(requiredGrid);
but this adds requiredGrid below the image panel. Now I want to add this
on image i.e. image should come as a background for the requiredGrid.
I am creating a panel having grid with controls like text box,label etc.
which should appear on image.
For that I have main panel
var mainPanel =
app.createVerticalPanel().setId("mainPanel").setVisible(false);
on this main panel I have added an image
var file =getFileFromFolder(existedFileName);
var fileID = file.getId();
var url = 'http://....;
mainPanel.add(mainImage);
Now on this image I need to add some controls so I have done something
like this...
var requiredGrid = app.createGrid(1,
2).setVisible(false).setId("requiredGrid");
mainPanel.add(requiredGrid);
but this adds requiredGrid below the image panel. Now I want to add this
on image i.e. image should come as a background for the requiredGrid.
Sunday, 15 September 2013
Clickable area with background image and text
Clickable area with background image and text
I'm a front-end novice and am trying to figure out how to build the
following in my rails app:
https://dl.dropboxusercontent.com/u/10334022/browse.png
Each image is a company model with the attributes title, subtitle, image,
and number of deals. I want the entire area of each separate image to be
clickable and link to the "show" action. Also I need to darken the image a
to make the text more readable. My question is how to make each individual
picture-button.
Currently, I have bootstrap deployed on my app via the following gem in my
Gemfile:
gem 'bootstrap-sass', '2.3.2.0'
I am using carrierwave to store the images and they are accessible in the
views the following way:
<%= image_tag @company.image_url %>
This seems like it will be a long answer, but I really don't know where to
start. Thanks alot!
I'm a front-end novice and am trying to figure out how to build the
following in my rails app:
https://dl.dropboxusercontent.com/u/10334022/browse.png
Each image is a company model with the attributes title, subtitle, image,
and number of deals. I want the entire area of each separate image to be
clickable and link to the "show" action. Also I need to darken the image a
to make the text more readable. My question is how to make each individual
picture-button.
Currently, I have bootstrap deployed on my app via the following gem in my
Gemfile:
gem 'bootstrap-sass', '2.3.2.0'
I am using carrierwave to store the images and they are accessible in the
views the following way:
<%= image_tag @company.image_url %>
This seems like it will be a long answer, but I really don't know where to
start. Thanks alot!
how to zoom into a small section of the screen android
how to zoom into a small section of the screen android
Hey i am new to android and i wanted to know how to zoom into a small
section of the screen as if a camera is moving across the screen and
zooming into particular parts of the screen. i want to be able to create
the effect that the app is automatically zooming across the screen and
more into particular contents on the screen. i have tried searching alot
of places but i need to at least confirm its possible to be done. a bit
similar to imageview when a user double clicks an image but automatic
Hey i am new to android and i wanted to know how to zoom into a small
section of the screen as if a camera is moving across the screen and
zooming into particular parts of the screen. i want to be able to create
the effect that the app is automatically zooming across the screen and
more into particular contents on the screen. i have tried searching alot
of places but i need to at least confirm its possible to be done. a bit
similar to imageview when a user double clicks an image but automatic
confusion on subnet total addresses
confusion on subnet total addresses
I know how to get a first and last usable, broadcast and network addresses
but my question is on total addresses,
for example if I have a address 146.88.57.23/25
would it be ---> 255 - 128 = 127 + 1 = 128
would that equal to 128 of total addresses ?
I know how to get a first and last usable, broadcast and network addresses
but my question is on total addresses,
for example if I have a address 146.88.57.23/25
would it be ---> 255 - 128 = 127 + 1 = 128
would that equal to 128 of total addresses ?
how to create an options menu at the bottom of the device nexus
how to create an options menu at the bottom of the device nexus
I have a problem, I would make an application without actionbar but I
would still put a options menu. On devices that have a physical key, do
not show the problem, but on devices like the galaxy nexus, yes. How can I
make a options menu that appears in the bottom of the screen? To help you
understand I put a picture below.
Thanks in advance for the answers
rebus
image: http://img585.imageshack.us/img585/8291/2tzc.jpg
I have a problem, I would make an application without actionbar but I
would still put a options menu. On devices that have a physical key, do
not show the problem, but on devices like the galaxy nexus, yes. How can I
make a options menu that appears in the bottom of the screen? To help you
understand I put a picture below.
Thanks in advance for the answers
rebus
image: http://img585.imageshack.us/img585/8291/2tzc.jpg
How to remove word in C string
How to remove word in C string
I currently have a char array that is storing a filename.
eg. folder1/subfolder/subsubfolder/file1.txt
I want to be able to remove the first folder name in this char array. so
it becomes
subfolder/subsubfolder/file1.txt
I know that basename() will make the output file1.txt but I need the
folder structure, just not the first one.
What is the best way to do it? use / as a delineating character?
I currently have a char array that is storing a filename.
eg. folder1/subfolder/subsubfolder/file1.txt
I want to be able to remove the first folder name in this char array. so
it becomes
subfolder/subsubfolder/file1.txt
I know that basename() will make the output file1.txt but I need the
folder structure, just not the first one.
What is the best way to do it? use / as a delineating character?
reading excel file in windows using perl
reading excel file in windows using perl
How do I read an .xlsx file in windows7 using perl module use
Spreadsheet::ParseExcel. it gives me an error that no excel data in
file.Does windows require some other module to read data from an excel
file. please help
How do I read an .xlsx file in windows7 using perl module use
Spreadsheet::ParseExcel. it gives me an error that no excel data in
file.Does windows require some other module to read data from an excel
file. please help
Memory leak - multiple instance of activity
Memory leak - multiple instance of activity
I've got a couple of activities. The thing is the app is running out of
memory. I tried to gc.clean() in all activities (in onDestroy), null
references, launchMode="singleTop" but without any success.
In MAT i've found out that I have multiple objects of the same activity
and it a default behaviour, if I'm not mistaken.
If i launch at first time, for example i will have main activity: 1, if i
will quit and launch again i will have 2 instance.
that the VM budget just grow and make force close dialog.
Example of my code:
public class Splash extends Activity { private RelativeLayout splash_layout;
private RelativeLayout welcome_message_layout;
private TextView welcome_message_text;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_layout);
splash_layout = (RelativeLayout)findViewById(R.id.splash_layout);
welcome_message_layout =
(RelativeLayout)findViewById(R.id.welcome_message_layout);
welcome_message_text = (TextView)findViewById(R.id.welcome_message_text);
if(ref.getBoolean("LANGUAGEMODECHANGE",false))
{
welcome_message_layout.setBackgroundResource(R.drawable.welcome_message);
welcome_message_text.setText(getString(R.string.welcome));
switch(ref.getInt("LANGUAGEMODENUMBER",Consts.DEFAULT))
{
case Consts.HEBREW:
splash_layout.setBackgroundResource(R.drawable.welcome_hebrew);
break;
case Consts.ENGLISH:
splash_layout.setBackgroundResource(R.drawable.welcome_english);
break;
case Consts.RUSSIAN:
splash_layout.setBackgroundResource(R.drawable.welcome_russian);
break;
case Consts.ARABIC:
splash_layout.setBackgroundResource(R.drawable.welcome_arabic);
break;
default:
splash_layout.setBackgroundResource(R.drawable.bg);
break;
}//close switch
}
}//close onCreate
}//close Splah
Where is the leak?
I've got a couple of activities. The thing is the app is running out of
memory. I tried to gc.clean() in all activities (in onDestroy), null
references, launchMode="singleTop" but without any success.
In MAT i've found out that I have multiple objects of the same activity
and it a default behaviour, if I'm not mistaken.
If i launch at first time, for example i will have main activity: 1, if i
will quit and launch again i will have 2 instance.
that the VM budget just grow and make force close dialog.
Example of my code:
public class Splash extends Activity { private RelativeLayout splash_layout;
private RelativeLayout welcome_message_layout;
private TextView welcome_message_text;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash_layout);
splash_layout = (RelativeLayout)findViewById(R.id.splash_layout);
welcome_message_layout =
(RelativeLayout)findViewById(R.id.welcome_message_layout);
welcome_message_text = (TextView)findViewById(R.id.welcome_message_text);
if(ref.getBoolean("LANGUAGEMODECHANGE",false))
{
welcome_message_layout.setBackgroundResource(R.drawable.welcome_message);
welcome_message_text.setText(getString(R.string.welcome));
switch(ref.getInt("LANGUAGEMODENUMBER",Consts.DEFAULT))
{
case Consts.HEBREW:
splash_layout.setBackgroundResource(R.drawable.welcome_hebrew);
break;
case Consts.ENGLISH:
splash_layout.setBackgroundResource(R.drawable.welcome_english);
break;
case Consts.RUSSIAN:
splash_layout.setBackgroundResource(R.drawable.welcome_russian);
break;
case Consts.ARABIC:
splash_layout.setBackgroundResource(R.drawable.welcome_arabic);
break;
default:
splash_layout.setBackgroundResource(R.drawable.bg);
break;
}//close switch
}
}//close onCreate
}//close Splah
Where is the leak?
Saturday, 14 September 2013
Warning: include(../../inc/functions.php): failed to open stream: no such file or directory
Warning: include(../../inc/functions.php): failed to open stream: no such
file or directory
This is the situation that I face off, the following is the structure of
the site:
[root]
index.php
[inc] // inside of this folder is functions.php
[css]
[img]
[connect] // inside of this folder is db.php and setup.php
[admin]
index.php
[img]
[css]
**[inc] // inside of this folder is functions.php**
[connect] // inside of this folder is db.php and setup.php to connect
the admin
[content] // here is page.php
[op] // here are add.php, modify.php, delete.php
I've tested using absolute and relative paths, DIR,
$_SERVER['DOCUMENT_ROOT'], etc
the problem is when I tried to include the functions.php file from the
folder inc to the folder content or op. I've tested in some different ways
and checks some answers from here I cannot fixed it.
Could someone fix this issue?
file or directory
This is the situation that I face off, the following is the structure of
the site:
[root]
index.php
[inc] // inside of this folder is functions.php
[css]
[img]
[connect] // inside of this folder is db.php and setup.php
[admin]
index.php
[img]
[css]
**[inc] // inside of this folder is functions.php**
[connect] // inside of this folder is db.php and setup.php to connect
the admin
[content] // here is page.php
[op] // here are add.php, modify.php, delete.php
I've tested using absolute and relative paths, DIR,
$_SERVER['DOCUMENT_ROOT'], etc
the problem is when I tried to include the functions.php file from the
folder inc to the folder content or op. I've tested in some different ways
and checks some answers from here I cannot fixed it.
Could someone fix this issue?
Embedding Image Data in CSS with System.Web.Optimization
Embedding Image Data in CSS with System.Web.Optimization
I have been searching all day reading articles, blogs, forums about this,
but either I'm not understanding it well or I truly haven't found the
answer.
On my site, I have implemented microsft.web.optimization v.1.0.0 and found
an extension method below (which can be found at Optimizing without
drawbacks):
public class CssImageEmbedTransform : CssMinify {
private static readonly Regex url = new
Regex(@"url\((([^\)]*)\?embed)\)", RegexOptions.IgnoreCase);
private const string format = "url(data:image/{0};base64,{1})";
public override void Process(BundleResponse bundle) {
base.Process(bundle);
string reference = HttpContext.Current.Request.ApplicationPath +
"includes/css/";
// Before Using BundleTable to ResolveUrl in head control
// HttpContext.Current.Request.Path.Replace("/barry.css", "/");
// debug stuff
// HttpContext.Current.Response.Write("<br />Before Matches<br />");
//
HttpContext.Current.Response.Write(url.Matches(bundle.Content).Count
+ "<br />");
foreach (Match match in url.Matches(bundle.Content)) {
var file = new FileInfo(HostingEnvironment.MapPath(reference +
match.Groups[2].Value));
if (file.Exists) {
string dataUri = GetDataUri(file);
bundle.Content = bundle.Content.Replace(match.Value,
dataUri);
HttpContext.Current.Response.AddFileDependency(file.FullName);
}
}
// debug stuff
// HttpContext.Current.Response.Write("After Matches");
// HttpContext.Current.Response.End();
}
private string GetDataUri(FileInfo file) {
byte[] buffer = File.ReadAllBytes(file.FullName);
string ext = file.Extension.Substring(1);
return string.Format(format, ext, Convert.ToBase64String(buffer));
}
}Along with this code:
private void SetupBundles() {
BundleTable.Bundles.EnableDefaultBundles();
Bundle css = new Bundle("~/mycc.css",
typeof(CssImageEmbedTransform));
css.AddFile("~/includes/css/mycss.css");
BundleTable.Bundles.Add(css);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}What that did was convert background-image:
url(Images/myImage.png?embed); to background-image:
url(data:image/png;base64,iVBORw0KGgoA...lFTkSuQmCC);.
I have recently updated my site to use system.web.optimization v.1.1.0
(found at Bundling and Minification) and I'm wondering if there is
something similar or better (maybe built-in) to accomplish the same?
Thanks!
I have been searching all day reading articles, blogs, forums about this,
but either I'm not understanding it well or I truly haven't found the
answer.
On my site, I have implemented microsft.web.optimization v.1.0.0 and found
an extension method below (which can be found at Optimizing without
drawbacks):
public class CssImageEmbedTransform : CssMinify {
private static readonly Regex url = new
Regex(@"url\((([^\)]*)\?embed)\)", RegexOptions.IgnoreCase);
private const string format = "url(data:image/{0};base64,{1})";
public override void Process(BundleResponse bundle) {
base.Process(bundle);
string reference = HttpContext.Current.Request.ApplicationPath +
"includes/css/";
// Before Using BundleTable to ResolveUrl in head control
// HttpContext.Current.Request.Path.Replace("/barry.css", "/");
// debug stuff
// HttpContext.Current.Response.Write("<br />Before Matches<br />");
//
HttpContext.Current.Response.Write(url.Matches(bundle.Content).Count
+ "<br />");
foreach (Match match in url.Matches(bundle.Content)) {
var file = new FileInfo(HostingEnvironment.MapPath(reference +
match.Groups[2].Value));
if (file.Exists) {
string dataUri = GetDataUri(file);
bundle.Content = bundle.Content.Replace(match.Value,
dataUri);
HttpContext.Current.Response.AddFileDependency(file.FullName);
}
}
// debug stuff
// HttpContext.Current.Response.Write("After Matches");
// HttpContext.Current.Response.End();
}
private string GetDataUri(FileInfo file) {
byte[] buffer = File.ReadAllBytes(file.FullName);
string ext = file.Extension.Substring(1);
return string.Format(format, ext, Convert.ToBase64String(buffer));
}
}Along with this code:
private void SetupBundles() {
BundleTable.Bundles.EnableDefaultBundles();
Bundle css = new Bundle("~/mycc.css",
typeof(CssImageEmbedTransform));
css.AddFile("~/includes/css/mycss.css");
BundleTable.Bundles.Add(css);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}What that did was convert background-image:
url(Images/myImage.png?embed); to background-image:
url(data:image/png;base64,iVBORw0KGgoA...lFTkSuQmCC);.
I have recently updated my site to use system.web.optimization v.1.1.0
(found at Bundling and Minification) and I'm wondering if there is
something similar or better (maybe built-in) to accomplish the same?
Thanks!
Record last activity of a logged in user in Pyramid
Record last activity of a logged in user in Pyramid
In an application I am building in Pyramid,I have a users table with a
field called 'last_activity'. This field is intented to store the
timestamp of the last time a user visited a page in the system.
Since I'm still a bit new in pyramid, I don't know if pyramid has some
sort of way to create a "common" view that can be executed everytime a
user visits any page in the site (in order to update the 'last_activity'
field in this view function). Is this possible?
If that is not possible, what would you recommend me to do this?
Thanks in advance.
In an application I am building in Pyramid,I have a users table with a
field called 'last_activity'. This field is intented to store the
timestamp of the last time a user visited a page in the system.
Since I'm still a bit new in pyramid, I don't know if pyramid has some
sort of way to create a "common" view that can be executed everytime a
user visits any page in the site (in order to update the 'last_activity'
field in this view function). Is this possible?
If that is not possible, what would you recommend me to do this?
Thanks in advance.
(Homework) Converting an NFA to a DFA with a lambda transition, but no transition for some a in the alphabet
(Homework) Converting an NFA to a DFA with a lambda transition, but no
transition for some a in the alphabet
If my alphabet is {a,b} and my nfa has a state q0 with the following
transition:
State | a b (no input)
--------------------------------------------
q0 q1 null q1
Is this table wrong? should delta(q0, b) = q1 because q0 can move on (no
input) to state q1?
transition for some a in the alphabet
If my alphabet is {a,b} and my nfa has a state q0 with the following
transition:
State | a b (no input)
--------------------------------------------
q0 q1 null q1
Is this table wrong? should delta(q0, b) = q1 because q0 can move on (no
input) to state q1?
How to calculate address subtraction in c++
How to calculate address subtraction in c++
I am a little surprised by the output of the following code:
double array[] = {4, 5, 6, 8, 10, 20};
double* p = array + 3;
//Print array address
cout << (unsigned long)(array) << endl; //This prints 1768104
cout << (unsigned long)(p) << endl; //This prints 1768128
//print p - array
cout << (unsigned long)(p - array) << endl; // This prints 3
I am surprised that the last line prints 3. Shouldn't it print 24 = 3 * 8
bytes? Also, as expected, the address of p is the address of array + 3 * 8
bytes. This seems inconsistent. In fact, it is not even a legal assignment
to write: p = p - array; // can't assign an int to type double* No idea,
why this is an int.
I am a little surprised by the output of the following code:
double array[] = {4, 5, 6, 8, 10, 20};
double* p = array + 3;
//Print array address
cout << (unsigned long)(array) << endl; //This prints 1768104
cout << (unsigned long)(p) << endl; //This prints 1768128
//print p - array
cout << (unsigned long)(p - array) << endl; // This prints 3
I am surprised that the last line prints 3. Shouldn't it print 24 = 3 * 8
bytes? Also, as expected, the address of p is the address of array + 3 * 8
bytes. This seems inconsistent. In fact, it is not even a legal assignment
to write: p = p - array; // can't assign an int to type double* No idea,
why this is an int.
Unit tests with java
Unit tests with java
I'm working on test cases in java.
I have a code something like this:
class Sample
{
public boolean isALive(boolean isLive, int num)
{
return if isLive ? num == 3 : num == 2 || num == 3;
}
}
In the tests, it will be something like this,
assertTrue(x.isAlive(true,1); with various combinations
Is there way to simplify or optimize this even more for all the tests to
pass ?
I'm working on test cases in java.
I have a code something like this:
class Sample
{
public boolean isALive(boolean isLive, int num)
{
return if isLive ? num == 3 : num == 2 || num == 3;
}
}
In the tests, it will be something like this,
assertTrue(x.isAlive(true,1); with various combinations
Is there way to simplify or optimize this even more for all the tests to
pass ?
Converting a PHP function to Objective-C and Java?
Converting a PHP function to Objective-C and Java?
I've written a function in PHP that I now need to write in Objective-C and
Java for an iOS and Android app respectively, but having issues with where
to even start.
The function is:
public static function decrypt($string, $key='my_key')
{
$result = '';
$string = str_replace(' ', '+', $string);
$string = base64_decode($string);
$string = str_replace($key, '', $string);
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)-ord($keychar));
$result.=$char;
}
return $result;
}
Result should return string:id
Anyone able to show me how to covert this into both languages? Any
guidance would be greatly appreciated.
Thanks.
I've written a function in PHP that I now need to write in Objective-C and
Java for an iOS and Android app respectively, but having issues with where
to even start.
The function is:
public static function decrypt($string, $key='my_key')
{
$result = '';
$string = str_replace(' ', '+', $string);
$string = base64_decode($string);
$string = str_replace($key, '', $string);
for($i=0; $i<strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key))-1, 1);
$char = chr(ord($char)-ord($keychar));
$result.=$char;
}
return $result;
}
Result should return string:id
Anyone able to show me how to covert this into both languages? Any
guidance would be greatly appreciated.
Thanks.
Friday, 13 September 2013
CustomListView and CursorAdapter Searching issue
CustomListView and CursorAdapter Searching issue
I have a custom ListView and I can access and show data from database. I
also have serach filter to search data in customListview
/*
* Serach Filter
*/
cursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchDataByName(constraint.toString());
}
});
searchOption.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int start, int before,
int count) {
// TODO Auto-generated method stub
AbstractActivity.this.cursorAdapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int
count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
The problem is When I don't perform any search, onItemClick is working
fine. But, when I try to Search any ListView item and want to access that
item. It shows this
09-14 06:17:50.280: E/AndroidRuntime(1091): FATAL EXCEPTION: main
09-14 06:17:50.280: E/AndroidRuntime(1091):
java.lang.IllegalArgumentException: column 'AF_NAME' does not exist
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
com.yasiradnan.abstracts.AbstractActivity$1.onItemClick(AbstractActivity.java:111)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.widget.AdapterView.performItemClick(AdapterView.java:298)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.widget.AbsListView.performItemClick(AbsListView.java:1100)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.widget.AbsListView$1.run(AbsListView.java:3423)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.os.Handler.handleCallback(Handler.java:725)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.os.Handler.dispatchMessage(Handler.java:92)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.os.Looper.loop(Looper.java:137)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.app.ActivityThread.main(ActivityThread.java:5041)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
java.lang.reflect.Method.invokeNative(Native Method)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
java.lang.reflect.Method.invoke(Method.java:511)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
dalvik.system.NativeStart.main(Native Method)
Here is the onitemCLick
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
// TODO Auto-generated method stub
cursor = (Cursor)arg0.getAdapter().getItem(position);
String Text = cursor.getString(cursor.getColumnIndexOrThrow("TEXT"));
String Title =
cursor.getString(cursor.getColumnIndexOrThrow("TITLE"));
String Topic =
cursor.getString(cursor.getColumnIndexOrThrow("TOPIC"));
String value = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
String afName =
cursor.getString(cursor.getColumnIndexOrThrow("AF_NAME"));
String email =
cursor.getString(cursor.getColumnIndexOrThrow("CORRESPONDENCE"));
String refs = cursor.getString(cursor.getColumnIndexOrThrow("REFS"));
String acknowledgements =
cursor.getString(cursor.getColumnIndexOrThrow("ACKNOWLEDGEMENTS"));
Log.e("Position", String.valueOf(position));
int itemNumber = cursor.getCount();
Intent in = new Intent(getApplicationContext(),
AbstractContent.class);
in.putExtra("abstracts", Text);
in.putExtra("Title", Title);
in.putExtra("Topic", Topic);
in.putExtra("value", value);
in.putExtra("afName", afName);
in.putExtra("email", email);
in.putExtra("refs", refs);
in.putExtra("itemNumber", itemNumber);
in.putExtra("acknowledgements",acknowledgements);
startActivity(in);
}
});
Here is my Adapter Code:
Cursor cursorOne;
String getName;
@SuppressWarnings("deprecation")
public AbstractCursorAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView title = (TextView)view.findViewById(R.id.abTitle);
title.setText(cursor.getString(cursor.getColumnIndexOrThrow("TITLE")));
TextView topic = (TextView)view.findViewById(R.id.abTopic);
topic.setText(cursor.getString(cursor.getColumnIndexOrThrow("TOPIC")));
TextView type = (TextView)view.findViewById(R.id.abType);
type.setText(cursor.getString(cursor.getColumnIndexOrThrow("TYPE")));
String value = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
String sqlQuery = "select abstracts_item._id AS
ID,abstract_author.NAME AS NAME from
abstracts_item,abstract_author,authors_abstract where
abstracts_item._id = authors_abstract.abstractsitem_id and
abstract_author._id = authors_abstract.abstractauthor_id and ID =
"
+ value;
cursorOne = DatabaseHelper.database.rawQuery(sqlQuery, null);
if (cursorOne != null) {
cursorOne.moveToFirst();
do {
if (cursorOne.getPosition() == 0) {
getName =
cursorOne.getString(cursorOne.getColumnIndexOrThrow("NAME"));
} else if (cursorOne.isLast()) {
getName = getName + " & "
+
cursorOne.getString(cursorOne.getColumnIndexOrThrow("NAME"));
} else {
getName = getName + " , "
+
cursorOne.getString(cursorOne.getColumnIndexOrThrow("NAME"));
}
} while (cursorOne.moveToNext());
}
TextView authorNames = (TextView)view.findViewById(R.id.SubTitle);
/*
* Get Width
*/
WindowManager WinMgr =
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
int displayWidth = WinMgr.getDefaultDisplay().getWidth();
Paint paint = new Paint();
Rect bounds = new Rect();
int text_height = 0;
int text_width = 0;
paint.getTextBounds(getName, 0, getName.length(), bounds);
text_height = bounds.height();
text_width = bounds.width();
if (text_width > displayWidth) {
//Log.e("Width inside",
String.valueOf(text_width)+"--------------"+String.valueOf(displayWidth));
String output = getName.split(",")[0] + " et al. ";
authorNames.setText(output);
} else {
//Log.e("Width inside",
String.valueOf(text_width)+"--------------"+String.valueOf(displayWidth));
authorNames
.setText(getName.replaceAll("((?:^|[^A-Z.])[A-Z])[a-z]*\\s(?=[A-Z])",
"$1."));
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup
viewgroup) {
// TODO Auto-generated method stub
LayoutInflater inflater =
LayoutInflater.from(viewgroup.getContext());
View returnView = inflater.inflate(R.layout.abstract_content,
viewgroup, false);
return returnView;
}
}
Now, My question why this is happening? How can I solve that ? Can you
give me a tutorial project link similar search function and
customListview, So that I can see what they're doing. I tried to find it
on google,but didn't found. Thanks
I have a custom ListView and I can access and show data from database. I
also have serach filter to search data in customListview
/*
* Serach Filter
*/
cursorAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return dbHelper.fetchDataByName(constraint.toString());
}
});
searchOption.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int start, int before,
int count) {
// TODO Auto-generated method stub
AbstractActivity.this.cursorAdapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int
count, int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
The problem is When I don't perform any search, onItemClick is working
fine. But, when I try to Search any ListView item and want to access that
item. It shows this
09-14 06:17:50.280: E/AndroidRuntime(1091): FATAL EXCEPTION: main
09-14 06:17:50.280: E/AndroidRuntime(1091):
java.lang.IllegalArgumentException: column 'AF_NAME' does not exist
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.database.AbstractCursor.getColumnIndexOrThrow(AbstractCursor.java:303)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
com.yasiradnan.abstracts.AbstractActivity$1.onItemClick(AbstractActivity.java:111)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.widget.AdapterView.performItemClick(AdapterView.java:298)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.widget.AbsListView.performItemClick(AbsListView.java:1100)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.widget.AbsListView$PerformClick.run(AbsListView.java:2749)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.widget.AbsListView$1.run(AbsListView.java:3423)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.os.Handler.handleCallback(Handler.java:725)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.os.Handler.dispatchMessage(Handler.java:92)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.os.Looper.loop(Looper.java:137)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
android.app.ActivityThread.main(ActivityThread.java:5041)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
java.lang.reflect.Method.invokeNative(Native Method)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
java.lang.reflect.Method.invoke(Method.java:511)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-14 06:17:50.280: E/AndroidRuntime(1091): at
dalvik.system.NativeStart.main(Native Method)
Here is the onitemCLick
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View view, int position,
long arg3) {
// TODO Auto-generated method stub
cursor = (Cursor)arg0.getAdapter().getItem(position);
String Text = cursor.getString(cursor.getColumnIndexOrThrow("TEXT"));
String Title =
cursor.getString(cursor.getColumnIndexOrThrow("TITLE"));
String Topic =
cursor.getString(cursor.getColumnIndexOrThrow("TOPIC"));
String value = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
String afName =
cursor.getString(cursor.getColumnIndexOrThrow("AF_NAME"));
String email =
cursor.getString(cursor.getColumnIndexOrThrow("CORRESPONDENCE"));
String refs = cursor.getString(cursor.getColumnIndexOrThrow("REFS"));
String acknowledgements =
cursor.getString(cursor.getColumnIndexOrThrow("ACKNOWLEDGEMENTS"));
Log.e("Position", String.valueOf(position));
int itemNumber = cursor.getCount();
Intent in = new Intent(getApplicationContext(),
AbstractContent.class);
in.putExtra("abstracts", Text);
in.putExtra("Title", Title);
in.putExtra("Topic", Topic);
in.putExtra("value", value);
in.putExtra("afName", afName);
in.putExtra("email", email);
in.putExtra("refs", refs);
in.putExtra("itemNumber", itemNumber);
in.putExtra("acknowledgements",acknowledgements);
startActivity(in);
}
});
Here is my Adapter Code:
Cursor cursorOne;
String getName;
@SuppressWarnings("deprecation")
public AbstractCursorAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView title = (TextView)view.findViewById(R.id.abTitle);
title.setText(cursor.getString(cursor.getColumnIndexOrThrow("TITLE")));
TextView topic = (TextView)view.findViewById(R.id.abTopic);
topic.setText(cursor.getString(cursor.getColumnIndexOrThrow("TOPIC")));
TextView type = (TextView)view.findViewById(R.id.abType);
type.setText(cursor.getString(cursor.getColumnIndexOrThrow("TYPE")));
String value = cursor.getString(cursor.getColumnIndexOrThrow("_id"));
String sqlQuery = "select abstracts_item._id AS
ID,abstract_author.NAME AS NAME from
abstracts_item,abstract_author,authors_abstract where
abstracts_item._id = authors_abstract.abstractsitem_id and
abstract_author._id = authors_abstract.abstractauthor_id and ID =
"
+ value;
cursorOne = DatabaseHelper.database.rawQuery(sqlQuery, null);
if (cursorOne != null) {
cursorOne.moveToFirst();
do {
if (cursorOne.getPosition() == 0) {
getName =
cursorOne.getString(cursorOne.getColumnIndexOrThrow("NAME"));
} else if (cursorOne.isLast()) {
getName = getName + " & "
+
cursorOne.getString(cursorOne.getColumnIndexOrThrow("NAME"));
} else {
getName = getName + " , "
+
cursorOne.getString(cursorOne.getColumnIndexOrThrow("NAME"));
}
} while (cursorOne.moveToNext());
}
TextView authorNames = (TextView)view.findViewById(R.id.SubTitle);
/*
* Get Width
*/
WindowManager WinMgr =
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
int displayWidth = WinMgr.getDefaultDisplay().getWidth();
Paint paint = new Paint();
Rect bounds = new Rect();
int text_height = 0;
int text_width = 0;
paint.getTextBounds(getName, 0, getName.length(), bounds);
text_height = bounds.height();
text_width = bounds.width();
if (text_width > displayWidth) {
//Log.e("Width inside",
String.valueOf(text_width)+"--------------"+String.valueOf(displayWidth));
String output = getName.split(",")[0] + " et al. ";
authorNames.setText(output);
} else {
//Log.e("Width inside",
String.valueOf(text_width)+"--------------"+String.valueOf(displayWidth));
authorNames
.setText(getName.replaceAll("((?:^|[^A-Z.])[A-Z])[a-z]*\\s(?=[A-Z])",
"$1."));
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup
viewgroup) {
// TODO Auto-generated method stub
LayoutInflater inflater =
LayoutInflater.from(viewgroup.getContext());
View returnView = inflater.inflate(R.layout.abstract_content,
viewgroup, false);
return returnView;
}
}
Now, My question why this is happening? How can I solve that ? Can you
give me a tutorial project link similar search function and
customListview, So that I can see what they're doing. I tried to find it
on google,but didn't found. Thanks
casperjs page loading: how to auto-load page's script files?
casperjs page loading: how to auto-load page's script files?
I'm new to casperjs and my desire is to try to test the javascript loaded
by certain pages of a web app. I'm using casper.thenOpen to load a page
from the web server, but it doesn't in turn load the tags that reference
js files. I even checked the web server's access log and sure enough, only
the page itself was requested, not the js files.
I would imagine there is built in functionality for doing this, but if I
have to do this manually I can live with writing my own utility function
for it. But again, being new to casperjs, I'm not sure how I'd go about it
- I haven't been able to locate examples that will help me figure this
out.
I'm new to casperjs and my desire is to try to test the javascript loaded
by certain pages of a web app. I'm using casper.thenOpen to load a page
from the web server, but it doesn't in turn load the tags that reference
js files. I even checked the web server's access log and sure enough, only
the page itself was requested, not the js files.
I would imagine there is built in functionality for doing this, but if I
have to do this manually I can live with writing my own utility function
for it. But again, being new to casperjs, I'm not sure how I'd go about it
- I haven't been able to locate examples that will help me figure this
out.
Joomla 2.5 Select All as page limit gives zero result
Joomla 2.5 Select All as page limit gives zero result
I developed a joomla 2.5 custom component for showing data table that
implemented filtering, shorting, and pagination. But in the middle of
pagination I selected page limit as All.It doesn't gives me any
result.When I select All as page limit it works well except only above
scenario.Seams page limit is set to 0.Then db query will like SELECT* FROM
_tebleName LIMIT 0,0.
I developed a joomla 2.5 custom component for showing data table that
implemented filtering, shorting, and pagination. But in the middle of
pagination I selected page limit as All.It doesn't gives me any
result.When I select All as page limit it works well except only above
scenario.Seams page limit is set to 0.Then db query will like SELECT* FROM
_tebleName LIMIT 0,0.
why is this happening to my jquery ui animation?
why is this happening to my jquery ui animation?
This is my HTML code
<div id="menu_status_item">
<span class="menu_status_bar"></span>
</div>
This is my CSS:
#menu_status_item
{
margin-top: 40px;
width: 100%;
}
.menu_status_bar
{
margin-left: 45px;
color: #fff;
}
And this is my jquery
var statusMessage = 'Success'
var colorCode = '';
var statusText = '';
if(statusMessage.indexOf("Success") > -1) {
colorCode = '#33CC33';
statusText = 'Success';
}else{
colorCode = '#CC0000';
statusText = 'Failure';
}
$(".menu_status_bar").css("display", "inline-table");
$(".menu_status_bar").text(statusText);
$("#menu_status_item").animate({backgroundColor: colorCode}, 4000);
$("#menu_status_item").animate({backgroundColor: "#ffffff"});
$(".menu_status_bar").css("display", "none");
Basically i want the text "Success" inside the menu_status_bar to appear,
do the animation, and disappear with the display: none.
If i use the display:none at the end, the text won't even show up. If i
remove it, the animation works, but the text will remain there... if
someone selects it, its horrible because the text will be highlighted.
Does any one know what could this be? or how can i achieve the same result
but doing it differently?
Thanks.
This is my HTML code
<div id="menu_status_item">
<span class="menu_status_bar"></span>
</div>
This is my CSS:
#menu_status_item
{
margin-top: 40px;
width: 100%;
}
.menu_status_bar
{
margin-left: 45px;
color: #fff;
}
And this is my jquery
var statusMessage = 'Success'
var colorCode = '';
var statusText = '';
if(statusMessage.indexOf("Success") > -1) {
colorCode = '#33CC33';
statusText = 'Success';
}else{
colorCode = '#CC0000';
statusText = 'Failure';
}
$(".menu_status_bar").css("display", "inline-table");
$(".menu_status_bar").text(statusText);
$("#menu_status_item").animate({backgroundColor: colorCode}, 4000);
$("#menu_status_item").animate({backgroundColor: "#ffffff"});
$(".menu_status_bar").css("display", "none");
Basically i want the text "Success" inside the menu_status_bar to appear,
do the animation, and disappear with the display: none.
If i use the display:none at the end, the text won't even show up. If i
remove it, the animation works, but the text will remain there... if
someone selects it, its horrible because the text will be highlighted.
Does any one know what could this be? or how can i achieve the same result
but doing it differently?
Thanks.
Is a static variable in java treated as a pointer internally?
Is a static variable in java treated as a pointer internally?
I have a question about the key word static. Lets say for instance we have
this piece of code.
public class Foo
{
private int age;
private static int weight;
..
...
}
Say in main you create 2 objects. You change the age in one and then you
change the weight in the other. Does that mean that the weight also
changes in the first object as well? If that is the case then does that
mean that weight is a pointer?
I guess my question in a nutshell would be. How does static work
internally? Is it essentially of a pointer type?
I have a question about the key word static. Lets say for instance we have
this piece of code.
public class Foo
{
private int age;
private static int weight;
..
...
}
Say in main you create 2 objects. You change the age in one and then you
change the weight in the other. Does that mean that the weight also
changes in the first object as well? If that is the case then does that
mean that weight is a pointer?
I guess my question in a nutshell would be. How does static work
internally? Is it essentially of a pointer type?
which binlog format runs mysql replication efficiently
which binlog format runs mysql replication efficiently
which binlog format runs mysql replication efficiently.Also many times
slave gets stopped because of errors like 1062,1054,1677,1032,1452.Any
help in this regarding can be useful.
which binlog format runs mysql replication efficiently.Also many times
slave gets stopped because of errors like 1062,1054,1677,1032,1452.Any
help in this regarding can be useful.
Thursday, 12 September 2013
c# - how to make this code as different manner?
c# - how to make this code as different manner?
Below code is my interview question but I don't know how to make perfect
Code:
public class Shape
{
public void Rectangle(int length, int height)
{
Console.Write(length * height);
}
public void Circle(int radius)
{
Console.Write(3.14 * (radius * radius));
}
}
Any ideas? Thanks in advance
Below code is my interview question but I don't know how to make perfect
Code:
public class Shape
{
public void Rectangle(int length, int height)
{
Console.Write(length * height);
}
public void Circle(int radius)
{
Console.Write(3.14 * (radius * radius));
}
}
Any ideas? Thanks in advance
Using Regex to validate a variable length string
Using Regex to validate a variable length string
I'm trying to validate a form field in Java using Regex, which can have 5
different format possibilities. I'm struggling to get this one working.
The string to be checked will be between 4-6 alphanumeric characters.
If it's 4 characters, it must be all numbers.
^\\d{4}$
If it's 5 characters, it can be all numbers, first position letter with 4
following numbers, or first 3 positions letters followed with 2 numbers.
^\\d{5}$
^[a-zA-Z]\\d{4}$
^[a-zA-Z]{3}\\d{2}$
And if it's 6 characters, it will be first position letter, 4 numbers, and
last another letter.
^[a-zA-Z]\\d{4}[a-zA-Z]$
I just can't seem to piece it all together though.
I'm trying to validate a form field in Java using Regex, which can have 5
different format possibilities. I'm struggling to get this one working.
The string to be checked will be between 4-6 alphanumeric characters.
If it's 4 characters, it must be all numbers.
^\\d{4}$
If it's 5 characters, it can be all numbers, first position letter with 4
following numbers, or first 3 positions letters followed with 2 numbers.
^\\d{5}$
^[a-zA-Z]\\d{4}$
^[a-zA-Z]{3}\\d{2}$
And if it's 6 characters, it will be first position letter, 4 numbers, and
last another letter.
^[a-zA-Z]\\d{4}[a-zA-Z]$
I just can't seem to piece it all together though.
How to create Instance by java.lang.reflect.Type
How to create Instance by java.lang.reflect.Type
I want to set property of class by using reflect,
and my class have a List<Article> property.
i just get the generics type of the List<Artile> by below code
Method[] methods = target.getClass().getMethods();
String key = k.toString(), methodName = "set" + key;
Method method = getMethod(methods, methodName);
if (Iterable.class.isAssignableFrom(method.getParameterTypes()[0])) {
// at there, i get the generics type of list
// how can i create a instance of this type?
Type type = getGenericsType(method);
}
public static Method getMethod(Method[] methods, String methodName) {
for (Method method : methods) {
if (method.getName().equalsIgnoreCase(methodName))
return method;
}
return null;
}
private static Type getGenericsType(Method method) {
Type[] types = method.getGenericParameterTypes();
for (int i = 0; i < types.length; i++) {
ParameterizedType pt = (ParameterizedType) types[i];
if (pt.getActualTypeArguments().length > 0)
return pt.getActualTypeArguments()[0];
}
return null;
}
EDIT:
i just solved it with a stupid solution,
its instantiation generics type by using Class.forName();
the class name come from type.toString()
Type type = getGenericsType(method);
Class<?> genericsType = null;
try {
genericsType = Class.forName(getClassName(type));
// now, i have a instance of generics type
Object o = genericsType.newInstance();
} catch (Exception e) {
}
static String NAME_PREFIX = "class ";
private static String getClassName(Type type) {
String fullName = type.toString();
if (fullName.startsWith(NAME_PREFIX))
return fullName.substring(NAME_PREFIX.length());
return fullName;
}
I want to set property of class by using reflect,
and my class have a List<Article> property.
i just get the generics type of the List<Artile> by below code
Method[] methods = target.getClass().getMethods();
String key = k.toString(), methodName = "set" + key;
Method method = getMethod(methods, methodName);
if (Iterable.class.isAssignableFrom(method.getParameterTypes()[0])) {
// at there, i get the generics type of list
// how can i create a instance of this type?
Type type = getGenericsType(method);
}
public static Method getMethod(Method[] methods, String methodName) {
for (Method method : methods) {
if (method.getName().equalsIgnoreCase(methodName))
return method;
}
return null;
}
private static Type getGenericsType(Method method) {
Type[] types = method.getGenericParameterTypes();
for (int i = 0; i < types.length; i++) {
ParameterizedType pt = (ParameterizedType) types[i];
if (pt.getActualTypeArguments().length > 0)
return pt.getActualTypeArguments()[0];
}
return null;
}
EDIT:
i just solved it with a stupid solution,
its instantiation generics type by using Class.forName();
the class name come from type.toString()
Type type = getGenericsType(method);
Class<?> genericsType = null;
try {
genericsType = Class.forName(getClassName(type));
// now, i have a instance of generics type
Object o = genericsType.newInstance();
} catch (Exception e) {
}
static String NAME_PREFIX = "class ";
private static String getClassName(Type type) {
String fullName = type.toString();
if (fullName.startsWith(NAME_PREFIX))
return fullName.substring(NAME_PREFIX.length());
return fullName;
}
Based on multiple criterias on parent's siblings
Based on multiple criterias on parent's siblings
I would like to know if I can combine at the same time an XPath looking
for the previous sibling of a certain class with a certain text and at the
same time a sibling at the same level with a certain text.
For example I would like to find the following cells:
<td class="sdawatt_booknow"><a href="#"
onclick="wa_class_book(160832)">Book</a></td>
by looking up a sibling of class sdawatt_hrdcell containing the text Spin
preceded by a td of class sdawatt_banner with the text Monday - 16
September 2013.
Or the following td:
<td class="sdawatt_booknow"><a href="#"
onclick="wa_class_book(160864)">Book</a></td>
if we look for the date of the 'Friday - 13 September 2013'.
Is this something doable in Xpath ?
<table cellspacing="0" cellpadding="0" border="0"
style="border-collapse:collapse;" class="sdawatt_outer">
<tbody><tr>
<td class="sdawatt_hdrcell">Time</td>
<td class="sdawatt_hdrcell">Class</td>
<td class="sdawatt_hdrcell">Level</td>
<td class="sdawatt_hdrcell">Spaces</td>
<td class="sdawatt_hdrcell">Location</td>
<td class="sdawatt_hdrcell">Instructors</td>
<td class="sdawatt_hdrcell">Tags</td>
<td class="sdawatt_hdrcell">Info</td>
<td class="sdawatt_hdrcell">Book</td>
</tr><tr>
<td colspan="9" class="sdawatt_banner">Friday - 13 September
2013</td>
</tr><tr class="sdawatt_classrow">
<td class="sdawatt_time">07:45-08:15</td>
<td class="sdawatt_classname">Boxing</td>
<td class="sdawatt_level"> </td>
<td class="sdawatt_spaces">14 Left</td>
<td class="sdawatt_location">Main Studio</td>
<td class="sdawatt_resources"> Darren</td>
<td class=" sdawatt_infotags"></td>
<td class="sdawatt_info"><img
src="https://v4.fitnessandlifestylecentre.com/webaccess/TimetableView/information.gif"
class="tiptip" /></td>
<td class="sdawatt_booknow"><a href="#"
onclick="wa_class_book(160848)">Book</a></td>
</tr><tr class="sdawatt_classrow">
<td class="sdawatt_time">12:00-12:45</td>
<td class="sdawatt_classname">Spin</td>
<td class="sdawatt_level"> </td>
<td class="sdawatt_spaces">8 Left</td>
<td class="sdawatt_location">Main Studio</td>
<td class="sdawatt_resources"> Matt</td>
<td class=" sdawatt_infotags"></td>
<td class="sdawatt_info"><img
src="https://v4.fitnessandlifestylecentre.com/webaccess/TimetableView/information.gif"
class="tiptip" /></td>
<td class="sdawatt_booknow"><a href="#"
onclick="wa_class_book(160864)">Book</a></td>
</tr><tr>
<td colspan="9" class="sdawatt_banner">Monday - 16 September
2013</td>
</tr><tr class="sdawatt_classrow">
<td class="sdawatt_time">13:00-13:45</td>
<td class="sdawatt_classname">Spin</td>
<td class="sdawatt_level"> </td>
<td class="sdawatt_spaces">12 Left</td>
<td class="sdawatt_location">Main Studio</td>
<td class="sdawatt_resources"> Marzena</td>
<td class=" sdawatt_infotags"></td>
<td class="sdawatt_info">
<img
src="https://v4.fitnessandlifestylecentre.com/webaccess/TimetableView/information.gif"
class="tiptip" /></td>
<td class="sdawatt_booknow"><a href="#"
onclick="wa_class_book(160832)">Book</a></td>
</tr>
</tbody></table>
I would like to know if I can combine at the same time an XPath looking
for the previous sibling of a certain class with a certain text and at the
same time a sibling at the same level with a certain text.
For example I would like to find the following cells:
<td class="sdawatt_booknow"><a href="#"
onclick="wa_class_book(160832)">Book</a></td>
by looking up a sibling of class sdawatt_hrdcell containing the text Spin
preceded by a td of class sdawatt_banner with the text Monday - 16
September 2013.
Or the following td:
<td class="sdawatt_booknow"><a href="#"
onclick="wa_class_book(160864)">Book</a></td>
if we look for the date of the 'Friday - 13 September 2013'.
Is this something doable in Xpath ?
<table cellspacing="0" cellpadding="0" border="0"
style="border-collapse:collapse;" class="sdawatt_outer">
<tbody><tr>
<td class="sdawatt_hdrcell">Time</td>
<td class="sdawatt_hdrcell">Class</td>
<td class="sdawatt_hdrcell">Level</td>
<td class="sdawatt_hdrcell">Spaces</td>
<td class="sdawatt_hdrcell">Location</td>
<td class="sdawatt_hdrcell">Instructors</td>
<td class="sdawatt_hdrcell">Tags</td>
<td class="sdawatt_hdrcell">Info</td>
<td class="sdawatt_hdrcell">Book</td>
</tr><tr>
<td colspan="9" class="sdawatt_banner">Friday - 13 September
2013</td>
</tr><tr class="sdawatt_classrow">
<td class="sdawatt_time">07:45-08:15</td>
<td class="sdawatt_classname">Boxing</td>
<td class="sdawatt_level"> </td>
<td class="sdawatt_spaces">14 Left</td>
<td class="sdawatt_location">Main Studio</td>
<td class="sdawatt_resources"> Darren</td>
<td class=" sdawatt_infotags"></td>
<td class="sdawatt_info"><img
src="https://v4.fitnessandlifestylecentre.com/webaccess/TimetableView/information.gif"
class="tiptip" /></td>
<td class="sdawatt_booknow"><a href="#"
onclick="wa_class_book(160848)">Book</a></td>
</tr><tr class="sdawatt_classrow">
<td class="sdawatt_time">12:00-12:45</td>
<td class="sdawatt_classname">Spin</td>
<td class="sdawatt_level"> </td>
<td class="sdawatt_spaces">8 Left</td>
<td class="sdawatt_location">Main Studio</td>
<td class="sdawatt_resources"> Matt</td>
<td class=" sdawatt_infotags"></td>
<td class="sdawatt_info"><img
src="https://v4.fitnessandlifestylecentre.com/webaccess/TimetableView/information.gif"
class="tiptip" /></td>
<td class="sdawatt_booknow"><a href="#"
onclick="wa_class_book(160864)">Book</a></td>
</tr><tr>
<td colspan="9" class="sdawatt_banner">Monday - 16 September
2013</td>
</tr><tr class="sdawatt_classrow">
<td class="sdawatt_time">13:00-13:45</td>
<td class="sdawatt_classname">Spin</td>
<td class="sdawatt_level"> </td>
<td class="sdawatt_spaces">12 Left</td>
<td class="sdawatt_location">Main Studio</td>
<td class="sdawatt_resources"> Marzena</td>
<td class=" sdawatt_infotags"></td>
<td class="sdawatt_info">
<img
src="https://v4.fitnessandlifestylecentre.com/webaccess/TimetableView/information.gif"
class="tiptip" /></td>
<td class="sdawatt_booknow"><a href="#"
onclick="wa_class_book(160832)">Book</a></td>
</tr>
</tbody></table>
Wednesday, 11 September 2013
how to call a variable outside of function
how to call a variable outside of function
jquery
$(selector).on('click',function(){
var $myvar = 'hi';
});
alert($myvar); // this won't alert hi as this is out of click function
How can I call that $myvar outside the function?
jquery
$(selector).on('click',function(){
var $myvar = 'hi';
});
alert($myvar); // this won't alert hi as this is out of click function
How can I call that $myvar outside the function?
Invoke Java program in Linux using "./"
Invoke Java program in Linux using "./"
Is it possible to invoke a Java program in a Linux command line using a
command like "./hello"?
Is it possible to invoke a Java program in a Linux command line using a
command like "./hello"?
Subscribe to:
Comments (Atom)