Mention 2 modifications that can be done to a linked list data structure
so that it is converted into a binary tree data structure?
It's an A level question. I looked it out on google but only programs are
found. I need theory explanation.
Saturday, 31 August 2013
listview setItemChecked not working properly
listview setItemChecked not working properly
I am having an issue with a listview populated by a merge cursor. I have a
button in my application to select all the entries in my listview. The
function called when the button is pressed is the following:
private void selectAllEntries() {
int numberOfItemsInList = listView.getCount();
for (int i = 0; i < numberOfItemsInList; i++) {
this.listView.setItemChecked(i, true);
}
}
The problem is that not all the entries get checked in the end. Very weird
indeed. After some testing I noticed that if I have 10 entries in the
mergecursor (5 from cursor a and 5 from cursor b), then if I only do
setItemChecked on the first 5 elements everything works okay (those 5
entries get checked), if I do setItemchecked on the last 5 elements again
everything works okay (the entries from cursor b get checked), but if I do
setItemChecked on elements from both cursors then the maximum number of
elements getting checked is the number of elements in cursor a (5 in our
example), with an offset of (number of items I wanted to set - number of
items in cursor a). I'll write down a couple of examples as this is a very
weird behaviour.
Example 1:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
setItemChecked(0,true);
setItemChecked(1,true);
setItemChecked(2,true);
setItemChecked(3,true);
setItemChecked(4,true);
Results:
element 0 (from cursor a, checked)
element 1 (from cursor a, checked)
element 2 (from cursor a, checked)
element 3 (from cursor a, checked)
element 4 (from cursor a, checked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
Example 2:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
setItemChecked(5,true);
setItemChecked(6,true);
setItemChecked(7,true);
setItemChecked(8,true);
setItemChecked(9,true);
results:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, checked)
element 6 (from cursor b, checked)
element 7 (from cursor b, checked)
element 8 (from cursor b, checked)
element 9 (from cursor b, checked)
Example 3:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
setItemChecked(0,true);
setItemChecked(1,true);
setItemChecked(2,true);
setItemChecked(3,true);
setItemChecked(4,true);
setItemChecked(5,true);
results in
element 0 (from cursor a, unchecked)
element 1 (from cursor a, checked)
element 2 (from cursor a, checked)
element 3 (from cursor a, checked)
element 4 (from cursor a, checked)
element 5 (from cursor b, checked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
Example 4:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
setItemChecked(0,true);
setItemChecked(1,true);
setItemChecked(2,true);
setItemChecked(3,true);
setItemChecked(4,true);
setItemChecked(5,true);
setItemChecked(6,true);
results:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, checked)
element 3 (from cursor a, checked)
element 4 (from cursor a, checked)
element 5 (from cursor b, checked)
element 6 (from cursor b, checked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
Example 5:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
setItemChecked(0,true);
setItemChecked(1,true);
setItemChecked(2,true);
setItemChecked(3,true);
setItemChecked(4,true);
setItemChecked(5,true);
setItemChecked(6,true);
setItemChecked(7,true);
results:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, checked)
element 4 (from cursor a, checked)
element 5 (from cursor b, checked)
element 6 (from cursor b, checked)
element 7 (from cursor b, checked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
I am using the
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
and
notifyDataSetChanged()
doesn't help either. Any help ?
As a side-note, the
listView.getCount();
always returns the correct number of entries in the view
I am having an issue with a listview populated by a merge cursor. I have a
button in my application to select all the entries in my listview. The
function called when the button is pressed is the following:
private void selectAllEntries() {
int numberOfItemsInList = listView.getCount();
for (int i = 0; i < numberOfItemsInList; i++) {
this.listView.setItemChecked(i, true);
}
}
The problem is that not all the entries get checked in the end. Very weird
indeed. After some testing I noticed that if I have 10 entries in the
mergecursor (5 from cursor a and 5 from cursor b), then if I only do
setItemChecked on the first 5 elements everything works okay (those 5
entries get checked), if I do setItemchecked on the last 5 elements again
everything works okay (the entries from cursor b get checked), but if I do
setItemChecked on elements from both cursors then the maximum number of
elements getting checked is the number of elements in cursor a (5 in our
example), with an offset of (number of items I wanted to set - number of
items in cursor a). I'll write down a couple of examples as this is a very
weird behaviour.
Example 1:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
setItemChecked(0,true);
setItemChecked(1,true);
setItemChecked(2,true);
setItemChecked(3,true);
setItemChecked(4,true);
Results:
element 0 (from cursor a, checked)
element 1 (from cursor a, checked)
element 2 (from cursor a, checked)
element 3 (from cursor a, checked)
element 4 (from cursor a, checked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
Example 2:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
setItemChecked(5,true);
setItemChecked(6,true);
setItemChecked(7,true);
setItemChecked(8,true);
setItemChecked(9,true);
results:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, checked)
element 6 (from cursor b, checked)
element 7 (from cursor b, checked)
element 8 (from cursor b, checked)
element 9 (from cursor b, checked)
Example 3:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
setItemChecked(0,true);
setItemChecked(1,true);
setItemChecked(2,true);
setItemChecked(3,true);
setItemChecked(4,true);
setItemChecked(5,true);
results in
element 0 (from cursor a, unchecked)
element 1 (from cursor a, checked)
element 2 (from cursor a, checked)
element 3 (from cursor a, checked)
element 4 (from cursor a, checked)
element 5 (from cursor b, checked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
Example 4:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
setItemChecked(0,true);
setItemChecked(1,true);
setItemChecked(2,true);
setItemChecked(3,true);
setItemChecked(4,true);
setItemChecked(5,true);
setItemChecked(6,true);
results:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, checked)
element 3 (from cursor a, checked)
element 4 (from cursor a, checked)
element 5 (from cursor b, checked)
element 6 (from cursor b, checked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
Example 5:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, unchecked)
element 4 (from cursor a, unchecked)
element 5 (from cursor b, unchecked)
element 6 (from cursor b, unchecked)
element 7 (from cursor b, unchecked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
setItemChecked(0,true);
setItemChecked(1,true);
setItemChecked(2,true);
setItemChecked(3,true);
setItemChecked(4,true);
setItemChecked(5,true);
setItemChecked(6,true);
setItemChecked(7,true);
results:
element 0 (from cursor a, unchecked)
element 1 (from cursor a, unchecked)
element 2 (from cursor a, unchecked)
element 3 (from cursor a, checked)
element 4 (from cursor a, checked)
element 5 (from cursor b, checked)
element 6 (from cursor b, checked)
element 7 (from cursor b, checked)
element 8 (from cursor b, unchecked)
element 9 (from cursor b, unchecked)
I am using the
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
and
notifyDataSetChanged()
doesn't help either. Any help ?
As a side-note, the
listView.getCount();
always returns the correct number of entries in the view
How to rename a column of a pandas.core.series.TimeSeries object?
How to rename a column of a pandas.core.series.TimeSeries object?
Substracting the 'Settle' column of a pandas.core.frame.DataFrame from the
'Settle' column of another pandas.core.frame.DataFrame resulted in a
pandas.core.series.TimeSeries object (the 'subs' object).
Now, when I plot subs and add a legend, it reads 'Settle'.
How can I change the name of a column of a pandas.core.series.TimeSeries
object?
thank you.
Substracting the 'Settle' column of a pandas.core.frame.DataFrame from the
'Settle' column of another pandas.core.frame.DataFrame resulted in a
pandas.core.series.TimeSeries object (the 'subs' object).
Now, when I plot subs and add a legend, it reads 'Settle'.
How can I change the name of a column of a pandas.core.series.TimeSeries
object?
thank you.
Java: Keep SecureRandom (SHA1PRNG) seed secret - calculate hash before seeding?
Java: Keep SecureRandom (SHA1PRNG) seed secret - calculate hash before
seeding?
I'm using SecureRandom with SHA1PRNG to generate a random sequence. I
won't let SecureRandom seed itself, I'm using my own values to seed it.
(Please don't tell me that this is unsafe, I have my reasons for doing
this).
However, I don't want anyone to know what seed I used. The seed must
remain secret and it shouldn't be possible to recalculate the seed from
the random sequence.
Does it make sense to calculate the SHA-512 from my value and seed
SecureRandom with it? Or will SecureRandom create a SHA1 hash from the
seed itself?
Long story short: Should I seed SecureRandom with "value".getBytes() or
with the SHA-512 hash of "value", if I want to keep "value" secret?
Where can I find information how the SHA1PRNG algorithm works?
seeding?
I'm using SecureRandom with SHA1PRNG to generate a random sequence. I
won't let SecureRandom seed itself, I'm using my own values to seed it.
(Please don't tell me that this is unsafe, I have my reasons for doing
this).
However, I don't want anyone to know what seed I used. The seed must
remain secret and it shouldn't be possible to recalculate the seed from
the random sequence.
Does it make sense to calculate the SHA-512 from my value and seed
SecureRandom with it? Or will SecureRandom create a SHA1 hash from the
seed itself?
Long story short: Should I seed SecureRandom with "value".getBytes() or
with the SHA-512 hash of "value", if I want to keep "value" secret?
Where can I find information how the SHA1PRNG algorithm works?
java.awt.image.BufferedImage.getRBG not returning expected values
java.awt.image.BufferedImage.getRBG not returning expected values
I'm trying to use the BufferedImage.getRGB method with seven parameters to
read an area of pixels and to get their colors. Sounds simple enough, but
for some reason it just won't work for me. Here's a short, self contained,
compilable example:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BufferedImageTest extends JPanel {
BufferedImage image;
public static void main(String[] args) {
BufferedImageTest mainClass = new BufferedImageTest();
mainClass.run();
}
private void run() {
initWindow();
// Create image:
image = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
int[] red = new int[25];
for (int i = 0; i < 25; i++)
red[i] = Color.RED.getRGB();
image.setRGB(1, 0, 3, 5, red, 0, 0);
// Read image:
int[] rgbArray = new int[25];
int w = image.getWidth();
int h = image.getHeight();
image.getRGB(0, 0, w, h, rgbArray, 0, 0);
for (int i = 0; i < rgbArray.length; i++) {
Color c = new Color(rgbArray[i]);
System.out.print("(" + c.getRed() + "," + c.getGreen() + "," +
c.getBlue() + ")");
if (i % 5 == 4)
System.out.println("");
}
}
@Override
public void paint(Graphics g) {
g.drawImage(image, 5, 5, null);
}
private void initWindow() {
JFrame frame = new JFrame();
frame.getContentPane().add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(40, 60);
frame.setVisible(true);
}
}
In the run() method I first create a very simple 5 by 5 pixel image like
this:
That goes fine. I then try to read in the pixels of that image, and that
doesn't work almost at all. It only gets the first line of pixels
correctly, then displays the rest as black. The output of the printing
loop is:
(0,0,0)(255,0,0)(255,0,0)(255,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
when I would expect it to be entirely like the first line. What am I
missing here? I have tried writing it all over from the scratch and
playing with the "scanline" and "offset" parameters in the getRGB call,
but nothing seems to work. I'm running Java 7 on Windows 7, if that makes
any difference.
I'm trying to use the BufferedImage.getRGB method with seven parameters to
read an area of pixels and to get their colors. Sounds simple enough, but
for some reason it just won't work for me. Here's a short, self contained,
compilable example:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BufferedImageTest extends JPanel {
BufferedImage image;
public static void main(String[] args) {
BufferedImageTest mainClass = new BufferedImageTest();
mainClass.run();
}
private void run() {
initWindow();
// Create image:
image = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB);
int[] red = new int[25];
for (int i = 0; i < 25; i++)
red[i] = Color.RED.getRGB();
image.setRGB(1, 0, 3, 5, red, 0, 0);
// Read image:
int[] rgbArray = new int[25];
int w = image.getWidth();
int h = image.getHeight();
image.getRGB(0, 0, w, h, rgbArray, 0, 0);
for (int i = 0; i < rgbArray.length; i++) {
Color c = new Color(rgbArray[i]);
System.out.print("(" + c.getRed() + "," + c.getGreen() + "," +
c.getBlue() + ")");
if (i % 5 == 4)
System.out.println("");
}
}
@Override
public void paint(Graphics g) {
g.drawImage(image, 5, 5, null);
}
private void initWindow() {
JFrame frame = new JFrame();
frame.getContentPane().add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(40, 60);
frame.setVisible(true);
}
}
In the run() method I first create a very simple 5 by 5 pixel image like
this:
That goes fine. I then try to read in the pixels of that image, and that
doesn't work almost at all. It only gets the first line of pixels
correctly, then displays the rest as black. The output of the printing
loop is:
(0,0,0)(255,0,0)(255,0,0)(255,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
(0,0,0)(0,0,0)(0,0,0)(0,0,0)(0,0,0)
when I would expect it to be entirely like the first line. What am I
missing here? I have tried writing it all over from the scratch and
playing with the "scanline" and "offset" parameters in the getRGB call,
but nothing seems to work. I'm running Java 7 on Windows 7, if that makes
any difference.
why is the following code not behving correctly?
why is the following code not behving correctly?
I wrote following piece of code to verify if the input is a valid pan
number using regular expressions. It is returning "NO" for ABCDS1234Y.
void process(string inp)
{
string panex= "[A-Z]{5}[0-9]{4}[A-Z]{1}";
regex panreg(panex,regex_constants::basic);
if(regex_match(inp,panreg))
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
http://ideone.com/fgGScw
is there something wrong with compiler or the regular expression.
I wrote following piece of code to verify if the input is a valid pan
number using regular expressions. It is returning "NO" for ABCDS1234Y.
void process(string inp)
{
string panex= "[A-Z]{5}[0-9]{4}[A-Z]{1}";
regex panreg(panex,regex_constants::basic);
if(regex_match(inp,panreg))
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
http://ideone.com/fgGScw
is there something wrong with compiler or the regular expression.
StimulSoft text wordwrap in table columns
StimulSoft text wordwrap in table columns
I have designed a table with some columns in stimul,I assign a constant
width to table columns, I want that each cell do wordwrap for even one
word, for example if Column width=10px cell's text width=20 px I want the
word to fit into the cell by multiline and keep the width 10px but stimul
grow the width of the column.I know it is wordwrap multiline a text but it
doesnt multi line a word.forexample I want this word: 'Windows' to be
written in two/more lines if it doesnt fit the width of column. I have
tried fixed width and can grow and wordwrap but none of them do the
functionality that I need. the only way is to make the word have
underlined with wordwrap ,and I dont want underlines on my text. So is
there any suggestion or solution for that?
I have designed a table with some columns in stimul,I assign a constant
width to table columns, I want that each cell do wordwrap for even one
word, for example if Column width=10px cell's text width=20 px I want the
word to fit into the cell by multiline and keep the width 10px but stimul
grow the width of the column.I know it is wordwrap multiline a text but it
doesnt multi line a word.forexample I want this word: 'Windows' to be
written in two/more lines if it doesnt fit the width of column. I have
tried fixed width and can grow and wordwrap but none of them do the
functionality that I need. the only way is to make the word have
underlined with wordwrap ,and I dont want underlines on my text. So is
there any suggestion or solution for that?
Friday, 30 August 2013
jQuery submit form with click event with new action
jQuery submit form with click event with new action
I am having a form like this
<form name="test" action="test/test_new" />
<input type="text" />
<input type="submit" value="search"/>
<input type="button" value="download"/>
I need a click even for download button. Eg. If i click download it should
submit as text/text_new.xls instead of text/text_new. How can i do it.
I am having a form like this
<form name="test" action="test/test_new" />
<input type="text" />
<input type="submit" value="search"/>
<input type="button" value="download"/>
I need a click even for download button. Eg. If i click download it should
submit as text/text_new.xls instead of text/text_new. How can i do it.
Thursday, 29 August 2013
Lock entire mysql database from hibernate
Lock entire mysql database from hibernate
I want to lock entire mysql database from hibernate, I mean put in a read
mode all the tables. Something like
FLUSH TABLES WITH READ LOCK;
And then unlock the database allways through hibernate. Thanks in advance!
Richard
I want to lock entire mysql database from hibernate, I mean put in a read
mode all the tables. Something like
FLUSH TABLES WITH READ LOCK;
And then unlock the database allways through hibernate. Thanks in advance!
Richard
Continue FOR loop after a function finished
Continue FOR loop after a function finished
I have a for loop from which a function is called.In that function i have
a AJAX call.After ajax finishes then it returns a value to the for loop.
then only for loop has to be continued.
for ( var j = 0; j < req.questionId.length; j++) {
var getanswer = getAnswers();
}
function getAnswers(){
$.getJSON("getAnswers?question_id="+questionId,function(data){
return "success";
});
}
I have a for loop from which a function is called.In that function i have
a AJAX call.After ajax finishes then it returns a value to the for loop.
then only for loop has to be continued.
for ( var j = 0; j < req.questionId.length; j++) {
var getanswer = getAnswers();
}
function getAnswers(){
$.getJSON("getAnswers?question_id="+questionId,function(data){
return "success";
});
}
Wednesday, 28 August 2013
selecting a record from a table based on column value of another table
selecting a record from a table based on column value of another table
I know forming this query is trivial, but I am not able frame the exact
query. Based on what I have read so far, the solution may include joining
two tables. Here is the problem :
TABLE_ONE {S_NO, DK_NO, FRM , DATE}
TABLE_TWO {S_NO, DK_NO , TO}
I want to select a record from TABLE_ONE based on an input value of DK_NO
and value checked for TO field of TABLE_TWO or FRM field of TABLE_ONE
unsuccessful trials so far:
1)
$sql = "select * from TABLE_ONE where DK_NO like '%".$dkno."%' and
(FRM='".$department."' or (daktracker.dakno like '%".$dakno."%' and
daktracker.todeptt='".$department."'))";
2)
$sql = "select * from TABLE_ONE where DK_NO like '%".$dkno."%' and
(FRM='".$department."' or daktracker.todeptt='".$department."')";
I know forming this query is trivial, but I am not able frame the exact
query. Based on what I have read so far, the solution may include joining
two tables. Here is the problem :
TABLE_ONE {S_NO, DK_NO, FRM , DATE}
TABLE_TWO {S_NO, DK_NO , TO}
I want to select a record from TABLE_ONE based on an input value of DK_NO
and value checked for TO field of TABLE_TWO or FRM field of TABLE_ONE
unsuccessful trials so far:
1)
$sql = "select * from TABLE_ONE where DK_NO like '%".$dkno."%' and
(FRM='".$department."' or (daktracker.dakno like '%".$dakno."%' and
daktracker.todeptt='".$department."'))";
2)
$sql = "select * from TABLE_ONE where DK_NO like '%".$dkno."%' and
(FRM='".$department."' or daktracker.todeptt='".$department."')";
Why this select query to Oracle database doesn't work?
Why this select query to Oracle database doesn't work?
First I tested simple cases:
cmd.Parameters.Add(new OracleParameter(":paramCode",
OracleDbType.NVarchar2)).Value = userCode;
cmd.CommandText = "SELECT * FROM VIEWUSERDATA WHERE Codigo = :paramCode";
cmd.CommandType = System.Data.CommandType.Text;
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//Works, retrieve data
}
Another:
cmd.Parameters.Add(new OracleParameter(":paramRole",
OracleDbType.NVarchar2)).Value = userRole;
cmd.CommandText = "SELECT * FROM VIEWUSERDATA WHERE Role = :paramRole";
...
while (reader.Read())
{
//Also works
}
But when join, doesn't work.
cmd.Parameters.Add(new OracleParameter(":paramCode",
OracleDbType.NVarchar2)).Value = userCode;
cmd.Parameters.Add(new OracleParameter(":paramRole",
OracleDbType.NVarchar2)).Value = userRole;
cmd.CommandText = "SELECT * FROM VIEWUSERDATA WHERE Role = :paramRole AND
Code = :paramCode";
...
while (reader.Read())//don't retrieve anything
{
}
Data exists, If I do the query in an external query editor(window) works
fine.
Thanks.
First I tested simple cases:
cmd.Parameters.Add(new OracleParameter(":paramCode",
OracleDbType.NVarchar2)).Value = userCode;
cmd.CommandText = "SELECT * FROM VIEWUSERDATA WHERE Codigo = :paramCode";
cmd.CommandType = System.Data.CommandType.Text;
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
//Works, retrieve data
}
Another:
cmd.Parameters.Add(new OracleParameter(":paramRole",
OracleDbType.NVarchar2)).Value = userRole;
cmd.CommandText = "SELECT * FROM VIEWUSERDATA WHERE Role = :paramRole";
...
while (reader.Read())
{
//Also works
}
But when join, doesn't work.
cmd.Parameters.Add(new OracleParameter(":paramCode",
OracleDbType.NVarchar2)).Value = userCode;
cmd.Parameters.Add(new OracleParameter(":paramRole",
OracleDbType.NVarchar2)).Value = userRole;
cmd.CommandText = "SELECT * FROM VIEWUSERDATA WHERE Role = :paramRole AND
Code = :paramCode";
...
while (reader.Read())//don't retrieve anything
{
}
Data exists, If I do the query in an external query editor(window) works
fine.
Thanks.
Round numbers in Javascript before decimal point
Round numbers in Javascript before decimal point
How do you round down a number before the decimal points So not 45.1 -> 45
But 47 -> 45 Or 45 -> 50
How do you round down a number before the decimal points So not 45.1 -> 45
But 47 -> 45 Or 45 -> 50
Foundation of category theory
Foundation of category theory
In the first pages of "category theory for the working mathematician"
Saunders claims that category can be introduced without set theory, as
objects and arrows without some "operations" satisfying some properties
which are called axioms. (he calls this metacategories)
I like that approach, but either I just try to understand things
intuitively, either if someone claims that everything is well-defined than
I want to see it. What I don't see is the definition of "operation" which
"assigns an object to an arrow", ex: the "domain"operation assigns to an
arrow an object called domain, same for codomain, composition etc...
More precisely, if we get rid of set theory, then what is a function, what
is a pair, what is something that belongs to something.
Another question: is the need to start with other axioms then those of set
theory only related to the notion of "class" of objects or is it
problematic in other places?
In the first pages of "category theory for the working mathematician"
Saunders claims that category can be introduced without set theory, as
objects and arrows without some "operations" satisfying some properties
which are called axioms. (he calls this metacategories)
I like that approach, but either I just try to understand things
intuitively, either if someone claims that everything is well-defined than
I want to see it. What I don't see is the definition of "operation" which
"assigns an object to an arrow", ex: the "domain"operation assigns to an
arrow an object called domain, same for codomain, composition etc...
More precisely, if we get rid of set theory, then what is a function, what
is a pair, what is something that belongs to something.
Another question: is the need to start with other axioms then those of set
theory only related to the notion of "class" of objects or is it
problematic in other places?
Hibernate criteria return page and rowcount
Hibernate criteria return page and rowcount
Using Hibernate Criteria i am trying to achieve pagination but the problem
is that for every page fetch i have to make two db calls one for results
and another for total records count. Is there any efficient way so that in
a single db call i can get both the data or i can reduce db calls.
Criteria criteria=session.createCriteria(Student.class);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.add(Restrictions.ne("enquiryStatus", ENQUIRY.JOINED));
criteria.setMaxResults(10);
criteria.setFirstResult((paginate.getStartIndex()-1)*10);
criteria.setProjection(Projections.rowCount());
//here i need to fetch total row count and records
Using Hibernate Criteria i am trying to achieve pagination but the problem
is that for every page fetch i have to make two db calls one for results
and another for total records count. Is there any efficient way so that in
a single db call i can get both the data or i can reduce db calls.
Criteria criteria=session.createCriteria(Student.class);
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.add(Restrictions.ne("enquiryStatus", ENQUIRY.JOINED));
criteria.setMaxResults(10);
criteria.setFirstResult((paginate.getStartIndex()-1)*10);
criteria.setProjection(Projections.rowCount());
//here i need to fetch total row count and records
Xtext:xtend: How to generate constructors and commentary lines with JvmModelInferrer.xtend?
Xtext:xtend: How to generate constructors and commentary lines with
JvmModelInferrer.xtend?
i tried the five simple steps to your JVM language example on
http://www.eclipse.org/Xtext/documentation.html#JvmDomainmodel. There you
can find the DSL file.
I generate my dsl entity instances into Java code via
DomaninModelInferrer.xtend. The actual file looks like this:
DomainmodelJvmModelInferrer.xtend
To generate Javadoc descriptions for methods i did this
(setDocumentation(...)):
Operation:{
members+=feature.toMethod(feature.name,feature.type)[
setDocumentation(it, feature.documentation) // Javadoc
Method
if (feature.static == true)
{
setStatic(true);
}
for (p:feature.params){
parameters+=p.toParameter(p.name,p.parameterType)
}
body=feature.body
]
}
I wanted to add an constructor too for my entity element, but i really
dont know how to realise it. There is a method in JvmTypesBuilder
toConstructor:
JvmConstructor JvmTypesBuilder.toConstructor(EObject sourceElement,
Procedure1<? super JvmConstructor> initializer)
But i dont know how to use it :/. Can someone explain? The Xtext online
documentation is okay, for understanding the theory thing, but there are
less code examples :(
Second Question: How to generate commentary lines? For Example, i write
something like this in my model:
op getFriendsSortedByFullName():List<Person>
{
// this is a test comment
return friends.sortBy(f | f.fullName);
}
DSL code for Operations:
Operation:
(static?='static')? 'op' name=ValidID
'('(params+=FullJvmFormalParameter
(',' params+=FullJvmFormalParameter)*)?')'
':' type=JvmTypeReference
body=XBlockExpression
The
body=XBlockExpression
doesnt allow commentary lines between the method hull. So it doesnt
generate comment lines.
I hope someone can help me :/
JvmModelInferrer.xtend?
i tried the five simple steps to your JVM language example on
http://www.eclipse.org/Xtext/documentation.html#JvmDomainmodel. There you
can find the DSL file.
I generate my dsl entity instances into Java code via
DomaninModelInferrer.xtend. The actual file looks like this:
DomainmodelJvmModelInferrer.xtend
To generate Javadoc descriptions for methods i did this
(setDocumentation(...)):
Operation:{
members+=feature.toMethod(feature.name,feature.type)[
setDocumentation(it, feature.documentation) // Javadoc
Method
if (feature.static == true)
{
setStatic(true);
}
for (p:feature.params){
parameters+=p.toParameter(p.name,p.parameterType)
}
body=feature.body
]
}
I wanted to add an constructor too for my entity element, but i really
dont know how to realise it. There is a method in JvmTypesBuilder
toConstructor:
JvmConstructor JvmTypesBuilder.toConstructor(EObject sourceElement,
Procedure1<? super JvmConstructor> initializer)
But i dont know how to use it :/. Can someone explain? The Xtext online
documentation is okay, for understanding the theory thing, but there are
less code examples :(
Second Question: How to generate commentary lines? For Example, i write
something like this in my model:
op getFriendsSortedByFullName():List<Person>
{
// this is a test comment
return friends.sortBy(f | f.fullName);
}
DSL code for Operations:
Operation:
(static?='static')? 'op' name=ValidID
'('(params+=FullJvmFormalParameter
(',' params+=FullJvmFormalParameter)*)?')'
':' type=JvmTypeReference
body=XBlockExpression
The
body=XBlockExpression
doesnt allow commentary lines between the method hull. So it doesnt
generate comment lines.
I hope someone can help me :/
Tuesday, 27 August 2013
How to set the MAC address for Docker LXC containers?
How to set the MAC address for Docker LXC containers?
Whenever I run a docker container, I see that it uses a random MAC address:
eth0 Link encap:Ethernet HWaddr de:6f:de:74:bd:d9
How do I set a specific MAC address for a container run?
Will I be able to have multiple containers running simultaneously with the
same MAC address? These containers do not need to access the outside
network and do not need to talk to each other.
Whenever I run a docker container, I see that it uses a random MAC address:
eth0 Link encap:Ethernet HWaddr de:6f:de:74:bd:d9
How do I set a specific MAC address for a container run?
Will I be able to have multiple containers running simultaneously with the
same MAC address? These containers do not need to access the outside
network and do not need to talk to each other.
do.call rbind of data.table depends on location of NA
do.call rbind of data.table depends on location of NA
Consider this
do.call(rbind, list(data.table(x=1, b='x'),data.table(x=1, b=NA)))
returns
x b
1: 1 x
2: 1 NA
but
do.call(rbind, list(data.table(x=1, b=NA),data.table(x=1, b='x')))
returns
x b
1: 1 NA
2: 1 NA
How can i force the first behavior, without reordering the contents of the
list?
Data table is really really faster in mapreduce jobs (calling data.table
~10*3MM times across 55 nodes, the data table is many many times faster
than data frame, so i want this to work ...) Regards saptarshi
Consider this
do.call(rbind, list(data.table(x=1, b='x'),data.table(x=1, b=NA)))
returns
x b
1: 1 x
2: 1 NA
but
do.call(rbind, list(data.table(x=1, b=NA),data.table(x=1, b='x')))
returns
x b
1: 1 NA
2: 1 NA
How can i force the first behavior, without reordering the contents of the
list?
Data table is really really faster in mapreduce jobs (calling data.table
~10*3MM times across 55 nodes, the data table is many many times faster
than data frame, so i want this to work ...) Regards saptarshi
Can I get the Page of the PDF Document where my Full Text Search Query finds a match?
Can I get the Page of the PDF Document where my Full Text Search Query
finds a match?
Im working with SQL Server 2008 R2. Im using Full Text Search to find some
text in a PDF Document stored as VarBinary(MAX). when I make a query, it
returns the row where the keyword matches somewhere in the PDF Document
stored.. How ever Im working with large pdf documents and I would like to
know if it is possible to get Page number in the document where the
keyword is found.. :)
finds a match?
Im working with SQL Server 2008 R2. Im using Full Text Search to find some
text in a PDF Document stored as VarBinary(MAX). when I make a query, it
returns the row where the keyword matches somewhere in the PDF Document
stored.. How ever Im working with large pdf documents and I would like to
know if it is possible to get Page number in the document where the
keyword is found.. :)
How to loop a MS Word macro applying word by word in a selection?
How to loop a MS Word macro applying word by word in a selection?
I have a simple macro in order to insert a symbol into the front and back
of a word.
Selection.MoveLeft Unit:=wdWord, Count:=1
Selection.TypeText Text:="a"
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Font.Color = -603914241
Selection.Font.Size = 1
Selection.MoveRight Unit:=wdWord, Count:=1
Selection.MoveLeft Unit:=wdWord, Count:=1
Selection.MoveRight Unit:=wdWord, Count:=1
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.TypeText Text:="a"
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Font.Color = -603914241
Selection.Font.Size = 1
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.MoveRight Unit:=wdWord, Count:=1
Is there any way to make the macros looping through each word in the
selection of text? Thanks!
I have a simple macro in order to insert a symbol into the front and back
of a word.
Selection.MoveLeft Unit:=wdWord, Count:=1
Selection.TypeText Text:="a"
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Font.Color = -603914241
Selection.Font.Size = 1
Selection.MoveRight Unit:=wdWord, Count:=1
Selection.MoveLeft Unit:=wdWord, Count:=1
Selection.MoveRight Unit:=wdWord, Count:=1
Selection.MoveLeft Unit:=wdCharacter, Count:=1
Selection.TypeText Text:="a"
Selection.MoveLeft Unit:=wdCharacter, Count:=1, Extend:=wdExtend
Selection.Font.Color = -603914241
Selection.Font.Size = 1
Selection.MoveRight Unit:=wdCharacter, Count:=1
Selection.MoveRight Unit:=wdWord, Count:=1
Is there any way to make the macros looping through each word in the
selection of text? Thanks!
Accessing variable which has comma during String concatenation
Accessing variable which has comma during String concatenation
I am using following code in my jsp.
<%= scriptletVar%> returns a string like 12,000.When value is hard coded
like 12,000 it displays it fine. But when this value comes as a scriptlet
variable. It would only print 12. A separate <tr> tag would be created
having value of 000.
I am finding it difficult to find how it works when hardcoded but not when
fetched dynamically. There is something wrong with value having comma in
it, but I am unable to figure a solution.
<script type="text/javascript">
$("#table tr:eq(1)").after("<tr><td class='row-highlight txt-ctr'>
<strong><span></span></strong></td>"+
"<td class='row-highlight
txt-right'><strong></strong></td><td class='row-highlight
txt-right'><strong>" +<%= scriptletVar%> +"</strong></td>"
+
//Rest of code
I am using following code in my jsp.
<%= scriptletVar%> returns a string like 12,000.When value is hard coded
like 12,000 it displays it fine. But when this value comes as a scriptlet
variable. It would only print 12. A separate <tr> tag would be created
having value of 000.
I am finding it difficult to find how it works when hardcoded but not when
fetched dynamically. There is something wrong with value having comma in
it, but I am unable to figure a solution.
<script type="text/javascript">
$("#table tr:eq(1)").after("<tr><td class='row-highlight txt-ctr'>
<strong><span></span></strong></td>"+
"<td class='row-highlight
txt-right'><strong></strong></td><td class='row-highlight
txt-right'><strong>" +<%= scriptletVar%> +"</strong></td>"
+
//Rest of code
Static caching as image of heavy DHTML-Pages
Static caching as image of heavy DHTML-Pages
I would like to see a service, that provides a screenshot of this site,
which uses heavy dhtml and is really slow on slower computers, especially
on Firefox.
It would be perfect, if that screenshot would be actualized every few
minutes, so I could implement it into our Website with an automatic
refresh.
I would like to see a service, that provides a screenshot of this site,
which uses heavy dhtml and is really slow on slower computers, especially
on Firefox.
It would be perfect, if that screenshot would be actualized every few
minutes, so I could implement it into our Website with an automatic
refresh.
How to make mysql query fast while searchs with like
How to make mysql query fast while searchs with like
hi friends please consider my problem and give solution. i have three
table. it have to search three table with like match..the query search
10,000 records and gives results.it works fine but take 4seconds to give
results.
please give better solution to make it 1second..
profile_category_table
----------------
restaurant
sea food restaurant
------------------------
profile_keywords_table
-------------------------
rest
restroom
--------------
company_profile_table
-------------------
maha restaurants
indian restaurants..
Query:
select name from ( (SELECT PC_name as name FROM profile_category_table
WHERE PC_status=1 and PC_parentid!=0
and ( regex_replace('[^a-zA-Z0-9\-]','',remove_specialCharacter(PC_name))
LIKE '%rest%' ) GROUP BY PC_name ) UNION (SELECT PROFKEY_name as name
FROM profile_keywords_table WHERE PROFKEY_status=1
and (
regex_replace('[^a-zA-Z0-9\-]','',remove_specialCharacter(PROFKEY_name))
LIKE '%rest%' ) GROUP BY PROFKEY_name )
UNION (SELECT COM_name as name FROM company_profile_table
WHERE COM_status=1 and (
regex_replace('[^a-zA-Z0-9\-]','',remove_specialCharacter(COM_name))
LIKE '%rest%' ) GROUP BY COM_name ) )a
ORDER BY IF(name LIKE '%rest%',1,0) desc
LIMIT 0,25<br><br>
table engine:myisam;
And I add INDEX FOR THAT columns too.. how to optimize my query to execute
fast..
thnks..
hi friends please consider my problem and give solution. i have three
table. it have to search three table with like match..the query search
10,000 records and gives results.it works fine but take 4seconds to give
results.
please give better solution to make it 1second..
profile_category_table
----------------
restaurant
sea food restaurant
------------------------
profile_keywords_table
-------------------------
rest
restroom
--------------
company_profile_table
-------------------
maha restaurants
indian restaurants..
Query:
select name from ( (SELECT PC_name as name FROM profile_category_table
WHERE PC_status=1 and PC_parentid!=0
and ( regex_replace('[^a-zA-Z0-9\-]','',remove_specialCharacter(PC_name))
LIKE '%rest%' ) GROUP BY PC_name ) UNION (SELECT PROFKEY_name as name
FROM profile_keywords_table WHERE PROFKEY_status=1
and (
regex_replace('[^a-zA-Z0-9\-]','',remove_specialCharacter(PROFKEY_name))
LIKE '%rest%' ) GROUP BY PROFKEY_name )
UNION (SELECT COM_name as name FROM company_profile_table
WHERE COM_status=1 and (
regex_replace('[^a-zA-Z0-9\-]','',remove_specialCharacter(COM_name))
LIKE '%rest%' ) GROUP BY COM_name ) )a
ORDER BY IF(name LIKE '%rest%',1,0) desc
LIMIT 0,25<br><br>
table engine:myisam;
And I add INDEX FOR THAT columns too.. how to optimize my query to execute
fast..
thnks..
Monday, 26 August 2013
rails - are my associations correct?
rails - are my associations correct?
I am beginning my first rails application and I would just like to make
sure that my associations will work like I am hoping. Here is an overview
of the models in my application:
class School < ActiveRecord::Base
has_many :courses
has_many :teachers, :through => :courses
has_many :students, :through => :courses
end
class Course < ActiveRecord::Base
belongs_to :school
belongs_to :teacher
has_and_belongs_to_many :students
end
class Teacher < ActiveRecord::Base
has_many :courses
has_many :students, :through => :courses
end
class Student < ActiveRecord::Base
has_and_belongs_to_many :courses
has_many :teachers, :through => :courses
end
The one thing I have noticed so far is that if I try to get the teachers
or students in a school it will return the same record multiple times. I
am aware I can just call uniq but I would prefer not having to doing that.
So I am wondering if there is a better way I can do this.
I am beginning my first rails application and I would just like to make
sure that my associations will work like I am hoping. Here is an overview
of the models in my application:
class School < ActiveRecord::Base
has_many :courses
has_many :teachers, :through => :courses
has_many :students, :through => :courses
end
class Course < ActiveRecord::Base
belongs_to :school
belongs_to :teacher
has_and_belongs_to_many :students
end
class Teacher < ActiveRecord::Base
has_many :courses
has_many :students, :through => :courses
end
class Student < ActiveRecord::Base
has_and_belongs_to_many :courses
has_many :teachers, :through => :courses
end
The one thing I have noticed so far is that if I try to get the teachers
or students in a school it will return the same record multiple times. I
am aware I can just call uniq but I would prefer not having to doing that.
So I am wondering if there is a better way I can do this.
Make app show view only when opening from notification
Make app show view only when opening from notification
I am making an app, and their is going to be a local notification that
asks you a question. I want it so that if the app is opened from the
notification or maybe within 5 minutes, a certain view is showed that is
not there when launching the app normally. Im using a UITabBar application
if that changes anything.
I am making an app, and their is going to be a local notification that
asks you a question. I want it so that if the app is opened from the
notification or maybe within 5 minutes, a certain view is showed that is
not there when launching the app normally. Im using a UITabBar application
if that changes anything.
Can I add a column with a value calculated from joined table?
Can I add a column with a value calculated from joined table?
I am trying to populate a column on my transactions table using the
difference between a timestamp in the transaction table and a timestamp in
the user table. The idea is to normalize the dates to reflect at what
point of a user experience the transactions happened (i.e. how many days
after a user joined was the transaction processed), as such:
update transactions
set days = ceil(extract(days from T.tdate - U.created_at)) +1
from transactions T join users U on T.user_id=U.id
For some reason, all the rows get the same number (262) in the "days"
field after running the query.
I am trying to populate a column on my transactions table using the
difference between a timestamp in the transaction table and a timestamp in
the user table. The idea is to normalize the dates to reflect at what
point of a user experience the transactions happened (i.e. how many days
after a user joined was the transaction processed), as such:
update transactions
set days = ceil(extract(days from T.tdate - U.created_at)) +1
from transactions T join users U on T.user_id=U.id
For some reason, all the rows get the same number (262) in the "days"
field after running the query.
iOS: why can't you have objects in structs?
iOS: why can't you have objects in structs?
I was wondering why you cannot have objects in structs when using ARC.
Whenever I do, I get the error "ARC forbids objective-c objects in
structs". I saw many answers that discuss solutions, but none discuss the
underlying reason why it doesn't work in the first place.
I was wondering why you cannot have objects in structs when using ARC.
Whenever I do, I get the error "ARC forbids objective-c objects in
structs". I saw many answers that discuss solutions, but none discuss the
underlying reason why it doesn't work in the first place.
MySQL query troubles
MySQL query troubles
I have this query here:
select distinct oawa_id, 'Team Impact' as Club, FirstName, LastName
from team_impacts ti
left join session_participants sp
on (sp.member_id = ti.id)
or (sp.member_id = ti.oawa_id)
order by LastName asc, FirstName asc
and this provides me with a list of users...but some users have the same
first name and last name and some come with an oawa_id and some
dont...exmaple:
Record 1. Brad May has an oawa_id Record 2. Brad May doesnt have an oawa_id
its okay if some people do not have an oawa_id, but for cases like these,
if people have the same name, get the one with the oawa_id and ignore the
one without. Thats only applys for people with the same name.
Any suggestions?
I have this query here:
select distinct oawa_id, 'Team Impact' as Club, FirstName, LastName
from team_impacts ti
left join session_participants sp
on (sp.member_id = ti.id)
or (sp.member_id = ti.oawa_id)
order by LastName asc, FirstName asc
and this provides me with a list of users...but some users have the same
first name and last name and some come with an oawa_id and some
dont...exmaple:
Record 1. Brad May has an oawa_id Record 2. Brad May doesnt have an oawa_id
its okay if some people do not have an oawa_id, but for cases like these,
if people have the same name, get the one with the oawa_id and ignore the
one without. Thats only applys for people with the same name.
Any suggestions?
javascript var scope issue
javascript var scope issue
My this question is to understand the concept of scoping(I guess) and also
to ask about its second solution. I have following javascript code
function one() {
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, i*1000);
}
}
function two() {
one();
}
for (var i = 0; i<3; i++) {
two();
}
I have two functions one and two. I am calling function two inside for
loop which runs 3 times. It means function two executes three times.
Inside two, I am calling one. Inside one, I am again using for loop and
declaring i variable and this loop runs 3 times. Inside this loop, I
setTimeout and inside this I am logging out i. This logs out value 3 all
the time whereas I want it to make like 0, 1, 2. WHY?
Solution
In order to make it work, I simply created third function three and place
all the code inside for loop which is inside one and then called function
three inside this for loop and passed i as argument.
so my function three looks like this
function three (i) {
setTimeout(function() {
console.log(i);
}, i*1000);
}
And function one looks like this
function one() {
for (var i = 0; i < 3; i++) {
three(i);
}
}
Now it shows output of 0, 1, 2. Is there another way to solve it? If yes
then please share below.
My this question is to understand the concept of scoping(I guess) and also
to ask about its second solution. I have following javascript code
function one() {
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i);
}, i*1000);
}
}
function two() {
one();
}
for (var i = 0; i<3; i++) {
two();
}
I have two functions one and two. I am calling function two inside for
loop which runs 3 times. It means function two executes three times.
Inside two, I am calling one. Inside one, I am again using for loop and
declaring i variable and this loop runs 3 times. Inside this loop, I
setTimeout and inside this I am logging out i. This logs out value 3 all
the time whereas I want it to make like 0, 1, 2. WHY?
Solution
In order to make it work, I simply created third function three and place
all the code inside for loop which is inside one and then called function
three inside this for loop and passed i as argument.
so my function three looks like this
function three (i) {
setTimeout(function() {
console.log(i);
}, i*1000);
}
And function one looks like this
function one() {
for (var i = 0; i < 3; i++) {
three(i);
}
}
Now it shows output of 0, 1, 2. Is there another way to solve it? If yes
then please share below.
Error message when importing astropy in Windows 8
Error message when importing astropy in Windows 8
I have Windows 8 (sadly I was lucky enough to but a laptop that support
very badly Linux, tried several distributions..). I have Python 2.7
installed, and also can import scipy and numpy. I've installed astropy
with the executable file from their site, but when I try to import it I
get an error message like this - http://dpaste.com/hold/1356625/
Can anyone help me with setting it up properly?
I have Windows 8 (sadly I was lucky enough to but a laptop that support
very badly Linux, tried several distributions..). I have Python 2.7
installed, and also can import scipy and numpy. I've installed astropy
with the executable file from their site, but when I try to import it I
get an error message like this - http://dpaste.com/hold/1356625/
Can anyone help me with setting it up properly?
iOS: How do I rename a folder in the documents directory
iOS: How do I rename a folder in the documents directory
I'm not sure if this is a silly question. If I move a file using
-[NSFileManger moveItemAtPath:toPath:error:] from one place e.g.
/Images/image.png to say /OtherImages/image.png will the old directory
/Images be deleted automatically or will it still exist? Also, if I wanted
to rename Images to Pictures could this be done in iOS or do I just have
to move everything to a new path/url?
I'm not sure if this is a silly question. If I move a file using
-[NSFileManger moveItemAtPath:toPath:error:] from one place e.g.
/Images/image.png to say /OtherImages/image.png will the old directory
/Images be deleted automatically or will it still exist? Also, if I wanted
to rename Images to Pictures could this be done in iOS or do I just have
to move everything to a new path/url?
can't start android virtual devices after update
can't start android virtual devices after update
I don't have experience with Eclipse, but some time ago, I've followed
some tutorials and I have successfully build 2 android applications. After
6 months of not using Eclipse, when I opened I had to make some updates,
but my virtual devices doesn't start. I get the following message error:
Adb connection Error:An existing connection was forcibly closed by the
remote host
Connection attempts: 1
I've tried the following, but the end results are the same: - deleted and
made new virtual device - reset adb from DDMS - adb kill-server from cmd
I assume that I didn't install the right packages in Android SDK Manager.
I don't have experience with Eclipse, but some time ago, I've followed
some tutorials and I have successfully build 2 android applications. After
6 months of not using Eclipse, when I opened I had to make some updates,
but my virtual devices doesn't start. I get the following message error:
Adb connection Error:An existing connection was forcibly closed by the
remote host
Connection attempts: 1
I've tried the following, but the end results are the same: - deleted and
made new virtual device - reset adb from DDMS - adb kill-server from cmd
I assume that I didn't install the right packages in Android SDK Manager.
Sunday, 25 August 2013
i am applying validate the text with value it may be positive whole number or number with one decimal point
i am applying validate the text with value it may be positive whole number
or number with one decimal point
i am applying validate the text with value it may be positive whole number
or number with one decimal point in javascript 123 1 12345 233.2 1212.2
1.1 are valid number and 1.222 1.33 -89789 -3 are invalid number could you
help me please i have applied this but not get desired result
function CheckOneDecimal(txtbox) {
if (txtbox.value.length > 0)
{
if (isNaN(txtbox.value)) {
txtbox.value = "";
alert("Please enter number with one decimal places");
txtbox.focus();
return;
}
else if (parseFloat(txtbox.value) > 0)
{
txtbox.value = "";
alert("Please enter number with one decimal places.
eg. 8.1");
txtbox.focus();
return;
}
var oRegExp = /^\s*\d+\.\d{1}\s*$/;
if (oRegExp.test(txtbox.value))
{ }
else {
txtbox.value = "";
alert("Please enter number with one decimal
places");
txtbox.focus();
}
}
}
Thanks in advance
or number with one decimal point
i am applying validate the text with value it may be positive whole number
or number with one decimal point in javascript 123 1 12345 233.2 1212.2
1.1 are valid number and 1.222 1.33 -89789 -3 are invalid number could you
help me please i have applied this but not get desired result
function CheckOneDecimal(txtbox) {
if (txtbox.value.length > 0)
{
if (isNaN(txtbox.value)) {
txtbox.value = "";
alert("Please enter number with one decimal places");
txtbox.focus();
return;
}
else if (parseFloat(txtbox.value) > 0)
{
txtbox.value = "";
alert("Please enter number with one decimal places.
eg. 8.1");
txtbox.focus();
return;
}
var oRegExp = /^\s*\d+\.\d{1}\s*$/;
if (oRegExp.test(txtbox.value))
{ }
else {
txtbox.value = "";
alert("Please enter number with one decimal
places");
txtbox.focus();
}
}
}
Thanks in advance
Need source code of Norton Android security application [on hold]
Need source code of Norton Android security application [on hold]
I need source code for an app through which we can lock our android phone
remotely using an sms or a message send from other phone . Which is
exactly like Norton android security app. see the link followed for
reference
http://www.thewwwblog.com/remote-lock-android-phone-sms.html#comment-45413
I need source code for an app through which we can lock our android phone
remotely using an sms or a message send from other phone . Which is
exactly like Norton android security app. see the link followed for
reference
http://www.thewwwblog.com/remote-lock-android-phone-sms.html#comment-45413
Python permutations including substrings
Python permutations including substrings
I've come across this post: How to generate all permutations of a list in
Python
but i require something more, i require all the permutations of a string
as well as all the permutations of all the substrings of that string. I
know its a big number, but is it possible?
I've come across this post: How to generate all permutations of a list in
Python
but i require something more, i require all the permutations of a string
as well as all the permutations of all the substrings of that string. I
know its a big number, but is it possible?
issue on wbadmin systemstatebackup
issue on wbadmin systemstatebackup
I have question is there anyway to backup C drive systemstate only and
save it to the D dirve? When I tried to run the following command:
wbadmin start systemstatebackup -backupTarget:D:
it showed that it will backup the C and D drive at the same time, causing
it can't generate the systemstatebackup file to D drive. (I forgot to dump
actural error message)
So, how can i do it to select C drive to backup the systemstate only and
save it to the D drive?
Please kindly advice!
I have question is there anyway to backup C drive systemstate only and
save it to the D dirve? When I tried to run the following command:
wbadmin start systemstatebackup -backupTarget:D:
it showed that it will backup the C and D drive at the same time, causing
it can't generate the systemstatebackup file to D drive. (I forgot to dump
actural error message)
So, how can i do it to select C drive to backup the systemstate only and
save it to the D drive?
Please kindly advice!
HTML - The above navbar scroll when user scroll and become smaller
HTML - The above navbar scroll when user scroll and become smaller
I want the navbar like this site
Example
The navbar follow the user scroll and become smaller. Thanks in advance.
I want the navbar like this site
Example
The navbar follow the user scroll and become smaller. Thanks in advance.
Saturday, 24 August 2013
Parsing the textbox text to date time
Parsing the textbox text to date time
I am using asp.net 4.0 and using ajax toolkit calander extender to get
values in date filed from the user.
I am trying to parse the value in the datetime filld as follows
DateTime.ParseExact("10/10/2013", "MM/dd/yyyy", null)
Which is not working. I was going throught my code and came to a strange
result
When I put - inplace of \ it started woking.
Can anybody explain why it is like that.
I am using asp.net 4.0 and using ajax toolkit calander extender to get
values in date filed from the user.
I am trying to parse the value in the datetime filld as follows
DateTime.ParseExact("10/10/2013", "MM/dd/yyyy", null)
Which is not working. I was going throught my code and came to a strange
result
When I put - inplace of \ it started woking.
Can anybody explain why it is like that.
Accessing this in anonymous function
Accessing this in anonymous function
I want to create a prototype function that has its own scope. For this, I
use an anonymous function but I cannot find a way to access the members of
the object.
Here is a simplified version of what I am trying to achieve:
function F() {
this.counter = 0;
}
F.prototype.increment = (function() {
var lastIncrementTime = -1;
var caller = this; // <--- it fails here because this is the Window
object
return function(time) {
if (time > lastIncrementTime) {
caller.counter++;
lastIncrementTime = time;
return caller.counter;
}
return caller.counter;
}
})();
f = new F();
f.increment();
I know it fails because this does not refer to F or the f object.
Is there a way to access it?
I want to create a prototype function that has its own scope. For this, I
use an anonymous function but I cannot find a way to access the members of
the object.
Here is a simplified version of what I am trying to achieve:
function F() {
this.counter = 0;
}
F.prototype.increment = (function() {
var lastIncrementTime = -1;
var caller = this; // <--- it fails here because this is the Window
object
return function(time) {
if (time > lastIncrementTime) {
caller.counter++;
lastIncrementTime = time;
return caller.counter;
}
return caller.counter;
}
})();
f = new F();
f.increment();
I know it fails because this does not refer to F or the f object.
Is there a way to access it?
UITapRecognizer: unrecognized selector sent to instance
UITapRecognizer: unrecognized selector sent to instance
I got the following error: unrecognized selector sent to instance and
found a lot of solutions that didn't work for me. I create the the object
from a view class. I tap the imageview and then i got the error
I have the following code:
@implementation MyTappableImage
@synthesize myImageView, myRect, isTapped, myTap;
- (id)initWithRect:(CGRect) myRect2
{
myRect = &myRect2;
UIImage *image = [UIImage imageNamed: @"hert.png"];
myImageView = [[UIImageView alloc]initWithFrame:*myRect];
myImageView.userInteractionEnabled = YES;
[myImageView setImage:image];
isTapped = NO;
myTap = [[UITapGestureRecognizer alloc]initWithTarget:self
action:@selector(tapped:)];
[myImageView addGestureRecognizer:myTap];
return self;
}
-(void)tapped:(UITapGestureRecognizer *)gr {
NSLog(@"druk");
}
I got the following error: unrecognized selector sent to instance and
found a lot of solutions that didn't work for me. I create the the object
from a view class. I tap the imageview and then i got the error
I have the following code:
@implementation MyTappableImage
@synthesize myImageView, myRect, isTapped, myTap;
- (id)initWithRect:(CGRect) myRect2
{
myRect = &myRect2;
UIImage *image = [UIImage imageNamed: @"hert.png"];
myImageView = [[UIImageView alloc]initWithFrame:*myRect];
myImageView.userInteractionEnabled = YES;
[myImageView setImage:image];
isTapped = NO;
myTap = [[UITapGestureRecognizer alloc]initWithTarget:self
action:@selector(tapped:)];
[myImageView addGestureRecognizer:myTap];
return self;
}
-(void)tapped:(UITapGestureRecognizer *)gr {
NSLog(@"druk");
}
sqlite query in oncreate decimal and other value types
sqlite query in oncreate decimal and other value types
as i am making an app that has to connect to an database on a server in
the future i want to make now a database on my android phone that has the
same columns and column names.
in my oncreate i made following
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + databasetabel + "(" +
recordnummer + " BLOB NOT NULL, " +
bezoekrapportnummer + " PRIMARY KEY BLOB AUTO INCREMENT, " +
bezoekrapportdatum + " DATETIME NOT NULL, " +
herstellingsoort + " VARCHAR(1) NOT NULL, " +
totaleduur + " VARCHAR(4) NOT NULL, " +
servicenummer + " BLOB NOT NULL, " +
ONBEKEND + " VARCHAR(2) NOT NULL, " +
klantnaam + " VARCHAR(100) NOT NULL, " +
adres + " VARCHAR(100) NOT NULL, " +
machinenummer + " BLOB NOT NULL, " +
omschrijving + " TEXT NULL, " +
duur + " VARCHAR(4) NOT NULL, " +
postcode + " VARCHAR(8) NOT NULL, " +
gemeente + " VARCHAR(30) NOT NULL, " +
merk + " VARCHAR(20) NOT NULL, " +
model + " VARCHAR(20) NOT NULL, " +
serienummer + " VARCHAR(20) NOT NULL, " +
opmerkingen + " TEXT NULL, " +
werkgereed + " VARCHAR(1) NOT NULL, " +
extratijd + " VARCHAR(4) NOT NULL, " +
urenstand + " BLOB NOT NULL, " +
gecontroleerdbureel + " VARCHAR(1) NOT NULL, " +
onderhoudsfiche + " VARCHAR(30) NOT NULL, " +
uitsplitsen + " VARCHAR(1) NOT NULL, " +
opmerkingbureel + " TEXT NULL, " +
ONBEKEND2 + " BLOB NOT NULL, " +
orderverwerkdatum + " DATETIME NOT NULL, " +
ordernummer + " BLOB NOT NULL, " +
basisservicenummer + " BLOB NOT NULL, " +
verzonden + " VARCHAR(1) NOT NULL );"
);
except for the BLOB statements i have everything declared as in my
database on my server (BLOB were all of the type DECIMAL(5,0) or simular)
anyway, BLOB or DECIMAL or ... all of it is giving following line in my
logcat:
08-24 11:59:04.578: E/SQLiteLog(5918): (1) near "BLOB": syntax error
except for this line there are no more red log lines
as this is the first time i have to work with sqlite i think my query is
wrong how to fix it so i have a table that allows me to put in the same
data as on my server
i found out already on the net that DECIMAL doesn't exists in sqlite that
is why i changed them to BLOB with no effect
thanks in advance
as i am making an app that has to connect to an database on a server in
the future i want to make now a database on my android phone that has the
same columns and column names.
in my oncreate i made following
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + databasetabel + "(" +
recordnummer + " BLOB NOT NULL, " +
bezoekrapportnummer + " PRIMARY KEY BLOB AUTO INCREMENT, " +
bezoekrapportdatum + " DATETIME NOT NULL, " +
herstellingsoort + " VARCHAR(1) NOT NULL, " +
totaleduur + " VARCHAR(4) NOT NULL, " +
servicenummer + " BLOB NOT NULL, " +
ONBEKEND + " VARCHAR(2) NOT NULL, " +
klantnaam + " VARCHAR(100) NOT NULL, " +
adres + " VARCHAR(100) NOT NULL, " +
machinenummer + " BLOB NOT NULL, " +
omschrijving + " TEXT NULL, " +
duur + " VARCHAR(4) NOT NULL, " +
postcode + " VARCHAR(8) NOT NULL, " +
gemeente + " VARCHAR(30) NOT NULL, " +
merk + " VARCHAR(20) NOT NULL, " +
model + " VARCHAR(20) NOT NULL, " +
serienummer + " VARCHAR(20) NOT NULL, " +
opmerkingen + " TEXT NULL, " +
werkgereed + " VARCHAR(1) NOT NULL, " +
extratijd + " VARCHAR(4) NOT NULL, " +
urenstand + " BLOB NOT NULL, " +
gecontroleerdbureel + " VARCHAR(1) NOT NULL, " +
onderhoudsfiche + " VARCHAR(30) NOT NULL, " +
uitsplitsen + " VARCHAR(1) NOT NULL, " +
opmerkingbureel + " TEXT NULL, " +
ONBEKEND2 + " BLOB NOT NULL, " +
orderverwerkdatum + " DATETIME NOT NULL, " +
ordernummer + " BLOB NOT NULL, " +
basisservicenummer + " BLOB NOT NULL, " +
verzonden + " VARCHAR(1) NOT NULL );"
);
except for the BLOB statements i have everything declared as in my
database on my server (BLOB were all of the type DECIMAL(5,0) or simular)
anyway, BLOB or DECIMAL or ... all of it is giving following line in my
logcat:
08-24 11:59:04.578: E/SQLiteLog(5918): (1) near "BLOB": syntax error
except for this line there are no more red log lines
as this is the first time i have to work with sqlite i think my query is
wrong how to fix it so i have a table that allows me to put in the same
data as on my server
i found out already on the net that DECIMAL doesn't exists in sqlite that
is why i changed them to BLOB with no effect
thanks in advance
Updating 300 million records in a collection
Updating 300 million records in a collection
I have collection called TimeSheet having few thousands records now. This
will eventually increase to 300 million records in a year. In this
collection I embed few fields from another collection called Department
which is mostly won't get any updates and only rarely some records will be
updated. By rarely I mean only once or twice in a year and also not all
records, only less than 1% of the records in the collection.
Mostly once a department is created there won't any update, even if there
is an update, it will be done initially (when there are not many related
records in TimeSheet)
Now if someone updates a department after a year, in a worst case scenario
there are chances collection TimeSheet will have about 300 million records
totally and about 5 million matching records for the department which gets
updated. The update query condition will be on a index field.
Since this update is time consuming and creates locks, I'm wondering is
there any better way to do it? One option that I'm thinking is run update
query in batches by adding extra condition like UpdatedDateTime> somedate
&& UpdatedDateTime < somedate.
Other details:
A single document size could be about 3 or 4 KB We have a replica set
containing three replicas.
Is there any other better way to do this? What do you think about this
kind of design? What do you think if there numbers I given are less like
below?
1) 100 million total records and 100,000 matching records for the update
query
2) 10 million total records and 10,000 matching records for the update query
3) 1 million total records and 1000 matching records for the update query
Note: The collection names department and timesheet, and their purpose are
fictional, not the real collections but the statistics that I have given
are true.
I have collection called TimeSheet having few thousands records now. This
will eventually increase to 300 million records in a year. In this
collection I embed few fields from another collection called Department
which is mostly won't get any updates and only rarely some records will be
updated. By rarely I mean only once or twice in a year and also not all
records, only less than 1% of the records in the collection.
Mostly once a department is created there won't any update, even if there
is an update, it will be done initially (when there are not many related
records in TimeSheet)
Now if someone updates a department after a year, in a worst case scenario
there are chances collection TimeSheet will have about 300 million records
totally and about 5 million matching records for the department which gets
updated. The update query condition will be on a index field.
Since this update is time consuming and creates locks, I'm wondering is
there any better way to do it? One option that I'm thinking is run update
query in batches by adding extra condition like UpdatedDateTime> somedate
&& UpdatedDateTime < somedate.
Other details:
A single document size could be about 3 or 4 KB We have a replica set
containing three replicas.
Is there any other better way to do this? What do you think about this
kind of design? What do you think if there numbers I given are less like
below?
1) 100 million total records and 100,000 matching records for the update
query
2) 10 million total records and 10,000 matching records for the update query
3) 1 million total records and 1000 matching records for the update query
Note: The collection names department and timesheet, and their purpose are
fictional, not the real collections but the statistics that I have given
are true.
Ophcrack: how to back up from drive C(sda2) to drive D(sda3) of a windows 7 machine not booting?
Ophcrack: how to back up from drive C(sda2) to drive D(sda3) of a windows
7 machine not booting?
My laptop cant boot. So im about to reformat it, I backed up my documents
using live CD Ophcrack, to drive D (sda3). At first I can copy paste my
files. But not until im about done, at 75% a weird dialog box appears with
a title "error" but a content "success". Really weird, and after that, I
can then no longer see the contents of my sda3, and also the partially
copied files there.
I'm new to linux or isolinux, so what would you suggest?
1.) maybe I can do some terminal command to enable writing permission in
sda3?, how about its content that's not visible anymore? or is my drive
D(sda3) gone already? hence, I just want to backup a folder I placed in my
desktop (which is surely in C), so I should paste it to drive D(sda3)
before I format Drive C.
2.) or the lesser convenient way to address this is that I need to get
some hardware to connect my laptop hdd to a desktop and do the backup etc,
as what I have researched.
3.) or maybe there's another software that might do the job better?
P.S: the preferred option is #1. But how? what command?
7 machine not booting?
My laptop cant boot. So im about to reformat it, I backed up my documents
using live CD Ophcrack, to drive D (sda3). At first I can copy paste my
files. But not until im about done, at 75% a weird dialog box appears with
a title "error" but a content "success". Really weird, and after that, I
can then no longer see the contents of my sda3, and also the partially
copied files there.
I'm new to linux or isolinux, so what would you suggest?
1.) maybe I can do some terminal command to enable writing permission in
sda3?, how about its content that's not visible anymore? or is my drive
D(sda3) gone already? hence, I just want to backup a folder I placed in my
desktop (which is surely in C), so I should paste it to drive D(sda3)
before I format Drive C.
2.) or the lesser convenient way to address this is that I need to get
some hardware to connect my laptop hdd to a desktop and do the backup etc,
as what I have researched.
3.) or maybe there's another software that might do the job better?
P.S: the preferred option is #1. But how? what command?
Friday, 23 August 2013
how to get android_id in JNI
how to get android_id in JNI
void init_androidId(JNIEnv * env, jobject activity){
jclass clsontentResolver = env->GetObjectClass(activity);
if (clsontentResolver==NULL)
{
LOG`E`("resolver is null");
}
jmethodID mid_getContentResolver
=env->GetMethodID(clsontentResolver,"getContentResolver","()Landroid/content/ContentResolver;");
if (mid_getContentResolver==NULL)
{
LOGE("mid_getContentResolver is null");
}
jobject contentObj = env->CallObjectMethod(activity,
mid_getContentResolver);
if (contentObj==NULL)
{
LOGE("contentObj is null");
}
jclass secClass=env->FindClass("android/provider/Settings$Secure");
if (secClass==NULL)
{
LOGE("secClass is null");
}
jmethodID
secMid=env->GetMethodID(secClass,"getString","(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;");
if (secMid==NULL)
{
LOGE("secMid is null");
return;
}
jstring jandroid_id= (jstring)
env->CallStaticObjectMethod(secClass,secMid,contentObj,"android_id");
if (jandroid_id==NULL)
{
LOGE("jandroid_id is null");
}
const char *id=env->GetStringUTFChars(jandroid_id, 0);
LOGE("id %s ",id);
// jstring jstring=
(jstring)env->CallStaticObjectMethod(secClass,secMid);}
}
I try get android_id from NDK, but i found secMid'value is NULL jmethodID
secMid=env->GetMethodID(secClass,"getString","(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;");
what's problem? thanks
void init_androidId(JNIEnv * env, jobject activity){
jclass clsontentResolver = env->GetObjectClass(activity);
if (clsontentResolver==NULL)
{
LOG`E`("resolver is null");
}
jmethodID mid_getContentResolver
=env->GetMethodID(clsontentResolver,"getContentResolver","()Landroid/content/ContentResolver;");
if (mid_getContentResolver==NULL)
{
LOGE("mid_getContentResolver is null");
}
jobject contentObj = env->CallObjectMethod(activity,
mid_getContentResolver);
if (contentObj==NULL)
{
LOGE("contentObj is null");
}
jclass secClass=env->FindClass("android/provider/Settings$Secure");
if (secClass==NULL)
{
LOGE("secClass is null");
}
jmethodID
secMid=env->GetMethodID(secClass,"getString","(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;");
if (secMid==NULL)
{
LOGE("secMid is null");
return;
}
jstring jandroid_id= (jstring)
env->CallStaticObjectMethod(secClass,secMid,contentObj,"android_id");
if (jandroid_id==NULL)
{
LOGE("jandroid_id is null");
}
const char *id=env->GetStringUTFChars(jandroid_id, 0);
LOGE("id %s ",id);
// jstring jstring=
(jstring)env->CallStaticObjectMethod(secClass,secMid);}
}
I try get android_id from NDK, but i found secMid'value is NULL jmethodID
secMid=env->GetMethodID(secClass,"getString","(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;");
what's problem? thanks
Write excel file in C# 2.0 without using any third party dlls/interop/sdk
Write excel file in C# 2.0 without using any third party dlls/interop/sdk
I want to write a excel file (xls/xlsx) in C#.
Constraints:
I don't want to use following things while writing:
1. Third Party dll( My client is not allowing me to use third party dll )
2. SDK(Same as above reason as am not allowed to download)
3. Not allowed to use interop as in target server there is no office
installed.
4. OpenXml
Info:
1. Using VS 2005.
2. Using ASP.Net (C# 2.0)
Please suggest me how can I proceed.
I want to write a excel file (xls/xlsx) in C#.
Constraints:
I don't want to use following things while writing:
1. Third Party dll( My client is not allowing me to use third party dll )
2. SDK(Same as above reason as am not allowed to download)
3. Not allowed to use interop as in target server there is no office
installed.
4. OpenXml
Info:
1. Using VS 2005.
2. Using ASP.Net (C# 2.0)
Please suggest me how can I proceed.
M-matrix check in Matlab/Octave?
M-matrix check in Matlab/Octave?
Is there a simple way to check that matrix is M-matrix in Octave/Matlab?
Thanks, Vojta
Is there a simple way to check that matrix is M-matrix in Octave/Matlab?
Thanks, Vojta
Random selection of a percent of entries from a table
Random selection of a percent of entries from a table
I'm try to get a random selection of 30% of tickets in a bin. The below
code works for the 30%, but when I add "ORDER BY RND(INT(NOW*ID)-NOW*ID)"
to the end, I get an error.
Works:
$result1 = "SELECT MainBin.Assignee, Count(MainBin.IncidentNumber) * .3 AS
CountOfIncidentNumber FROM MainBin GROUP BY MainBin.Assignee";
$rs1=odbc_exec($conn,$result1);
while($row = odbc_fetch_array($rs1))
{
$Assignee = "". $row['Assignee'];
$CountOfIncidentNumber = ceil($row["CountOfIncidentNumber"]);
$result2 = "INSERT INTO TicketBin (IncidentNumber)
SELECT TOP $CountOfIncidentNumber IncidentNumber FROM MainBin
WHERE Assignee = '$Assignee'";
$rs2=odbc_exec($conn,$result2);
}
Does Not Work:
$result1 = "SELECT MainBin.Assignee, Count(MainBin.IncidentNumber) * .3
AS CountOfIncidentNumber FROM MainBin GROUP BY MainBin.Assignee ORDER BY
RND(INT(NOW*ID)-NOW*ID)";
$rs1=odbc_exec($conn,$result1);
I have and AutoNumber field named ID and I've used this before, just not
with the grouping. Any help is appreciated!
I'm try to get a random selection of 30% of tickets in a bin. The below
code works for the 30%, but when I add "ORDER BY RND(INT(NOW*ID)-NOW*ID)"
to the end, I get an error.
Works:
$result1 = "SELECT MainBin.Assignee, Count(MainBin.IncidentNumber) * .3 AS
CountOfIncidentNumber FROM MainBin GROUP BY MainBin.Assignee";
$rs1=odbc_exec($conn,$result1);
while($row = odbc_fetch_array($rs1))
{
$Assignee = "". $row['Assignee'];
$CountOfIncidentNumber = ceil($row["CountOfIncidentNumber"]);
$result2 = "INSERT INTO TicketBin (IncidentNumber)
SELECT TOP $CountOfIncidentNumber IncidentNumber FROM MainBin
WHERE Assignee = '$Assignee'";
$rs2=odbc_exec($conn,$result2);
}
Does Not Work:
$result1 = "SELECT MainBin.Assignee, Count(MainBin.IncidentNumber) * .3
AS CountOfIncidentNumber FROM MainBin GROUP BY MainBin.Assignee ORDER BY
RND(INT(NOW*ID)-NOW*ID)";
$rs1=odbc_exec($conn,$result1);
I have and AutoNumber field named ID and I've used this before, just not
with the grouping. Any help is appreciated!
adding url parameters to grails form
adding url parameters to grails form
I have a form and want to add customer URL parameters , for example in the
classical "create"
http://localhost:8080/test/customer/create?abc=asd
I changed the form from POST to GET, both in the view file method="GET"
and in the controller, remove the allowedMethods
Still the custom parameter "abc" is not inserted from the view to the
action, it does not appear in the params - params.abc is null
the show action works
http://localhost:8080/grails/copyOfLead/show/3?abc=asd
works....
I have a form and want to add customer URL parameters , for example in the
classical "create"
http://localhost:8080/test/customer/create?abc=asd
I changed the form from POST to GET, both in the view file method="GET"
and in the controller, remove the allowedMethods
Still the custom parameter "abc" is not inserted from the view to the
action, it does not appear in the params - params.abc is null
the show action works
http://localhost:8080/grails/copyOfLead/show/3?abc=asd
works....
show checkout process of another site on my site
show checkout process of another site on my site
I've been having this problem that I want users on my site to be able to
do a complete checkout of another site with whom we will have legal
contracts of course. Iframe is not an option as that will show their
complete pages and we don't want that. We want a stripped down version of
their site which just has their logo and say the shopping cart and then
just the payment form and so on.
I have tried creating a proxy site to try to capture and redirect
requests, but was having problems in cookie management. What is the best
approach to do this? I just need a direction to get started.
The shops are emphasizing that their look and feel should be used.
I've been having this problem that I want users on my site to be able to
do a complete checkout of another site with whom we will have legal
contracts of course. Iframe is not an option as that will show their
complete pages and we don't want that. We want a stripped down version of
their site which just has their logo and say the shopping cart and then
just the payment form and so on.
I have tried creating a proxy site to try to capture and redirect
requests, but was having problems in cookie management. What is the best
approach to do this? I just need a direction to get started.
The shops are emphasizing that their look and feel should be used.
Thursday, 22 August 2013
Incorporating external function in R's apply
Incorporating external function in R's apply
Given this data.frame
x y z
1 1 3 5
2 2 4 6
I'd like to add the value of columns x and z plus a coefficient 10, for
every rows in dat. The intended result is this
x y z result
1 1 3 5 16 #(1+5+10)
2 2 4 6 18 #(2+6+10)
But why this code doesn't produce the desired result?
dat <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
Coeff <- 10
# Function
process.xz <- function(v1,v2,cf) {
return(v1+v2+cf)
}
# It breaks here
sm <- apply(dat[,c('x','z')], 1, process.xz(dat$x,dat$y,Coeff ))
# Later I'd do this:
# cbind(dat,sm);
Given this data.frame
x y z
1 1 3 5
2 2 4 6
I'd like to add the value of columns x and z plus a coefficient 10, for
every rows in dat. The intended result is this
x y z result
1 1 3 5 16 #(1+5+10)
2 2 4 6 18 #(2+6+10)
But why this code doesn't produce the desired result?
dat <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
Coeff <- 10
# Function
process.xz <- function(v1,v2,cf) {
return(v1+v2+cf)
}
# It breaks here
sm <- apply(dat[,c('x','z')], 1, process.xz(dat$x,dat$y,Coeff ))
# Later I'd do this:
# cbind(dat,sm);
Why am I getting blips when encoding a sound file using Java JNA?
Why am I getting blips when encoding a sound file using Java JNA?
I have implemented a hello world libavcodec using JNA to generate a pure
sine wave. But when I actually run the program, it is mostly 440Hz but
also contains annoying clicks and blips. How am I calling
avcodec_encode_audio2 wrong?
Here is my Java code. All the sources are also at github in case you want
to try to compile it.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.Objects;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
public class Sin {
/**
* Abstract class that allows you to put the initialization and cleanup
* code at the same place instead of separated by the big try block.
*/
public static abstract class SharedPtr<T> implements AutoCloseable {
public T ptr;
public SharedPtr(T ptr) {
this.ptr = ptr;
}
/**
* Abstract override forces method to throw no checked exceptions.
* Subclasses will call a C function that throws no exceptions.
*/
@Override public abstract void close();
}
/**
* @param args
* @throws IOException
* @throws LineUnavailableException
*/
public static void main(String[] args) throws IOException,
LineUnavailableException {
final AvcodecLibrary avcodec = AvcodecLibrary.INSTANCE;
final AvformatLibrary avformat = AvformatLibrary.INSTANCE;
final AvutilLibrary avutil = AvutilLibrary.INSTANCE;
avcodec.avcodec_register_all();
avformat.av_register_all();
AVOutputFormat.ByReference format = null;
String format_name = "wav", file_url = "file:sinjava.wav";
for (AVOutputFormat.ByReference formatIter =
avformat.av_oformat_next(null); formatIter != null; formatIter =
avformat.av_oformat_next(formatIter)) {
formatIter.setAutoWrite(false);
String iterName = formatIter.name;
if (format_name.equals(iterName)) {
format = formatIter;
break;
}
}
Objects.requireNonNull(format);
System.out.format("Found format %s%n", format_name);
AVCodec codec = avcodec.avcodec_find_encoder(format.audio_codec);
Objects.requireNonNull(codec);
codec.setAutoWrite(false);
try (
SharedPtr<AVFormatContext> fmtCtxPtr = new
SharedPtr<AVFormatContext>(avformat.avformat_alloc_context())
{@Override public void close(){if (null!=ptr)
avformat.avformat_free_context(ptr);}};
) {
AVFormatContext fmtCtx = Objects.requireNonNull(fmtCtxPtr.ptr);
fmtCtx.setAutoWrite(false);
fmtCtx.setAutoRead(false);
fmtCtx.oformat = format; fmtCtx.writeField("oformat");
AVStream st = avformat.avformat_new_stream(fmtCtx, codec);
if (null == st)
throw new IllegalStateException();
AVCodecContext c = st.codec;
if (null == c)
throw new IllegalStateException();
st.setAutoWrite(false);
fmtCtx.readField("nb_streams");
st.id = fmtCtx.nb_streams - 1; st.writeField("id");
assert st.id >= 0;
System.out.format("New stream: id=%d%n", st.id);
if (0 != (format.flags & AvformatLibrary.AVFMT_GLOBALHEADER)) {
c.flags |= AvcodecLibrary.CODEC_FLAG_GLOBAL_HEADER;
}
c.writeField("flags");
c.bit_rate = 64000; c.writeField("bit_rate");
int bestSampleRate;
if (null == codec.supported_samplerates) {
bestSampleRate = 44100;
} else {
bestSampleRate = 0;
for (int offset = 0, sample_rate =
codec.supported_samplerates.getInt(offset); sample_rate !=
0; codec.supported_samplerates.getInt(++offset)) {
bestSampleRate = Math.max(bestSampleRate, sample_rate);
}
assert bestSampleRate > 0;
}
c.sample_rate = bestSampleRate; c.writeField("sample_rate");
c.channel_layout = AvutilLibrary.AV_CH_LAYOUT_STEREO;
c.writeField("channel_layout");
c.channels =
avutil.av_get_channel_layout_nb_channels(c.channel_layout);
c.writeField("channels");
assert 2 == c.channels;
c.sample_fmt = AvutilLibrary.AVSampleFormat.AV_SAMPLE_FMT_S16;
c.writeField("sample_fmt");
c.time_base.num = 1;
c.time_base.den = bestSampleRate;
c.writeField("time_base");
c.setAutoWrite(false);
AudioFormat javaSoundFormat = new AudioFormat(bestSampleRate,
Short.SIZE, c.channels, true, ByteOrder.nativeOrder() ==
ByteOrder.BIG_ENDIAN);
DataLine.Info javaDataLineInfo = new
DataLine.Info(TargetDataLine.class, javaSoundFormat);
if (! AudioSystem.isLineSupported(javaDataLineInfo))
throw new IllegalStateException();
int err;
if ((err = avcodec.avcodec_open(c, codec)) < 0) {
throw new IllegalStateException();
}
try (
SharedPtr<AVCodecContext> encCtxPtr = new
SharedPtr<AVCodecContext>(c) {@Override public void
close() {}}
) {
assert c.channels != 0;
AVIOContext.ByReference[] ioCtxReference = new
AVIOContext.ByReference[1];
if (0 != (err = avformat.avio_open(ioCtxReference,
file_url, AvformatLibrary.AVIO_FLAG_WRITE))) {
throw new IllegalStateException("averror " + err);
}
try (
SharedPtr<AVIOContext.ByReference> ioCtxPtr = new
SharedPtr<AVIOContext.ByReference>(ioCtxReference[0])
{@Override public void close(){if (null!=ptr)
avutil.av_free(ptr.getPointer());}}
) {
AVIOContext.ByReference ioCtx =
Objects.requireNonNull(ioCtxPtr.ptr);
fmtCtx.pb = ioCtx; fmtCtx.writeField("pb");
int averr = avformat.avformat_write_header(fmtCtx, null);
if (averr < 0) {
throw new IllegalStateException("" + averr);
}
st.read(); // it is modified by avformat_write_header
System.out.format("Wrote header.
fmtCtx->nb_streams=%d, st->time_base=%d/%d;
st->avg_frame_rate=%d/%d%n", fmtCtx.nb_streams,
st.time_base.num, st.time_base.den,
st.avg_frame_rate.num, st.avg_frame_rate.den);
avformat.avio_flush(ioCtx);
int frame_size = c.frame_size != 0 ? c.frame_size : 4096;
int expectedBufferSize = frame_size * c.channels *
(Short.SIZE/8);
boolean supports_small_last_frame = c.frame_size == 0
? true : 0 != (codec.capabilities &
AvcodecLibrary.CODEC_CAP_SMALL_LAST_FRAME);
int bufferSize =
avutil.av_samples_get_buffer_size((IntBuffer)null,
c.channels, frame_size, c.sample_fmt, 1);
assert bufferSize == expectedBufferSize:
String.format("expected %d; got %d",
expectedBufferSize, bufferSize);
ByteBuffer samples =
ByteBuffer.allocate(expectedBufferSize);
samples.order(ByteOrder.nativeOrder());
int audio_time = 0; // unit: (c.time_base) s =
(1/c.sample_rate) s
int audio_sample_count = supports_small_last_frame ?
3 * c.sample_rate :
3 * c.sample_rate / frame_size * frame_size;
while (audio_time < audio_sample_count) {
int frame_audio_time = audio_time;
samples.clear();
int nb_samples_in_frame = 0;
// encode a single tone sound
for (; samples.hasRemaining() && audio_time <
audio_sample_count; nb_samples_in_frame++,
audio_time++) {
double x = 2*Math.PI*440/c.sample_rate *
audio_time;
double y = 10000 * Math.sin(x);
samples.putShort((short) y);
samples.putShort((short) y);
}
samples.flip();
try (
SharedPtr<AVFrame> framePtr = new
SharedPtr<AVFrame>(avcodec.avcodec_alloc_frame())
{@Override public void close() {if
(null!=ptr)
avutil.av_free(ptr.getPointer());}};
) {
AVFrame frame =
Objects.requireNonNull(framePtr.ptr);
frame.setAutoRead(false); // will be an in param
frame.setAutoWrite(false);
frame.nb_samples = nb_samples_in_frame;
frame.writeField("nb_samples"); // actually
unused during encoding
// Presentation time, in AVStream.time_base
units.
frame.pts =
avutil.av_rescale_q(frame_audio_time,
c.time_base, st.time_base); // i *
codec_time_base / st_time_base
frame.writeField("pts");
assert c.channels > 0;
int bytesPerSample =
avutil.av_get_bytes_per_sample(c.sample_fmt);
assert bytesPerSample > 0;
if (0 != (err =
avcodec.avcodec_fill_audio_frame(frame,
c.channels, c.sample_fmt, samples,
samples.capacity(), 1))) {
throw new IllegalStateException(""+err);
}
AVPacket packet = new AVPacket(); // one of
the few structs from ffmpeg with guaranteed
size
avcodec.av_init_packet(packet);
packet.size = 0;
packet.data = null;
packet.stream_index = st.index;
packet.writeField("stream_index");
// encode the samples
IntBuffer gotPacket = IntBuffer.allocate(1);
if (0 != (err =
avcodec.avcodec_encode_audio2(c, packet,
frame, gotPacket))) {
throw new IllegalStateException("" + err);
} else if (0 != gotPacket.get()) {
packet.read();
averr = avformat.av_write_frame(fmtCtx,
packet);
if (averr < 0)
throw new IllegalStateException("" +
averr);
}
System.out.format("encoded frame: codec time =
%d; pts=%d = av_rescale_q(%d,%d/%d,%d/%d)
(%.02fs) contains %d samples (%.02fs);
got_packet=%d; packet.size=%d%n",
frame_audio_time,
frame.pts,
frame_audio_time,
st.codec.time_base.num,st.codec.time_base.den,st.time_base.num,st.time_base.den,
1.*frame_audio_time/c.sample_rate,
frame.nb_samples,
1.*frame.nb_samples/c.sample_rate,
gotPacket.array()[0], packet.size);
}
}
if (0 != (err = avformat.av_write_trailer(fmtCtx))) {
throw new IllegalStateException();
}
avformat.avio_flush(ioCtx);
}
}
}
System.out.println("Done writing");
}
}
I also rewrote it in C, and the C version works fine without any blips.
But I can't figure out how I am using the library differently; all the
library function calls should be identical!
//! gcc --std=c99 sin.c $(pkg-config --cflags --libs libavutil libavformat
libavcodec) -o sin
// sudo apt-get install libswscale-dev
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <libavutil/opt.h>
#include <libavutil/mathematics.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavcodec/avcodec.h>
int main(int argc, char *argv[]) {
const char *format_name = "wav", *file_url = "file:sin.wav";
avcodec_register_all();
av_register_all();
AVOutputFormat *format = NULL;
for (AVOutputFormat *formatIter = av_oformat_next(NULL); formatIter !=
NULL; formatIter = av_oformat_next(formatIter)) {
int hasEncoder = NULL != avcodec_find_encoder(formatIter->audio_codec);
if (0 == strcmp(format_name, formatIter->name)) {
format = formatIter;
break;
}
}
printf("Found format %s\n", format->name);
AVCodec *codec = avcodec_find_encoder(format->audio_codec);
if (! codec) {
fprintf(stderr, "Could not find codec %d\n", format->audio_codec);
exit(1);
}
AVFormatContext *fmtCtx = avformat_alloc_context();
if (! fmtCtx) {
fprintf(stderr, "error allocating AVFormatContext\n");
exit(1);
}
fmtCtx->oformat = format;
AVStream *st = avformat_new_stream(fmtCtx, codec);
if (! st) {
fprintf(stderr, "error allocating AVStream\n");
exit(1);
}
if (fmtCtx->nb_streams != 1) {
fprintf(stderr, "avformat_new_stream should have incremented
nb_streams, but it's still %d\n", fmtCtx->nb_streams);
exit(1);
}
AVCodecContext *c = st->codec;
if (! c) {
fprintf(stderr, "avformat_new_stream should have allocated a
AVCodecContext for my stream\n");
exit(1);
}
st->id = fmtCtx->nb_streams - 1;
printf("Created stream %d\n", st->id);
if (0 != (format->flags & AVFMT_GLOBALHEADER)) {
c->flags |= CODEC_FLAG_GLOBAL_HEADER;
}
c->bit_rate = 64000;
int bestSampleRate;
if (NULL == codec->supported_samplerates) {
bestSampleRate = 44100;
printf("Setting sample rate: %d\n", bestSampleRate);
} else {
bestSampleRate = 0;
for (const int *sample_rate_iter = codec->supported_samplerates;
*sample_rate_iter != 0; sample_rate_iter++) {
if (*sample_rate_iter >= bestSampleRate)
bestSampleRate = *sample_rate_iter;
}
printf("Using best supported sample rate: %d\n", bestSampleRate);
}
c->sample_rate = bestSampleRate;
c->channel_layout = AV_CH_LAYOUT_STEREO;
c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
c->time_base.num = 1;
c->time_base.den = c->sample_rate;
if (c->channels != 2) {
fprintf(stderr, "av_get_channel_layout_nb_channels returned %d instead
of 2\n", c->channels);
exit(1);
}
c->sample_fmt = AV_SAMPLE_FMT_S16;
int averr;
if ((averr = avcodec_open2(c, codec, NULL)) < 0) {
fprintf(stderr, "avcodec_open2 returned error %d\n", averr);
exit(1);
}
AVIOContext *ioCtx = NULL;
if (0 != (averr = avio_open(&ioCtx, file_url, AVIO_FLAG_WRITE))) {
fprintf(stderr, "avio_open returned error %d\n", averr);
exit(1);
}
if (ioCtx == NULL) {
fprintf(stderr, "AVIOContext should have been set by avio_open\n");
exit(1);
}
fmtCtx->pb = ioCtx;
if (0 != (averr = avformat_write_header(fmtCtx, NULL))) {
fprintf(stderr, "avformat_write_header returned error %d\n", averr);
exit(1);
}
printf("Wrote header. fmtCtx->nb_streams=%d, st->time_base=%d/%d;
st->avg_frame_rate=%d/%d\n", fmtCtx->nb_streams, st->time_base.num,
st->time_base.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
int align = 1;
int sample_size = av_get_bytes_per_sample(c->sample_fmt);
if (sample_size != sizeof(int16_t)) {
fprintf(stderr, "expected sample size=%zu but got %d\n",
sizeof(int16_t), sample_size);
exit(1);
}
int frame_size = c->frame_size != 0 ? c->frame_size : 4096;
int bufferSize = av_samples_get_buffer_size(NULL, c->channels,
frame_size, c->sample_fmt, align);
int expectedBufferSize = frame_size * c->channels * sample_size;
int supports_small_last_frame = c->frame_size == 0 ? 1 : 0 !=
(codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME);
if (bufferSize != expectedBufferSize) {
fprintf(stderr, "expected buffer size=%d but got %d\n",
expectedBufferSize, bufferSize);
exit(1);
}
int16_t *samples = (int16_t*)malloc(bufferSize);
uint32_t audio_time = 0; // unit: (1/c->sample_rate) s
uint32_t audio_sample_count = supports_small_last_frame ?
3 * c->sample_rate :
3 * c->sample_rate / frame_size * frame_size;
while (audio_time < audio_sample_count) {
uint32_t frame_audio_time = audio_time; // unit: (1/c->sample_rate) s
AVFrame *frame = avcodec_alloc_frame();
if (frame == NULL) {
fprintf(stderr, "avcodec_alloc_frame failed\n");
exit(1);
}
for (uint32_t i = 0; i != frame_size && audio_time <
audio_sample_count; i++, audio_time++) {
samples[2*i] = samples[2*i + 1] = 10000 *
sin(2*M_PI*440/c->sample_rate * audio_time);
frame->nb_samples = i+1; // actually unused during encoding
}
// frame->format = c->sample_fmt; // unused during encoding
frame->pts = av_rescale_q(frame_audio_time, c->time_base, st->time_base);
if (0 != (averr = avcodec_fill_audio_frame(frame, c->channels,
c->sample_fmt, (const uint8_t*)samples, bufferSize, align))) {
fprintf(stderr, "avcodec_fill_audio_frame returned error %d\n", averr);
exit(1);
}
AVPacket packet;
av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;
int got_packet;
if (0 != (averr = avcodec_encode_audio2(c, &packet, frame,
&got_packet))) {
fprintf(stderr, "avcodec_encode_audio2 returned error %d\n", averr);
exit(1);
}
if (got_packet) {
packet.stream_index = st->index;
if (0 < (averr = av_write_frame(fmtCtx, &packet))) {
fprintf(stderr, "av_write_frame returned error %d\n", averr);
exit(1);
} else if (averr == 1) {
// end of stream wanted.
}
}
printf("encoded frame: codec time = %u; format pts=%ld =
av_rescale_q(%u,%d/%d,%d/%d) (%.02fs) contains %d samples (%.02fs);
got_packet=%d; packet.size=%d\n",
frame_audio_time,
frame->pts,
frame_audio_time, c->time_base.num, c->time_base.den,
st->time_base.num, st->time_base.den,
1.*frame_audio_time/c->sample_rate, frame->nb_samples,
1.*frame->nb_samples/c->sample_rate, got_packet, packet.size);
av_free(frame);
}
free(samples);
cleanupFile:
if (0 != (averr = av_write_trailer(fmtCtx))) {
fprintf(stderr, "av_write_trailer returned error %d\n", averr);
exit(1);
}
avio_flush(ioCtx);
avio_close(ioCtx);
avformat_free_context(fmtCtx);
}
I have implemented a hello world libavcodec using JNA to generate a pure
sine wave. But when I actually run the program, it is mostly 440Hz but
also contains annoying clicks and blips. How am I calling
avcodec_encode_audio2 wrong?
Here is my Java code. All the sources are also at github in case you want
to try to compile it.
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.Objects;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
public class Sin {
/**
* Abstract class that allows you to put the initialization and cleanup
* code at the same place instead of separated by the big try block.
*/
public static abstract class SharedPtr<T> implements AutoCloseable {
public T ptr;
public SharedPtr(T ptr) {
this.ptr = ptr;
}
/**
* Abstract override forces method to throw no checked exceptions.
* Subclasses will call a C function that throws no exceptions.
*/
@Override public abstract void close();
}
/**
* @param args
* @throws IOException
* @throws LineUnavailableException
*/
public static void main(String[] args) throws IOException,
LineUnavailableException {
final AvcodecLibrary avcodec = AvcodecLibrary.INSTANCE;
final AvformatLibrary avformat = AvformatLibrary.INSTANCE;
final AvutilLibrary avutil = AvutilLibrary.INSTANCE;
avcodec.avcodec_register_all();
avformat.av_register_all();
AVOutputFormat.ByReference format = null;
String format_name = "wav", file_url = "file:sinjava.wav";
for (AVOutputFormat.ByReference formatIter =
avformat.av_oformat_next(null); formatIter != null; formatIter =
avformat.av_oformat_next(formatIter)) {
formatIter.setAutoWrite(false);
String iterName = formatIter.name;
if (format_name.equals(iterName)) {
format = formatIter;
break;
}
}
Objects.requireNonNull(format);
System.out.format("Found format %s%n", format_name);
AVCodec codec = avcodec.avcodec_find_encoder(format.audio_codec);
Objects.requireNonNull(codec);
codec.setAutoWrite(false);
try (
SharedPtr<AVFormatContext> fmtCtxPtr = new
SharedPtr<AVFormatContext>(avformat.avformat_alloc_context())
{@Override public void close(){if (null!=ptr)
avformat.avformat_free_context(ptr);}};
) {
AVFormatContext fmtCtx = Objects.requireNonNull(fmtCtxPtr.ptr);
fmtCtx.setAutoWrite(false);
fmtCtx.setAutoRead(false);
fmtCtx.oformat = format; fmtCtx.writeField("oformat");
AVStream st = avformat.avformat_new_stream(fmtCtx, codec);
if (null == st)
throw new IllegalStateException();
AVCodecContext c = st.codec;
if (null == c)
throw new IllegalStateException();
st.setAutoWrite(false);
fmtCtx.readField("nb_streams");
st.id = fmtCtx.nb_streams - 1; st.writeField("id");
assert st.id >= 0;
System.out.format("New stream: id=%d%n", st.id);
if (0 != (format.flags & AvformatLibrary.AVFMT_GLOBALHEADER)) {
c.flags |= AvcodecLibrary.CODEC_FLAG_GLOBAL_HEADER;
}
c.writeField("flags");
c.bit_rate = 64000; c.writeField("bit_rate");
int bestSampleRate;
if (null == codec.supported_samplerates) {
bestSampleRate = 44100;
} else {
bestSampleRate = 0;
for (int offset = 0, sample_rate =
codec.supported_samplerates.getInt(offset); sample_rate !=
0; codec.supported_samplerates.getInt(++offset)) {
bestSampleRate = Math.max(bestSampleRate, sample_rate);
}
assert bestSampleRate > 0;
}
c.sample_rate = bestSampleRate; c.writeField("sample_rate");
c.channel_layout = AvutilLibrary.AV_CH_LAYOUT_STEREO;
c.writeField("channel_layout");
c.channels =
avutil.av_get_channel_layout_nb_channels(c.channel_layout);
c.writeField("channels");
assert 2 == c.channels;
c.sample_fmt = AvutilLibrary.AVSampleFormat.AV_SAMPLE_FMT_S16;
c.writeField("sample_fmt");
c.time_base.num = 1;
c.time_base.den = bestSampleRate;
c.writeField("time_base");
c.setAutoWrite(false);
AudioFormat javaSoundFormat = new AudioFormat(bestSampleRate,
Short.SIZE, c.channels, true, ByteOrder.nativeOrder() ==
ByteOrder.BIG_ENDIAN);
DataLine.Info javaDataLineInfo = new
DataLine.Info(TargetDataLine.class, javaSoundFormat);
if (! AudioSystem.isLineSupported(javaDataLineInfo))
throw new IllegalStateException();
int err;
if ((err = avcodec.avcodec_open(c, codec)) < 0) {
throw new IllegalStateException();
}
try (
SharedPtr<AVCodecContext> encCtxPtr = new
SharedPtr<AVCodecContext>(c) {@Override public void
close() {}}
) {
assert c.channels != 0;
AVIOContext.ByReference[] ioCtxReference = new
AVIOContext.ByReference[1];
if (0 != (err = avformat.avio_open(ioCtxReference,
file_url, AvformatLibrary.AVIO_FLAG_WRITE))) {
throw new IllegalStateException("averror " + err);
}
try (
SharedPtr<AVIOContext.ByReference> ioCtxPtr = new
SharedPtr<AVIOContext.ByReference>(ioCtxReference[0])
{@Override public void close(){if (null!=ptr)
avutil.av_free(ptr.getPointer());}}
) {
AVIOContext.ByReference ioCtx =
Objects.requireNonNull(ioCtxPtr.ptr);
fmtCtx.pb = ioCtx; fmtCtx.writeField("pb");
int averr = avformat.avformat_write_header(fmtCtx, null);
if (averr < 0) {
throw new IllegalStateException("" + averr);
}
st.read(); // it is modified by avformat_write_header
System.out.format("Wrote header.
fmtCtx->nb_streams=%d, st->time_base=%d/%d;
st->avg_frame_rate=%d/%d%n", fmtCtx.nb_streams,
st.time_base.num, st.time_base.den,
st.avg_frame_rate.num, st.avg_frame_rate.den);
avformat.avio_flush(ioCtx);
int frame_size = c.frame_size != 0 ? c.frame_size : 4096;
int expectedBufferSize = frame_size * c.channels *
(Short.SIZE/8);
boolean supports_small_last_frame = c.frame_size == 0
? true : 0 != (codec.capabilities &
AvcodecLibrary.CODEC_CAP_SMALL_LAST_FRAME);
int bufferSize =
avutil.av_samples_get_buffer_size((IntBuffer)null,
c.channels, frame_size, c.sample_fmt, 1);
assert bufferSize == expectedBufferSize:
String.format("expected %d; got %d",
expectedBufferSize, bufferSize);
ByteBuffer samples =
ByteBuffer.allocate(expectedBufferSize);
samples.order(ByteOrder.nativeOrder());
int audio_time = 0; // unit: (c.time_base) s =
(1/c.sample_rate) s
int audio_sample_count = supports_small_last_frame ?
3 * c.sample_rate :
3 * c.sample_rate / frame_size * frame_size;
while (audio_time < audio_sample_count) {
int frame_audio_time = audio_time;
samples.clear();
int nb_samples_in_frame = 0;
// encode a single tone sound
for (; samples.hasRemaining() && audio_time <
audio_sample_count; nb_samples_in_frame++,
audio_time++) {
double x = 2*Math.PI*440/c.sample_rate *
audio_time;
double y = 10000 * Math.sin(x);
samples.putShort((short) y);
samples.putShort((short) y);
}
samples.flip();
try (
SharedPtr<AVFrame> framePtr = new
SharedPtr<AVFrame>(avcodec.avcodec_alloc_frame())
{@Override public void close() {if
(null!=ptr)
avutil.av_free(ptr.getPointer());}};
) {
AVFrame frame =
Objects.requireNonNull(framePtr.ptr);
frame.setAutoRead(false); // will be an in param
frame.setAutoWrite(false);
frame.nb_samples = nb_samples_in_frame;
frame.writeField("nb_samples"); // actually
unused during encoding
// Presentation time, in AVStream.time_base
units.
frame.pts =
avutil.av_rescale_q(frame_audio_time,
c.time_base, st.time_base); // i *
codec_time_base / st_time_base
frame.writeField("pts");
assert c.channels > 0;
int bytesPerSample =
avutil.av_get_bytes_per_sample(c.sample_fmt);
assert bytesPerSample > 0;
if (0 != (err =
avcodec.avcodec_fill_audio_frame(frame,
c.channels, c.sample_fmt, samples,
samples.capacity(), 1))) {
throw new IllegalStateException(""+err);
}
AVPacket packet = new AVPacket(); // one of
the few structs from ffmpeg with guaranteed
size
avcodec.av_init_packet(packet);
packet.size = 0;
packet.data = null;
packet.stream_index = st.index;
packet.writeField("stream_index");
// encode the samples
IntBuffer gotPacket = IntBuffer.allocate(1);
if (0 != (err =
avcodec.avcodec_encode_audio2(c, packet,
frame, gotPacket))) {
throw new IllegalStateException("" + err);
} else if (0 != gotPacket.get()) {
packet.read();
averr = avformat.av_write_frame(fmtCtx,
packet);
if (averr < 0)
throw new IllegalStateException("" +
averr);
}
System.out.format("encoded frame: codec time =
%d; pts=%d = av_rescale_q(%d,%d/%d,%d/%d)
(%.02fs) contains %d samples (%.02fs);
got_packet=%d; packet.size=%d%n",
frame_audio_time,
frame.pts,
frame_audio_time,
st.codec.time_base.num,st.codec.time_base.den,st.time_base.num,st.time_base.den,
1.*frame_audio_time/c.sample_rate,
frame.nb_samples,
1.*frame.nb_samples/c.sample_rate,
gotPacket.array()[0], packet.size);
}
}
if (0 != (err = avformat.av_write_trailer(fmtCtx))) {
throw new IllegalStateException();
}
avformat.avio_flush(ioCtx);
}
}
}
System.out.println("Done writing");
}
}
I also rewrote it in C, and the C version works fine without any blips.
But I can't figure out how I am using the library differently; all the
library function calls should be identical!
//! gcc --std=c99 sin.c $(pkg-config --cflags --libs libavutil libavformat
libavcodec) -o sin
// sudo apt-get install libswscale-dev
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <libavutil/opt.h>
#include <libavutil/mathematics.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#include <libavcodec/avcodec.h>
int main(int argc, char *argv[]) {
const char *format_name = "wav", *file_url = "file:sin.wav";
avcodec_register_all();
av_register_all();
AVOutputFormat *format = NULL;
for (AVOutputFormat *formatIter = av_oformat_next(NULL); formatIter !=
NULL; formatIter = av_oformat_next(formatIter)) {
int hasEncoder = NULL != avcodec_find_encoder(formatIter->audio_codec);
if (0 == strcmp(format_name, formatIter->name)) {
format = formatIter;
break;
}
}
printf("Found format %s\n", format->name);
AVCodec *codec = avcodec_find_encoder(format->audio_codec);
if (! codec) {
fprintf(stderr, "Could not find codec %d\n", format->audio_codec);
exit(1);
}
AVFormatContext *fmtCtx = avformat_alloc_context();
if (! fmtCtx) {
fprintf(stderr, "error allocating AVFormatContext\n");
exit(1);
}
fmtCtx->oformat = format;
AVStream *st = avformat_new_stream(fmtCtx, codec);
if (! st) {
fprintf(stderr, "error allocating AVStream\n");
exit(1);
}
if (fmtCtx->nb_streams != 1) {
fprintf(stderr, "avformat_new_stream should have incremented
nb_streams, but it's still %d\n", fmtCtx->nb_streams);
exit(1);
}
AVCodecContext *c = st->codec;
if (! c) {
fprintf(stderr, "avformat_new_stream should have allocated a
AVCodecContext for my stream\n");
exit(1);
}
st->id = fmtCtx->nb_streams - 1;
printf("Created stream %d\n", st->id);
if (0 != (format->flags & AVFMT_GLOBALHEADER)) {
c->flags |= CODEC_FLAG_GLOBAL_HEADER;
}
c->bit_rate = 64000;
int bestSampleRate;
if (NULL == codec->supported_samplerates) {
bestSampleRate = 44100;
printf("Setting sample rate: %d\n", bestSampleRate);
} else {
bestSampleRate = 0;
for (const int *sample_rate_iter = codec->supported_samplerates;
*sample_rate_iter != 0; sample_rate_iter++) {
if (*sample_rate_iter >= bestSampleRate)
bestSampleRate = *sample_rate_iter;
}
printf("Using best supported sample rate: %d\n", bestSampleRate);
}
c->sample_rate = bestSampleRate;
c->channel_layout = AV_CH_LAYOUT_STEREO;
c->channels = av_get_channel_layout_nb_channels(c->channel_layout);
c->time_base.num = 1;
c->time_base.den = c->sample_rate;
if (c->channels != 2) {
fprintf(stderr, "av_get_channel_layout_nb_channels returned %d instead
of 2\n", c->channels);
exit(1);
}
c->sample_fmt = AV_SAMPLE_FMT_S16;
int averr;
if ((averr = avcodec_open2(c, codec, NULL)) < 0) {
fprintf(stderr, "avcodec_open2 returned error %d\n", averr);
exit(1);
}
AVIOContext *ioCtx = NULL;
if (0 != (averr = avio_open(&ioCtx, file_url, AVIO_FLAG_WRITE))) {
fprintf(stderr, "avio_open returned error %d\n", averr);
exit(1);
}
if (ioCtx == NULL) {
fprintf(stderr, "AVIOContext should have been set by avio_open\n");
exit(1);
}
fmtCtx->pb = ioCtx;
if (0 != (averr = avformat_write_header(fmtCtx, NULL))) {
fprintf(stderr, "avformat_write_header returned error %d\n", averr);
exit(1);
}
printf("Wrote header. fmtCtx->nb_streams=%d, st->time_base=%d/%d;
st->avg_frame_rate=%d/%d\n", fmtCtx->nb_streams, st->time_base.num,
st->time_base.den, st->avg_frame_rate.num, st->avg_frame_rate.den);
int align = 1;
int sample_size = av_get_bytes_per_sample(c->sample_fmt);
if (sample_size != sizeof(int16_t)) {
fprintf(stderr, "expected sample size=%zu but got %d\n",
sizeof(int16_t), sample_size);
exit(1);
}
int frame_size = c->frame_size != 0 ? c->frame_size : 4096;
int bufferSize = av_samples_get_buffer_size(NULL, c->channels,
frame_size, c->sample_fmt, align);
int expectedBufferSize = frame_size * c->channels * sample_size;
int supports_small_last_frame = c->frame_size == 0 ? 1 : 0 !=
(codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME);
if (bufferSize != expectedBufferSize) {
fprintf(stderr, "expected buffer size=%d but got %d\n",
expectedBufferSize, bufferSize);
exit(1);
}
int16_t *samples = (int16_t*)malloc(bufferSize);
uint32_t audio_time = 0; // unit: (1/c->sample_rate) s
uint32_t audio_sample_count = supports_small_last_frame ?
3 * c->sample_rate :
3 * c->sample_rate / frame_size * frame_size;
while (audio_time < audio_sample_count) {
uint32_t frame_audio_time = audio_time; // unit: (1/c->sample_rate) s
AVFrame *frame = avcodec_alloc_frame();
if (frame == NULL) {
fprintf(stderr, "avcodec_alloc_frame failed\n");
exit(1);
}
for (uint32_t i = 0; i != frame_size && audio_time <
audio_sample_count; i++, audio_time++) {
samples[2*i] = samples[2*i + 1] = 10000 *
sin(2*M_PI*440/c->sample_rate * audio_time);
frame->nb_samples = i+1; // actually unused during encoding
}
// frame->format = c->sample_fmt; // unused during encoding
frame->pts = av_rescale_q(frame_audio_time, c->time_base, st->time_base);
if (0 != (averr = avcodec_fill_audio_frame(frame, c->channels,
c->sample_fmt, (const uint8_t*)samples, bufferSize, align))) {
fprintf(stderr, "avcodec_fill_audio_frame returned error %d\n", averr);
exit(1);
}
AVPacket packet;
av_init_packet(&packet);
packet.data = NULL;
packet.size = 0;
int got_packet;
if (0 != (averr = avcodec_encode_audio2(c, &packet, frame,
&got_packet))) {
fprintf(stderr, "avcodec_encode_audio2 returned error %d\n", averr);
exit(1);
}
if (got_packet) {
packet.stream_index = st->index;
if (0 < (averr = av_write_frame(fmtCtx, &packet))) {
fprintf(stderr, "av_write_frame returned error %d\n", averr);
exit(1);
} else if (averr == 1) {
// end of stream wanted.
}
}
printf("encoded frame: codec time = %u; format pts=%ld =
av_rescale_q(%u,%d/%d,%d/%d) (%.02fs) contains %d samples (%.02fs);
got_packet=%d; packet.size=%d\n",
frame_audio_time,
frame->pts,
frame_audio_time, c->time_base.num, c->time_base.den,
st->time_base.num, st->time_base.den,
1.*frame_audio_time/c->sample_rate, frame->nb_samples,
1.*frame->nb_samples/c->sample_rate, got_packet, packet.size);
av_free(frame);
}
free(samples);
cleanupFile:
if (0 != (averr = av_write_trailer(fmtCtx))) {
fprintf(stderr, "av_write_trailer returned error %d\n", averr);
exit(1);
}
avio_flush(ioCtx);
avio_close(ioCtx);
avformat_free_context(fmtCtx);
}
how to tell the http server stop sending redundant bytes that i previously requested through "get"?
how to tell the http server stop sending redundant bytes that i previously
requested through "get"?
Say I want to download a file on a http server which supports segmenting
downloading. For example:
url to the file: www.music.com/rock.mp3
length of file: 4000 bytes
Say I launched two threads and each is downloading half of bytes of file.
thread t1 downloads bytes from 0 to 1999
thread t2 downloads bytes from 2000 to 3999
Say that t2 finished downloading down the later half, and t1 only
downloaded up to bytes 1199 yet, so t1 still has bytes 1200 to 1999 to go,
which is 800 bytes in total.
Now I want t1 keep downloading, up to bytes 1599, and let t2 start
download from byte 1600 to byte 1999. I see no problem of doing this with
t2, I just need to send another get message with range from 1600 to 1999.
But when I launched t1, it originally sent get message from range 0 to
1999, not from 0 to 1599, so it will keep getting bytes until the byte
1999 is delivered to my machine, which in t1's perspective include some
redundant bytes..
So for t1, is there any way to tell the server that, "ok plan changed I
only need up to 1599, don't send bytes from 1600"? One workaround that I
can come up with is just letting t1 not storing any bytes from byte 1599,
but it still consumes the bandwith and affect the network throughput. I am
doing this to make a dynamic segment downloading scheme to boost up the
downloading speed, so that's why I am concerned with speed and throughput
here. I imagine if it's a larg file, say maybe 1G, and using two threads,
then in worst case, the redundant bytes I have to discard would be a
lot....
In above scenario, when t2 finished its job from 2000 to 3999 and about to
grab bytes from 1600 to 1999, will t2 use the same http connection to grab
new range of bytes in default or I should do something before hand to make
it happen? And I am right that in such case, using same connection is
better than closing and opening another connection?
requested through "get"?
Say I want to download a file on a http server which supports segmenting
downloading. For example:
url to the file: www.music.com/rock.mp3
length of file: 4000 bytes
Say I launched two threads and each is downloading half of bytes of file.
thread t1 downloads bytes from 0 to 1999
thread t2 downloads bytes from 2000 to 3999
Say that t2 finished downloading down the later half, and t1 only
downloaded up to bytes 1199 yet, so t1 still has bytes 1200 to 1999 to go,
which is 800 bytes in total.
Now I want t1 keep downloading, up to bytes 1599, and let t2 start
download from byte 1600 to byte 1999. I see no problem of doing this with
t2, I just need to send another get message with range from 1600 to 1999.
But when I launched t1, it originally sent get message from range 0 to
1999, not from 0 to 1599, so it will keep getting bytes until the byte
1999 is delivered to my machine, which in t1's perspective include some
redundant bytes..
So for t1, is there any way to tell the server that, "ok plan changed I
only need up to 1599, don't send bytes from 1600"? One workaround that I
can come up with is just letting t1 not storing any bytes from byte 1599,
but it still consumes the bandwith and affect the network throughput. I am
doing this to make a dynamic segment downloading scheme to boost up the
downloading speed, so that's why I am concerned with speed and throughput
here. I imagine if it's a larg file, say maybe 1G, and using two threads,
then in worst case, the redundant bytes I have to discard would be a
lot....
In above scenario, when t2 finished its job from 2000 to 3999 and about to
grab bytes from 1600 to 1999, will t2 use the same http connection to grab
new range of bytes in default or I should do something before hand to make
it happen? And I am right that in such case, using same connection is
better than closing and opening another connection?
Show only 2 numbers after percentage
Show only 2 numbers after percentage
I have a problem where when i run the following query I get
"PercentageDifference" as 99.253731343283500 all i really want to show is
99.25 but no amount fiddling seems to get it any lower or results in an
error:
select PlannedMonthName, CountOfPlannedVisits, CountOfPlannedVisitsClosed,
CONVERT(DECIMAL(12,2),nullif(CountOfPlannedVisitsClosed, 0)) /
CONVERT(DECIMAL(12,2),nullif(CountOfPlannedVisits, 0)) * 100 AS
PercentageDifference
I have a problem where when i run the following query I get
"PercentageDifference" as 99.253731343283500 all i really want to show is
99.25 but no amount fiddling seems to get it any lower or results in an
error:
select PlannedMonthName, CountOfPlannedVisits, CountOfPlannedVisitsClosed,
CONVERT(DECIMAL(12,2),nullif(CountOfPlannedVisitsClosed, 0)) /
CONVERT(DECIMAL(12,2),nullif(CountOfPlannedVisits, 0)) * 100 AS
PercentageDifference
MissingMethodException on domain class save in Grails 1.3.7
MissingMethodException on domain class save in Grails 1.3.7
I'm having a problem calling the save method on a domain object. The error
is:
groovy.lang.MissingMethodException: No signature of method: static
my.awesome.Class.FeedHit.save() is applicable for argument types: ()
values: []
Possible solutions: save(), save(java.lang.Boolean), save(java.util.Map),
wait(), any(), wait(long)
I'm going through an array of FeedHits, updating a flag, and then calling
the save method:
void updateFeedHits(Set<FeedHit> list, FeedHitStatus status) {
for (FeedHit feedHit: list) {
feedHit.status = status
try {
alertHit.save()
} catch (Exception ex) {
log.info("unknown exception during update FeedHit", ex)
}
}
}
I've seen other StackOVerflow users have the same problem, but only during
tests. This code is in normal release code.
Any help would be appreciated.
I'm having a problem calling the save method on a domain object. The error
is:
groovy.lang.MissingMethodException: No signature of method: static
my.awesome.Class.FeedHit.save() is applicable for argument types: ()
values: []
Possible solutions: save(), save(java.lang.Boolean), save(java.util.Map),
wait(), any(), wait(long)
I'm going through an array of FeedHits, updating a flag, and then calling
the save method:
void updateFeedHits(Set<FeedHit> list, FeedHitStatus status) {
for (FeedHit feedHit: list) {
feedHit.status = status
try {
alertHit.save()
} catch (Exception ex) {
log.info("unknown exception during update FeedHit", ex)
}
}
}
I've seen other StackOVerflow users have the same problem, but only during
tests. This code is in normal release code.
Any help would be appreciated.
Wednesday, 21 August 2013
Image invalid when `&` in URL is escaped using `%26` and also `&`
Image invalid when `&` in URL is escaped using `%26` and also `&`
I try to validate my web page and I get the UNESCAPED ERRORS due to the &
characters in the image URL:
Original URL:
http://weathersticker.wunderground.com/weathersticker/cgi-bin/banner/ban/wxBanner?bannertype=wu_clean2day_metric_cond&airportcode=WMKK&ForcedCity=Kuala%20Lumpur&ForcedState=&wmo=48647&language=EN
I tried to replace the & with %26 and also & but the image became
invalid.
Is there a way to solve this?
I try to validate my web page and I get the UNESCAPED ERRORS due to the &
characters in the image URL:
Original URL:
http://weathersticker.wunderground.com/weathersticker/cgi-bin/banner/ban/wxBanner?bannertype=wu_clean2day_metric_cond&airportcode=WMKK&ForcedCity=Kuala%20Lumpur&ForcedState=&wmo=48647&language=EN
I tried to replace the & with %26 and also & but the image became
invalid.
Is there a way to solve this?
ExtJS resize listener not invoked
ExtJS resize listener not invoked
The resize listener is not invoked for the first item. I'm confused by
that. The only difference between them is an "activate" listener.
When I click the first panel, nothing happens. clicking on the second
panel invokes resize. And clicking back the first panel, still nothing
happens.
{
xtype: 'tabpanel',
defaults: {
bodyPadding: 0,
listeners:{
}
},
layout: 'fit',
items:[
{
id: 'selector-usermap',
html: '<div id="selector-usermap-body">'
+ '</div>',
listeners: {
afterrender: function(){
renderSelectorUserMapView('selector-usermap-body',
300,300);
},
activate: function(tp, t){
console.log("active" + t.id);
brushUser(Ext.getCmp('preview-container').getUsers());
},
resize: function(panel){
var size = panel.body.getSize();
console.log("User Map resize()");
console.log(size);
resizeSelectorUserMapView(size.height, size.width);
}
}
},
{
title: 'Organization',
id: 'selector-organization',
html: '<div id="selector-organization-body">'
+ '</div>',
listeners: {
afterrender: function(){
Ext.getCmp('selector-usermap').doLayout();
renderSelectorOrgView(divId, divHeight, divWidth);
},
resize: function(panel){
var size = panel.body.getSize();
console.log("Org Hier resize");
console.log(size);
resizeSelectorOrgView(size.height, size.width);
},
}
}
]
}
The resize listener is not invoked for the first item. I'm confused by
that. The only difference between them is an "activate" listener.
When I click the first panel, nothing happens. clicking on the second
panel invokes resize. And clicking back the first panel, still nothing
happens.
{
xtype: 'tabpanel',
defaults: {
bodyPadding: 0,
listeners:{
}
},
layout: 'fit',
items:[
{
id: 'selector-usermap',
html: '<div id="selector-usermap-body">'
+ '</div>',
listeners: {
afterrender: function(){
renderSelectorUserMapView('selector-usermap-body',
300,300);
},
activate: function(tp, t){
console.log("active" + t.id);
brushUser(Ext.getCmp('preview-container').getUsers());
},
resize: function(panel){
var size = panel.body.getSize();
console.log("User Map resize()");
console.log(size);
resizeSelectorUserMapView(size.height, size.width);
}
}
},
{
title: 'Organization',
id: 'selector-organization',
html: '<div id="selector-organization-body">'
+ '</div>',
listeners: {
afterrender: function(){
Ext.getCmp('selector-usermap').doLayout();
renderSelectorOrgView(divId, divHeight, divWidth);
},
resize: function(panel){
var size = panel.body.getSize();
console.log("Org Hier resize");
console.log(size);
resizeSelectorOrgView(size.height, size.width);
},
}
}
]
}
How to prevent user to input nothing in bash script
How to prevent user to input nothing in bash script
I have a program that will take user input string and create output files
accordingly, for example, "./bashexample2 J40087" this will create output
files for all the files in the folder that contain the string J40087. One
problem is that if the user does not input anything in the input string it
will generate output files for every file inside the containing folder. Is
there a way to prevent user to input nothing in the input string? Or maybe
spit out some sort of warning saying " please input an input string".
#Please follow the following example as input: xl-irv-05{kmoslehp}312:
./bashexample2 J40087
#!/bin/bash
directory=$(cd `dirname .` && pwd) ##declaring current path
tag=$1 ##declaring argument which is the user input string
echo find: $tag on $directory ##output input string in current directory.
find $directory . -maxdepth 0 -type f -exec grep -sl "$tag" {} \; ##this
finds the string the user requested
for files in "$directory"/*"$tag"* ##for all the files with input string
name...
do
if [[ $files == *.std ]]; then ##if files have .std extensions convert
them to .sum files...
/projects/OPSLIB/BCMTOOLS/sumfmt_linux < "$files" >
"${files}.sum"
fi
if [[ $files == *.txt ]]; then ## if files have .txt extensions grep
all fails and convert them..
egrep "device|Device|\(F\)" "$files" > "${files}.fail"
fi
echo $files ##print all files that we found
done
I have a program that will take user input string and create output files
accordingly, for example, "./bashexample2 J40087" this will create output
files for all the files in the folder that contain the string J40087. One
problem is that if the user does not input anything in the input string it
will generate output files for every file inside the containing folder. Is
there a way to prevent user to input nothing in the input string? Or maybe
spit out some sort of warning saying " please input an input string".
#Please follow the following example as input: xl-irv-05{kmoslehp}312:
./bashexample2 J40087
#!/bin/bash
directory=$(cd `dirname .` && pwd) ##declaring current path
tag=$1 ##declaring argument which is the user input string
echo find: $tag on $directory ##output input string in current directory.
find $directory . -maxdepth 0 -type f -exec grep -sl "$tag" {} \; ##this
finds the string the user requested
for files in "$directory"/*"$tag"* ##for all the files with input string
name...
do
if [[ $files == *.std ]]; then ##if files have .std extensions convert
them to .sum files...
/projects/OPSLIB/BCMTOOLS/sumfmt_linux < "$files" >
"${files}.sum"
fi
if [[ $files == *.txt ]]; then ## if files have .txt extensions grep
all fails and convert them..
egrep "device|Device|\(F\)" "$files" > "${files}.fail"
fi
echo $files ##print all files that we found
done
error importing python library in scraperwiki
error importing python library in scraperwiki
I am using scraperwiki to run some code in Python. However, when I run
this code I am getting this error:
Traceback (most recent call last): File "./code/scraper", line 4, in from
scrapemark import scrape ImportError: No module named scrapemark
here is the code:
import scraperwiki
from scrapemark import scrape
import scraperwiki
for page in range(1,40):
URL =
"https://appexchange.salesforce.com/results?pageNo="+str(page)+"&filter=a0L3000000OvSOGEA3"
#Marketing
print URL
html = scraperwiki.scrape(URL)
scrape_data = scrape("""
{*
<a class="tile-title" href="{{ [mobile].[link] }}" id="{{ [mobile].[id]
}}" title="{{ [mobile].[title1] }}"></a>
*}
""", html=html);
data = [{'Title':p['title1'][0], 'URL':p['link'][0], 'ID':p['id'][0],
'Format':'Managed'} for p in scrape_data['mobile']]
scraperwiki.sqlite.save(unique_keys=["URL"], data=data)
Can anyone tell me how to fix this?
I am using scraperwiki to run some code in Python. However, when I run
this code I am getting this error:
Traceback (most recent call last): File "./code/scraper", line 4, in from
scrapemark import scrape ImportError: No module named scrapemark
here is the code:
import scraperwiki
from scrapemark import scrape
import scraperwiki
for page in range(1,40):
URL =
"https://appexchange.salesforce.com/results?pageNo="+str(page)+"&filter=a0L3000000OvSOGEA3"
#Marketing
print URL
html = scraperwiki.scrape(URL)
scrape_data = scrape("""
{*
<a class="tile-title" href="{{ [mobile].[link] }}" id="{{ [mobile].[id]
}}" title="{{ [mobile].[title1] }}"></a>
*}
""", html=html);
data = [{'Title':p['title1'][0], 'URL':p['link'][0], 'ID':p['id'][0],
'Format':'Managed'} for p in scrape_data['mobile']]
scraperwiki.sqlite.save(unique_keys=["URL"], data=data)
Can anyone tell me how to fix this?
Remove or change google maps address in google search result snippet
Remove or change google maps address in google search result snippet
On one of my sites I have a google maps pin, address and phone number
included in my search result snippet. The problem is that it's the correct
address but the phone number is wrong and I can't understand where this
come from and how to change it or remove the maps snippet from the result.
What I have read is that Google can use information from all over the web
to produce a great snippet for my site but in my case it's not so great.
Is it possible to change it in any way?
On one of my sites I have a google maps pin, address and phone number
included in my search result snippet. The problem is that it's the correct
address but the phone number is wrong and I can't understand where this
come from and how to change it or remove the maps snippet from the result.
What I have read is that Google can use information from all over the web
to produce a great snippet for my site but in my case it's not so great.
Is it possible to change it in any way?
How to loosely couple modules in service oriented architecture
How to loosely couple modules in service oriented architecture
We're developing a total solution, and we've chosen service-oriented
architecture to loosen subsystems. However, now we have a problem.
When customer orders something, Order Subsystem is responsible to get that
order, and register it. However, there are some other modules which are
responsible too, in order registration process, and each module should do
something on it:
Customer Accounting module should check customer's balance, and prevent
order registration if there is not enough money in customer's account.
Asset Management module should increase/decrease customer's assets
Rule Engine should apply some business rules dynamically on it (like
preventing a specific customer, or notifying an operator, etc.)
CRM should view customer's history, and give good customers some discount
...
Right now, we're doing it this way:
public void RegisterOrder(Order order)
{
RuleEngineService.ApplyBusinessRules(order);
// some code here
CrmService.GiveDiscountIfApplicable(order);
// some code here
CustomerAccountingService.CheckBalance(order);
// some code here
AssetManagementService.ChangeAssetCount(order);
// some code here
}
This means that if we add another subsystem (module) that needs to do
something on order, we have to recompile the code of our OMS (Order
Management System) to support it. Also we're coupled to some extent to
other subsystems here, and if one of them fail, this registration process
fails.
One way of making this piece of code dynamic and loosely coupled is to use
interfaces or contracts, like:
public void RegisterOrder(Order order)
{
// Finding a list of all IOrderProcessors.
// Looping over each, calling orderProcessor.Process(order);
}
However, it has two problems:
We can't use interfaces over SOAP and HTTP (we don't have access to other
subsystems' DLL files)
Those need to run in a specified order (rule engine the first one)
What should we do here? What are the known patterns and practices?
We're developing a total solution, and we've chosen service-oriented
architecture to loosen subsystems. However, now we have a problem.
When customer orders something, Order Subsystem is responsible to get that
order, and register it. However, there are some other modules which are
responsible too, in order registration process, and each module should do
something on it:
Customer Accounting module should check customer's balance, and prevent
order registration if there is not enough money in customer's account.
Asset Management module should increase/decrease customer's assets
Rule Engine should apply some business rules dynamically on it (like
preventing a specific customer, or notifying an operator, etc.)
CRM should view customer's history, and give good customers some discount
...
Right now, we're doing it this way:
public void RegisterOrder(Order order)
{
RuleEngineService.ApplyBusinessRules(order);
// some code here
CrmService.GiveDiscountIfApplicable(order);
// some code here
CustomerAccountingService.CheckBalance(order);
// some code here
AssetManagementService.ChangeAssetCount(order);
// some code here
}
This means that if we add another subsystem (module) that needs to do
something on order, we have to recompile the code of our OMS (Order
Management System) to support it. Also we're coupled to some extent to
other subsystems here, and if one of them fail, this registration process
fails.
One way of making this piece of code dynamic and loosely coupled is to use
interfaces or contracts, like:
public void RegisterOrder(Order order)
{
// Finding a list of all IOrderProcessors.
// Looping over each, calling orderProcessor.Process(order);
}
However, it has two problems:
We can't use interfaces over SOAP and HTTP (we don't have access to other
subsystems' DLL files)
Those need to run in a specified order (rule engine the first one)
What should we do here? What are the known patterns and practices?
Error while CSV-JSON conversion
Error while CSV-JSON conversion
I am using following code but i am getting error: JSON is undefined.Any clue?
<html>
<head>
<title>Demo - Covnert JSON to CSV</title>
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript"
src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
<script type="text/javascript">
// JSON to CSV Converter
function ConvertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray)
: objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
// Example
$(document).ready(function () {
// Create Object
var items = [
{
"items": [
{
"ID": "1",
"NAME": " John"
},
{
"ID": "2",
"NAME": " Ashley"
},
{
"ID": "3",
"NAME": " Joseph"
}
]
}];
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
// Display JSON
$('#json').text(jsonObject);
// Convert JSON to CSV & Display CSV
$('#csv').text(ConvertToCSV(jsonObject));
});
</script>
</head>
<body>
<h1>
JSON</h1>
<pre id="json"></pre>
<h1>
CSV</h1>
<pre id="csv"></pre>
</body>
</html>
I am using following code but i am getting error: JSON is undefined.Any clue?
<html>
<head>
<title>Demo - Covnert JSON to CSV</title>
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript"
src="https://github.com/douglascrockford/JSON-js/raw/master/json2.js"></script>
<script type="text/javascript">
// JSON to CSV Converter
function ConvertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray)
: objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
// Example
$(document).ready(function () {
// Create Object
var items = [
{
"items": [
{
"ID": "1",
"NAME": " John"
},
{
"ID": "2",
"NAME": " Ashley"
},
{
"ID": "3",
"NAME": " Joseph"
}
]
}];
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
// Display JSON
$('#json').text(jsonObject);
// Convert JSON to CSV & Display CSV
$('#csv').text(ConvertToCSV(jsonObject));
});
</script>
</head>
<body>
<h1>
JSON</h1>
<pre id="json"></pre>
<h1>
CSV</h1>
<pre id="csv"></pre>
</body>
</html>
Tuesday, 20 August 2013
Sqoop--Error during export, job failed
Sqoop--Error during export, job failed
we are trying to export the data from HDFS to mysql using sqoop, and
facing the following issue.
Sample data:
{(THB0000000018401231),(18401231),(+00000cbsadm),(000000000000),(00),(0000000018401231),(200001),(+013050120AA0+0000000000000000001),(+000000000000000000+00DEPOSIT),(+000000000000000000+000000),(2001+00000+000000000000000000+0000000000000000009257),(201305001#2001#20AA),(0),(ATSWC),(000000K03395),(00AD1#000141KRUNG),(TSDAAI),(~ZCM#2~ZIR#0),(K03395),(201474001),(91141),(312108004)}
{(THB0000000018401231),(18401231),(+00000cbsadm),(000000000000),(00),(0000000018401231),(200001),(+013050120AA0+0000000000000000001),(+000000000000000000+00DEPOSIT),(+000000000000000000+000000),(2001+00000+000000000000000000+0000000000000000009257),(201305001#2001#20AA),(0),(ATSWC),(000000K03395),(00AD1#000141KRUNG),(TSDAAI),(~ZCM#2~ZIR#0),(K03395),(201474001),(91141),(312108004)}
First, we did tokenize using pig and to make data comma separated, as
shown above. After we replicated the record for testing purpose.
Following Sqoop program, we used to export data from HDFS to MYSQL and we
specified the schema in table b1:
public class App //Export data from hdfs to mysql using sqoop
{
public static void main(String[] args) {
String[] str = { "export", "--connect", "jdbc:mysql://-------/test",
"--table", "b1", "--username", "root", "--password", "******",
"--export-dir", "hdfs://-----/user/hdfs/token2/",
"--input-fields-terminated-by", ",",
"--input-lines-terminated-by", "\n"
};
Sqoop.runTool(str);
}
Error after program execution:
11068 [main] ERROR org.apache.sqoop.tool.ExportTool - Error during export:
Export job failed!
After, we checked the mysql table only first record is there. We are
trying to load multiple records also but only one record is exported to
table.
Your help is highly appreciated.
we are trying to export the data from HDFS to mysql using sqoop, and
facing the following issue.
Sample data:
{(THB0000000018401231),(18401231),(+00000cbsadm),(000000000000),(00),(0000000018401231),(200001),(+013050120AA0+0000000000000000001),(+000000000000000000+00DEPOSIT),(+000000000000000000+000000),(2001+00000+000000000000000000+0000000000000000009257),(201305001#2001#20AA),(0),(ATSWC),(000000K03395),(00AD1#000141KRUNG),(TSDAAI),(~ZCM#2~ZIR#0),(K03395),(201474001),(91141),(312108004)}
{(THB0000000018401231),(18401231),(+00000cbsadm),(000000000000),(00),(0000000018401231),(200001),(+013050120AA0+0000000000000000001),(+000000000000000000+00DEPOSIT),(+000000000000000000+000000),(2001+00000+000000000000000000+0000000000000000009257),(201305001#2001#20AA),(0),(ATSWC),(000000K03395),(00AD1#000141KRUNG),(TSDAAI),(~ZCM#2~ZIR#0),(K03395),(201474001),(91141),(312108004)}
First, we did tokenize using pig and to make data comma separated, as
shown above. After we replicated the record for testing purpose.
Following Sqoop program, we used to export data from HDFS to MYSQL and we
specified the schema in table b1:
public class App //Export data from hdfs to mysql using sqoop
{
public static void main(String[] args) {
String[] str = { "export", "--connect", "jdbc:mysql://-------/test",
"--table", "b1", "--username", "root", "--password", "******",
"--export-dir", "hdfs://-----/user/hdfs/token2/",
"--input-fields-terminated-by", ",",
"--input-lines-terminated-by", "\n"
};
Sqoop.runTool(str);
}
Error after program execution:
11068 [main] ERROR org.apache.sqoop.tool.ExportTool - Error during export:
Export job failed!
After, we checked the mysql table only first record is there. We are
trying to load multiple records also but only one record is exported to
table.
Your help is highly appreciated.
how to overcome login in TNS issue in oracle?
how to overcome login in TNS issue in oracle?
I created demodb when I was installing oracle. I used to connect to oracle
easyly using my login and password via SQL plus.
Today I encountered a problem login in: ORA-12560: TNS: protocol adapter
error
What is wrong?
I created demodb when I was installing oracle. I used to connect to oracle
easyly using my login and password via SQL plus.
Today I encountered a problem login in: ORA-12560: TNS: protocol adapter
error
What is wrong?
iOS SalesForce SDK on existing iOS App
iOS SalesForce SDK on existing iOS App
pls can anyone explain how to include saleforce SDK to existing iOS app
and have it authenticate to a salesforce account? Thanks!
pls can anyone explain how to include saleforce SDK to existing iOS app
and have it authenticate to a salesforce account? Thanks!
What is the max number of variables once can use in an exhaustive all-subsets regression using glmulti()
What is the max number of variables once can use in an exhaustive
all-subsets regression using glmulti()
I am using the glmulti() package in R to try and run an all-subset
regression on some data. I have 51 predictors, all with a maximum of 276
observations. I realize that the exhaustive and genetic algorithm
approaches cannot compute with this many variables as I receive the
following:
Warning message: In glmulti(y = "Tons_N", data = MDatEB1_TonsN, level = 1,
method = "h", : !Too many predictors.
With these types of requirements (i.e. many variables with lots of
observations), how many will I be able to use in a single run of the
all-subsets regression? I am looking into variable elimination techniques
but I would like to use as many variables as possible in this stage of the
analysis. That is, I want to use the results of this analysis to make
variable elimination decisions. Is there another package that can process
more variables at a time?
Here is the code I am using. Unfortunately, because of the confidentiality
associated with the project, I cannot attach datasets.
TonsN_AllSubset <- glmulti(Tons_N ~ ., data = MDatEB1_TonsN, level = 1,
method = "h",crit = "aic", confsetsize = 20, plotty = T, report =
T,fitfunction = "glm")
I am relatively new to this package and modeling in general. Any direction
or advice will be greatly appreciated. Thank you!
all-subsets regression using glmulti()
I am using the glmulti() package in R to try and run an all-subset
regression on some data. I have 51 predictors, all with a maximum of 276
observations. I realize that the exhaustive and genetic algorithm
approaches cannot compute with this many variables as I receive the
following:
Warning message: In glmulti(y = "Tons_N", data = MDatEB1_TonsN, level = 1,
method = "h", : !Too many predictors.
With these types of requirements (i.e. many variables with lots of
observations), how many will I be able to use in a single run of the
all-subsets regression? I am looking into variable elimination techniques
but I would like to use as many variables as possible in this stage of the
analysis. That is, I want to use the results of this analysis to make
variable elimination decisions. Is there another package that can process
more variables at a time?
Here is the code I am using. Unfortunately, because of the confidentiality
associated with the project, I cannot attach datasets.
TonsN_AllSubset <- glmulti(Tons_N ~ ., data = MDatEB1_TonsN, level = 1,
method = "h",crit = "aic", confsetsize = 20, plotty = T, report =
T,fitfunction = "glm")
I am relatively new to this package and modeling in general. Any direction
or advice will be greatly appreciated. Thank you!
404 - File or directory not found with Azure/GoDaddy
404 - File or directory not found with Azure/GoDaddy
I'm moving my web host from GoDaddy to Azure, and I'm getting the error
above.
These are the steps I followed:
1) Made my azure website the paid (yet shared) version
2) Went to GoDaddy and change A record to @ 168.62.224.13 (my ip)
3) Under CNAME entered "www" under CNAME and "mysite.azurewebsites.net"
under points to.
www.mysite.com goes to the IP, but it does not find my site so I get the
404. Maybe I need to wait longer... or did I neglect to do something?
I'm moving my web host from GoDaddy to Azure, and I'm getting the error
above.
These are the steps I followed:
1) Made my azure website the paid (yet shared) version
2) Went to GoDaddy and change A record to @ 168.62.224.13 (my ip)
3) Under CNAME entered "www" under CNAME and "mysite.azurewebsites.net"
under points to.
www.mysite.com goes to the IP, but it does not find my site so I get the
404. Maybe I need to wait longer... or did I neglect to do something?
How to reset terminator terminal emulator configuration?
How to reset terminator terminal emulator configuration?
I messed up terminator, I tried to use some commands in the preferences
and now it doesn't work anymore, it starts and exits immediately, I tried
reinstalling it using synaptic manager, but that didn't work either. I
searched didn't find anything.
I still can use xterm.
I messed up terminator, I tried to use some commands in the preferences
and now it doesn't work anymore, it starts and exits immediately, I tried
reinstalling it using synaptic manager, but that didn't work either. I
searched didn't find anything.
I still can use xterm.
select div when clicked according to z-index value
select div when clicked according to z-index value
I am very much confused how to get the div id I want. If I am going to
click the div layer3 , all DIVs(parent divs) also include into it.
INNER DIV content
Thank you so much
I am very much confused how to get the div id I want. If I am going to
click the div layer3 , all DIVs(parent divs) also include into it.
INNER DIV content
Thank you so much
Monday, 19 August 2013
How can we filter text from array
How can we filter text from array
I have an array which return data in size like 3,6,9,12,15..
(multiplication of 3)
DataTable dt = new DataTable();
string GridData = ViewState["ShowItem"].ToString();
string[] FilterData = GridData.Split('^');
Above array return data like..
FilterData [0] = "Pizza"; (Item)
FilterData [1] = "2$"; (Price)
FilterData [2] = "2"; (Quantity)
FilterData [3] = "Burger";
FilterData [4] = "5$";
FilterData [5] = "1";
FilterData [6] = "Cesa";
FilterData [7] = "7$";
FilterData [8] = "3";
now I want to enter above data as column wise in database like:
Item Price Quantity Total(Price*Quantity)
now I want to run a loop that add data of particular field like:
for (int nIndex = 0; nIndex < FilterData.Length; nIndex++)
{
DataRow drow = dt.NewRow();
drow["ProductItem"] = FilterData[nIndex].ToString(); (Add all Item)
drow["Cost"] = FilterData[nIndex].ToString(); (Add all Cost)
drow["Quantity"] = FilterData[nIndex].ToString(); (Add all Quantity)
double Total= Convert.ToDouble(FilterData[nIndex].ToString()) *
Convert.ToInt32(FilterData[nIndex].ToString()); (Add all
cost*Quantity)
drow["Total"] = Total;
dt.Rows.Add(drow);
}
So can anybody help me how could I run the loop so it add data to
particular column like: Item Price Quantity Total(Price*Quantity)
Pizza 2 2 4
Burger 5 1 5
Cesa 7 3 21
I have an array which return data in size like 3,6,9,12,15..
(multiplication of 3)
DataTable dt = new DataTable();
string GridData = ViewState["ShowItem"].ToString();
string[] FilterData = GridData.Split('^');
Above array return data like..
FilterData [0] = "Pizza"; (Item)
FilterData [1] = "2$"; (Price)
FilterData [2] = "2"; (Quantity)
FilterData [3] = "Burger";
FilterData [4] = "5$";
FilterData [5] = "1";
FilterData [6] = "Cesa";
FilterData [7] = "7$";
FilterData [8] = "3";
now I want to enter above data as column wise in database like:
Item Price Quantity Total(Price*Quantity)
now I want to run a loop that add data of particular field like:
for (int nIndex = 0; nIndex < FilterData.Length; nIndex++)
{
DataRow drow = dt.NewRow();
drow["ProductItem"] = FilterData[nIndex].ToString(); (Add all Item)
drow["Cost"] = FilterData[nIndex].ToString(); (Add all Cost)
drow["Quantity"] = FilterData[nIndex].ToString(); (Add all Quantity)
double Total= Convert.ToDouble(FilterData[nIndex].ToString()) *
Convert.ToInt32(FilterData[nIndex].ToString()); (Add all
cost*Quantity)
drow["Total"] = Total;
dt.Rows.Add(drow);
}
So can anybody help me how could I run the loop so it add data to
particular column like: Item Price Quantity Total(Price*Quantity)
Pizza 2 2 4
Burger 5 1 5
Cesa 7 3 21
A basic doubt on linear maps
A basic doubt on linear maps
Let $f$ be a linear map from $V$ to its field set, say $F$. Now if
$f(v)=0$ does it necessarily imply that $v=0$. I don't think so. $v=0$ is
one solution, but it need not be the only solution because $f$ need not be
one-to-one. Is this correct ?
Let $f$ be a linear map from $V$ to its field set, say $F$. Now if
$f(v)=0$ does it necessarily imply that $v=0$. I don't think so. $v=0$ is
one solution, but it need not be the only solution because $f$ need not be
one-to-one. Is this correct ?
Animation when drawing with CGContext
Animation when drawing with CGContext
My question is how to animate the drawing process when drawing with
CGContextRef. Is it possible? Assuming it is, how?
I have two code snippets that I would like to animate. First one draws a
progress bar and the second one draws a simple line chart. The drawing is
done inside a subclass of UIView.
Progress bar is nice and easy. But I want it to sort of draw itself out
from the left. I am pretty sure that this will require using something
other than UIRectFill but I dont know how to accomplish it.
- (void)drawProgressLine
{
[bgColor set];
UIRectFill(self.bounds);
[graphColor set];
UIRectFill(CGRectMake(0, 0, self.frame.size.width / 100 * [[items
objectAtIndex:0] floatValue], self.frame.size.height));
}
The line chart is a bit more complex. I would really really like it to
start drawing itself from the left line by line slowly completing itself
towards the right but if that is too much how can I just slowly fade it
in? The code:
- (void)drawLineChart
{
[bgColor set];
UIRectFill(self.bounds);
[graphColor set];
if (items.count < 2) return;
CGRect bounds = CGRectMake(0, 50, self.bounds.size.width,
self.bounds.size.height - 100);
float max = -1;
for (GraphItem *item in items)
if (item.value > max)
max = item.value;
float xStep = (self.frame.size.width) / (items.count - 1);
for (int i = 0; i < items.count; i++)
{
if (i == items.count - 1) break;
float itemHeight = bounds.origin.y + bounds.size.height -
((GraphItem*)[items objectAtIndex:i]).value / max *
bounds.size.height;
float nextItemHeight = bounds.origin.y + bounds.size.height -
((GraphItem*)[items objectAtIndex:i + 1]).value / max *
bounds.size.height;
CGPoint start = CGPointMake(xStep * i, itemHeight);
CGPoint stop = CGPointMake(xStep * (i + 1), nextItemHeight);
[self drawLineFromPoint:start toPoint:stop lineWidth:1
color:graphColor shadow:YES];
}
}
Pretty simple I guess. If important the drawLineFromPoint..... is
implemented like:
- (void)drawLineFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint
lineWidth:(CGFloat)width color:(UIColor *)color shadow:(BOOL)shadow
{
if (shadow)
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat components[4] = {0.0, 0.0, 0.0, 1.0};
CGColorRef shadowColor = CGColorCreate(colorSpace, components);
CGContextSetShadowWithColor(UIGraphicsGetCurrentContext(),
CGSizeMake(1,1), 2.0, shadowColor);
}
CGContextBeginPath(context);
CGContextSetLineWidth(context, width);
CGContextMoveToPoint(context, startPoint.x, startPoint.y);
CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
CGContextClosePath(context);
[color setStroke];
CGContextStrokePath(context);
CGContextSetShadowWithColor(context, CGSizeZero, 0, NULL);
}
I hope I made myself clear cause its 1 am in my country and this post is
the last thing that stands between me and my bed. Cheers, Jan.
My question is how to animate the drawing process when drawing with
CGContextRef. Is it possible? Assuming it is, how?
I have two code snippets that I would like to animate. First one draws a
progress bar and the second one draws a simple line chart. The drawing is
done inside a subclass of UIView.
Progress bar is nice and easy. But I want it to sort of draw itself out
from the left. I am pretty sure that this will require using something
other than UIRectFill but I dont know how to accomplish it.
- (void)drawProgressLine
{
[bgColor set];
UIRectFill(self.bounds);
[graphColor set];
UIRectFill(CGRectMake(0, 0, self.frame.size.width / 100 * [[items
objectAtIndex:0] floatValue], self.frame.size.height));
}
The line chart is a bit more complex. I would really really like it to
start drawing itself from the left line by line slowly completing itself
towards the right but if that is too much how can I just slowly fade it
in? The code:
- (void)drawLineChart
{
[bgColor set];
UIRectFill(self.bounds);
[graphColor set];
if (items.count < 2) return;
CGRect bounds = CGRectMake(0, 50, self.bounds.size.width,
self.bounds.size.height - 100);
float max = -1;
for (GraphItem *item in items)
if (item.value > max)
max = item.value;
float xStep = (self.frame.size.width) / (items.count - 1);
for (int i = 0; i < items.count; i++)
{
if (i == items.count - 1) break;
float itemHeight = bounds.origin.y + bounds.size.height -
((GraphItem*)[items objectAtIndex:i]).value / max *
bounds.size.height;
float nextItemHeight = bounds.origin.y + bounds.size.height -
((GraphItem*)[items objectAtIndex:i + 1]).value / max *
bounds.size.height;
CGPoint start = CGPointMake(xStep * i, itemHeight);
CGPoint stop = CGPointMake(xStep * (i + 1), nextItemHeight);
[self drawLineFromPoint:start toPoint:stop lineWidth:1
color:graphColor shadow:YES];
}
}
Pretty simple I guess. If important the drawLineFromPoint..... is
implemented like:
- (void)drawLineFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint
lineWidth:(CGFloat)width color:(UIColor *)color shadow:(BOOL)shadow
{
if (shadow)
{
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat components[4] = {0.0, 0.0, 0.0, 1.0};
CGColorRef shadowColor = CGColorCreate(colorSpace, components);
CGContextSetShadowWithColor(UIGraphicsGetCurrentContext(),
CGSizeMake(1,1), 2.0, shadowColor);
}
CGContextBeginPath(context);
CGContextSetLineWidth(context, width);
CGContextMoveToPoint(context, startPoint.x, startPoint.y);
CGContextAddLineToPoint(context, endPoint.x, endPoint.y);
CGContextClosePath(context);
[color setStroke];
CGContextStrokePath(context);
CGContextSetShadowWithColor(context, CGSizeZero, 0, NULL);
}
I hope I made myself clear cause its 1 am in my country and this post is
the last thing that stands between me and my bed. Cheers, Jan.
Move data to next cell on click when repopulating a grid after update
Move data to next cell on click when repopulating a grid after update
populate grid view and then on cell click i populate text box on cell
click event like,
private void dgvCompany_CellClick(object sender,
DataGridViewCellEventArgs e)
{
int i = dgvCompany.SelectedCells[0].RowIndex;
ID = dgvCompany.Rows[i].Cells[0].Value.ToString();
txtCompanyName.Text =
dgvCompany.Rows[i].Cells[1].Value.ToString();
txtContactName.Text =
dgvCompany.Rows[i].Cells[2].Value.ToString();
txtContactPersonPhone.Text =
dgvCompany.Rows[i].Cells[3].Value.ToString();
txtAddress.Text = dgvCompany.Rows[i].Cells[4].Value.ToString();
txtCity.Text = dgvCompany.Rows[i].Cells[5].Value.ToString();
txtPhone.Text = dgvCompany.Rows[i].Cells[6].Value.ToString();
cbIsActive.Checked =
Convert.ToBoolean(dgvCompany.Rows[i].Cells[7].Value);
}
here ID is string variable after populating text box i edit and save
update and then refill grid as previous method like,
public void FillCompanyInfo()
{
DataTable dtCompanyInfo = objFunctions.GetCompanyInfo();
if(dtCompanyInfo.Rows.Count>0)
{
dgvCompany.DataSource = dtCompanyInfo;
if (this.dgvCompany.Columns.Count == 8)
{
DataGridViewCheckBoxColumn checkColumn = new
DataGridViewCheckBoxColumn();
checkColumn.Name = "";
checkColumn.HeaderText = "Select";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10; //if the datagridview is
resized (on form resize) the checkbox won't take up
too much; value is relative to the other columns' fill
values\\
dgvCompany.Columns.Add(checkColumn);
}
}
}
here i use if condition counting column to 8 because each time it add
column Select and after populating grid again when i click on grid and
cell click event fire result in error ,
on line ,
ID = dgvCompany.Rows[i].Cells[0].Value.ToString();
object reference not found because it is getting null on cell 0 while it
was working fine before update on cell click and when i use break point i
am getting ID on cells[1] and cell[0] is null
i am not understanding this error
Hopes for your suggestion
Thanks
populate grid view and then on cell click i populate text box on cell
click event like,
private void dgvCompany_CellClick(object sender,
DataGridViewCellEventArgs e)
{
int i = dgvCompany.SelectedCells[0].RowIndex;
ID = dgvCompany.Rows[i].Cells[0].Value.ToString();
txtCompanyName.Text =
dgvCompany.Rows[i].Cells[1].Value.ToString();
txtContactName.Text =
dgvCompany.Rows[i].Cells[2].Value.ToString();
txtContactPersonPhone.Text =
dgvCompany.Rows[i].Cells[3].Value.ToString();
txtAddress.Text = dgvCompany.Rows[i].Cells[4].Value.ToString();
txtCity.Text = dgvCompany.Rows[i].Cells[5].Value.ToString();
txtPhone.Text = dgvCompany.Rows[i].Cells[6].Value.ToString();
cbIsActive.Checked =
Convert.ToBoolean(dgvCompany.Rows[i].Cells[7].Value);
}
here ID is string variable after populating text box i edit and save
update and then refill grid as previous method like,
public void FillCompanyInfo()
{
DataTable dtCompanyInfo = objFunctions.GetCompanyInfo();
if(dtCompanyInfo.Rows.Count>0)
{
dgvCompany.DataSource = dtCompanyInfo;
if (this.dgvCompany.Columns.Count == 8)
{
DataGridViewCheckBoxColumn checkColumn = new
DataGridViewCheckBoxColumn();
checkColumn.Name = "";
checkColumn.HeaderText = "Select";
checkColumn.Width = 50;
checkColumn.ReadOnly = false;
checkColumn.FillWeight = 10; //if the datagridview is
resized (on form resize) the checkbox won't take up
too much; value is relative to the other columns' fill
values\\
dgvCompany.Columns.Add(checkColumn);
}
}
}
here i use if condition counting column to 8 because each time it add
column Select and after populating grid again when i click on grid and
cell click event fire result in error ,
on line ,
ID = dgvCompany.Rows[i].Cells[0].Value.ToString();
object reference not found because it is getting null on cell 0 while it
was working fine before update on cell click and when i use break point i
am getting ID on cells[1] and cell[0] is null
i am not understanding this error
Hopes for your suggestion
Thanks
Subscribe to:
Comments (Atom)