Cant get my regex to validate my html form
I have a html form with some client validation and some server validation
(regex). But i cant get the regex to work with the html form, and it
possible to submit the form without any inputs. I have been stuck on this
for hours, argh. Any one that can understand why?
This is the HTML form
<form action="brukerinfo.php" method="post" name="kontaktskjema"
id="kontaktskjema">
<h3>Registrer din informasjon her</h3>
<div>
<label>
<span>Fornavn: (påkrevd)</span>
<input name="fornavn" id="fornavn"
placeholder="Fornavn" type="text" tabindex="1"
pattern="^[a-zA-ZæøåÆØÅ]{2,}$"
title="Fornavn er påkrevd, og må være minst 2
tegn" required autofocus>
</label>
</div>
<div>
<label>
<span>Etternavn: (påkrevd)</span>
<input name="etternavn" id="etternavn"
placeholder="Etternavn" type="text" tabindex="2"
pattern="^[a-zA-ZæøåÆØÅ]{2,}$"
title="Etternavn er påkrevd, og må være minst 2
tegn og kan ikke bestå av mellomrom" required>
</label>
</div>
<div>
<label>
<span>Email:</span>
<input name="email" id="email" type="email"
placeholder="Skriv inn din mailadresse"
tabindex="3">
</label>
</div>
<div>
<label>
<span>Telefon: (påkrevd) </span>
<input name="telefon" id="telefon"
placeholder="Skriv inn ditt telefonnummer"
type="tel" tabindex="4"
pattern="[0-9]{8}" title="Må bestå av 8 siffer"
required>
</label>
</div>
<div>
<label>
<span>DOB:</span>
<input name="fdag" id="fdag" type="date"
tabindex="5" required>
</label>
</div>
<div>
<button name="submit" type="submit"
id="kontaktskjema-submit">Send inn</button>
</div>
</form>
</div>
</div>
enter code here
And this i the regex validation,
<?
//preg_match for email
$email = $_POST['email'];
$emailregex = '[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}';
if(isset($_POST['email'])) {
if (!preg_match($emailregex, $email)) {
echo 'invalid email';
}
}
//validating the phone number
$telefon = $_POST ['telefon'];
$telmatch = array('98979695'
,'97969594','90807090','90908080','40908070','45674849','46573823','45343456');
if(isset($_POST['telefon'])){
if(!preg_match($telefon, $telmatch)){
echo 'invalid phone number';
}
}
//validatin the date
$fdag = $_POST['fdag'];
if(isset($_POST['fdag'])) {
if(preg_match('/(0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-^[0-9]{4}$/',
$fdag))
{
if(date(Y, time()) - date(Y,strtotime($fdag)) > 16){
echo 'invalid date';
}
else
{
echo 'you have to be at least 16';
}
}
}
?>
Thursday, 3 October 2013
Wednesday, 2 October 2013
Getting maven webstart plugin to sign only the final jar file
Getting maven webstart plugin to sign only the final jar file
I followed the tutorial on the website for the plugin to the T and it
right now it not only packs and signs my final artefact, it also signs and
packs all the dependencies in the zipfile that is created. Is there any
way I could prevent it from signing and packing my dependencies?
I followed the tutorial on the website for the plugin to the T and it
right now it not only packs and signs my final artefact, it also signs and
packs all the dependencies in the zipfile that is created. Is there any
way I could prevent it from signing and packing my dependencies?
Comparing two words from two lists in python
Comparing two words from two lists in python
I would like to compare words that are in two different lists, so for
example, I have:
['freeze','dog','difficult','answer'] and another list
['freaze','dot','dificult','anser']. I want to compare the words in this
list and give marks for incorrect letters. So, +1 for being correct, and
-1 for one letter wrong. To give some context, in a spelling test, the
first list would be answers, and the second list would be the student's
answers. How would i go about doing this?
I would like to compare words that are in two different lists, so for
example, I have:
['freeze','dog','difficult','answer'] and another list
['freaze','dot','dificult','anser']. I want to compare the words in this
list and give marks for incorrect letters. So, +1 for being correct, and
-1 for one letter wrong. To give some context, in a spelling test, the
first list would be answers, and the second list would be the student's
answers. How would i go about doing this?
updating and searching mysql set using php
updating and searching mysql set using php
I have a column in table which has possible values of tom,john,jerry(SET).
I have a variable that a user enter and I store it in $var and want that
at some point. I could check that if the value in $var exists in
particular row then don't update else update, How I can do this in PHP. I
have several rows like tom,john
john,jerry
I dont want `tom,john,tom`
Any help in this regard
I have a column in table which has possible values of tom,john,jerry(SET).
I have a variable that a user enter and I store it in $var and want that
at some point. I could check that if the value in $var exists in
particular row then don't update else update, How I can do this in PHP. I
have several rows like tom,john
john,jerry
I dont want `tom,john,tom`
Any help in this regard
Determining the range of values returned by Python's hash()
Determining the range of values returned by Python's hash()
I would like to map values returned by Python's hash() function to floats
in the range 0 to 1. On my system I can do this with
scale = 1.0/(2**64)
print hash(some_object)*scale+0.5
However, I know this will be different on 32-bit systems. Most likely I
will never run this code anywhere else, but still I would like to know if
there's a way to programmatically determine the maximum and minimum values
that Python's built-in hash() function can return.
(By the way the reason I'm doing this is that I'm developing a numerical
simulation in which I need to consistently generate the same pseudo-random
number from a given Numpy array. I know the built-in hash won't have the
best statistics for this, but it's fast, so it's convenient to use it for
testing purposes.)
I would like to map values returned by Python's hash() function to floats
in the range 0 to 1. On my system I can do this with
scale = 1.0/(2**64)
print hash(some_object)*scale+0.5
However, I know this will be different on 32-bit systems. Most likely I
will never run this code anywhere else, but still I would like to know if
there's a way to programmatically determine the maximum and minimum values
that Python's built-in hash() function can return.
(By the way the reason I'm doing this is that I'm developing a numerical
simulation in which I need to consistently generate the same pseudo-random
number from a given Numpy array. I know the built-in hash won't have the
best statistics for this, but it's fast, so it's convenient to use it for
testing purposes.)
Tuesday, 1 October 2013
ORA-02270: no matching unique or primary key for this column-list i don't know why
ORA-02270: no matching unique or primary key for this column-list i don't
know why
i tried to create a table with a foreign key to another one but i dont
know why this error keeps poping up every time i try, please help me
CREATE TABLE usuarios( username VARCHAR2(100), cedula VARCHAR2(100),
ultimoAcceso DATE, CONSTRAINT Pk PRIMARY KEY (cedula,username) ) ;
CREATE TABLE pagoPlanillas( ced VARCHAR2(100), fecha DATE, detalle
VARCHAR2(100), salario VARCHAR2(100), CONSTRAINT FK1 FOREIGN KEY(ced)
REFERENCES usuarios(cedula) ) ;
know why
i tried to create a table with a foreign key to another one but i dont
know why this error keeps poping up every time i try, please help me
CREATE TABLE usuarios( username VARCHAR2(100), cedula VARCHAR2(100),
ultimoAcceso DATE, CONSTRAINT Pk PRIMARY KEY (cedula,username) ) ;
CREATE TABLE pagoPlanillas( ced VARCHAR2(100), fecha DATE, detalle
VARCHAR2(100), salario VARCHAR2(100), CONSTRAINT FK1 FOREIGN KEY(ced)
REFERENCES usuarios(cedula) ) ;
remove lines after second pattern sed
remove lines after second pattern sed
I'm looking to trim a file and I need to remove everything after the
second match (and everything before the first match).
For example Say I have this text:
xxx xxx
yyy yyy
New USB device found
xxx xxx
yyy yyy
zzz zzz
New USB device found
xxx xxx
yyy yyy
If I use : sed -i '1,/New USB device found/d' this removes everything
before the first match. which is great:
New USB device found
xxx xxx
yyy yyy
zzz zzz
New USB device found
xxx xxx
yyy yyy
But I'm only 1/2 way there, now I want to remove everything after the 2nd
match to get this result:
New USB device found
xxx xxx
yyy yyy
zzz zzz
Hence just the data for the first device. Can anyone help?
I'm looking to trim a file and I need to remove everything after the
second match (and everything before the first match).
For example Say I have this text:
xxx xxx
yyy yyy
New USB device found
xxx xxx
yyy yyy
zzz zzz
New USB device found
xxx xxx
yyy yyy
If I use : sed -i '1,/New USB device found/d' this removes everything
before the first match. which is great:
New USB device found
xxx xxx
yyy yyy
zzz zzz
New USB device found
xxx xxx
yyy yyy
But I'm only 1/2 way there, now I want to remove everything after the 2nd
match to get this result:
New USB device found
xxx xxx
yyy yyy
zzz zzz
Hence just the data for the first device. Can anyone help?
N people sit at a round table, starting from #1, every other one leaves, who's the last one?
N people sit at a round table, starting from #1, every other one leaves,
who's the last one?
For example, there are 10 people sitting there.
So the 1st round, such people leave: $$\#1, \#3, \#5, \#7, \#9$$ and
remains $$\#2, \#4, \#6, \#8, \#10$$
Then the 2nd round, such people leave: $$\#2, \#6, \#10$$ and remains
$$\#4, \#8$$
Then the 3rd round, such people leave: $$\#8$$ and remains $$\#4$$
so the last one remained is #4.
If we note f(10)=4, how to get a general formula for f(N)?
who's the last one?
For example, there are 10 people sitting there.
So the 1st round, such people leave: $$\#1, \#3, \#5, \#7, \#9$$ and
remains $$\#2, \#4, \#6, \#8, \#10$$
Then the 2nd round, such people leave: $$\#2, \#6, \#10$$ and remains
$$\#4, \#8$$
Then the 3rd round, such people leave: $$\#8$$ and remains $$\#4$$
so the last one remained is #4.
If we note f(10)=4, how to get a general formula for f(N)?
standard deviation in unbiased problem
standard deviation in unbiased problem
For unbiased standard deviation, if there are n types samples then we
divide by (n-1) why? whereas in standard deviation we divide by n. How can
I get the sample is biased or unbiased? source:
https://www.khanacademy.org/math/probability/descriptive-statistics/variance_std_deviation/e/standard_deviation
For unbiased standard deviation, if there are n types samples then we
divide by (n-1) why? whereas in standard deviation we divide by n. How can
I get the sample is biased or unbiased? source:
https://www.khanacademy.org/math/probability/descriptive-statistics/variance_std_deviation/e/standard_deviation
Monday, 30 September 2013
OpenSSH not connecting to IPv6 host unless 'AddressFamily inet6'
OpenSSH not connecting to IPv6 host unless 'AddressFamily inet6'
I have an OpenSSH client and server. Both are running on Debian 7 with
OpenSSH 6.0. I have a VPN established between the two machines, and the
VPN has functional IPv6. It does not have any IPv4.
The frustrating problem is that I can only connect to the server using
IPv6 if I have set the AddressFamily inet6 option in my ssh_config. I
really don't want to have to set this option. It sure seems like I should
be able to set AddressFamily any and have my connections work.
My Working connection over IPv6 looks like this.
working ssh_config
Host test-fw-01 test-fw-01.example.org
HostKeyAlias test-fw-01.example.org
HostName test-fw-01.example.org
AddressFamily inet6
Working console output
# ssh -v test-fw-01.example.org
OpenSSH_6.0p1 Debian-4, OpenSSL 1.0.1e 11 Feb 2013
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 122: Applying options for
test-fw-01.example.org
debug1: /etc/ssh/ssh_config line 370: Applying options for *
debug1: Connecting to test-fw-01.example.org. [2607:fa78:1051:2001::1:26]
port 22.
...
Linux test-fw-01 3.2.0-4-amd64 #1 SMP Debian 3.2.46-1+deb7u1 x86_64
root@test-fw-01:~#
working tcpdump for port 53
# tcpdump -n port 53
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
17:05:27.294506 IP 10.2.4.5.59917 > 10.2.4.51.53: 34233+ AAAA?
test-fw-01.example.org. (59)
17:05:27.295398 IP 10.2.4.51.53 > 10.2.4.5.59917: 34233* 1/0/0 AAAA
2607:fa78:1051:2001::1:26 (87)
17:05:27.295762 IP 10.2.4.5.42664 > 10.2.4.51.53: 42285+ AAAA?
test-fw-01.example.org. (59)
17:05:27.295970 IP 10.2.4.51.53 > 10.2.4.5.42664: 42285 1/0/0 AAAA
2607:fa78:1051:2001::1:26 (87)
When I use AddressFamily any or AddressFamily inet I see this.
broken ssh_config
Host test-fw-01 test-fw-01.example.org
HostKeyAlias test-fw-01.example.org
HostName test-fw-01.example.org
AddressFamily any #supposed to use any?
broken console output
# ssh -v test-fw-01.example.org
OpenSSH_6.0p1 Debian-4, OpenSSL 1.0.1e 11 Feb 2013
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 122: Applying options for
test-fw-01.example.org
debug1: /etc/ssh/ssh_config line 370: Applying options for *
ssh: Could not resolve hostname test-fw-01.example.org.: Name or service
not known
tcpdump for port 53 on broken connection
# tcpdump -n port 53
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
17:03:30.814876 IP 10.2.4.5.33824 > 10.2.4.51.53: 23711+ A?
test-fw-01.esd189.org. (59)
17:03:30.815276 IP 10.2.4.5.33824 > 10.2.4.51.53: 65399+ AAAA?
test-fw-01.esd189.org. (59)
17:03:30.815746 IP 10.2.4.51.53 > 10.2.4.5.33824: 65399* 1/0/0 AAAA
2607:fa78:1051:2001::1:26 (87)
17:03:35.819158 IP 10.2.4.5.33824 > 10.2.4.51.53: 23711+ A?
test-fw-01.esd189.org. (59)
17:03:39.481119 IP 10.2.4.51.53 > 10.2.4.5.33824: 23711 ServFail 0/0/0 (59)
17:03:40.819636 IP 10.2.4.5.33824 > 10.2.4.51.53: 23711+ A?
test-fw-01.esd189.org. (59)
17:03:45.824898 IP 10.2.4.5.51629 > 10.2.4.51.53: 63582+ A?
test-fw-01.esd189.org.esd189.org. (70)
17:03:45.825252 IP 10.2.4.51.53 > 10.2.4.5.51629: 63582 NXDomain* 0/1/0 (137)
17:03:45.825423 IP 10.2.4.5.51629 > 10.2.4.51.53: 12711+ AAAA?
test-fw-01.esd189.org.esd189.org. (70)
17:03:45.825669 IP 10.2.4.51.53 > 10.2.4.5.51629: 12711 NXDomain* 0/1/0 (137)
17:03:45.825874 IP 10.2.4.5.56246 > 10.2.4.51.53: 64150+ A?
test-fw-01.esd189.org.nwesd.org. (69)
17:03:45.826062 IP 10.2.4.51.53 > 10.2.4.5.56246: 64150 NXDomain* 0/1/0 (139)
17:03:45.826177 IP 10.2.4.5.56246 > 10.2.4.51.53: 21391+ AAAA?
test-fw-01.esd189.org.nwesd.org. (69)
17:03:45.826302 IP 10.2.4.51.53 > 10.2.4.5.56246: 21391 NXDomain* 0/1/0 (139)
17:03:49.621048 IP 10.2.4.51.53 > 10.2.4.5.33824: 23711 ServFail 0/0/0 (59)
Dig output for the test server.
# dig -t aaaa @10.2.4.51 test-fw-01.example.org.
; <<>> DiG 9.8.4-rpz2+rl005.12-P1 <<>> -t aaaa @10.2.4.51
test-fw-01.example.org.
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33798
;; flags: qr aa ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;test-fw-01.example.org. IN AAAA
;; ANSWER SECTION:
test-fw-01.example.org. 0 IN AAAA 2607:fa78:1051:2001::1:26
;; Query time: 1 msec
;; SERVER: 10.2.4.51#53(10.2.4.51)
;; WHEN: Mon Sep 30 17:01:41 2013
;; MSG SIZE rcvd: 87
I will have about 70 hosts using this IPv6 VPN. I want to simply put the
AddressFamily any in the Host * section of my ssh_config and then have my
connections get established. I don't want to have to explicitly list all
my IPv6 hosts in my SSH config. There will be no consistent naming pattern
so I can't do something like Host *.ipv6. I don't want to have to type the
-6 to connect via IPv6. Am I missing something obvious? What do I have to
do to get OpenSSH to connect use the IPv6 address since it is available?
I have an OpenSSH client and server. Both are running on Debian 7 with
OpenSSH 6.0. I have a VPN established between the two machines, and the
VPN has functional IPv6. It does not have any IPv4.
The frustrating problem is that I can only connect to the server using
IPv6 if I have set the AddressFamily inet6 option in my ssh_config. I
really don't want to have to set this option. It sure seems like I should
be able to set AddressFamily any and have my connections work.
My Working connection over IPv6 looks like this.
working ssh_config
Host test-fw-01 test-fw-01.example.org
HostKeyAlias test-fw-01.example.org
HostName test-fw-01.example.org
AddressFamily inet6
Working console output
# ssh -v test-fw-01.example.org
OpenSSH_6.0p1 Debian-4, OpenSSL 1.0.1e 11 Feb 2013
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 122: Applying options for
test-fw-01.example.org
debug1: /etc/ssh/ssh_config line 370: Applying options for *
debug1: Connecting to test-fw-01.example.org. [2607:fa78:1051:2001::1:26]
port 22.
...
Linux test-fw-01 3.2.0-4-amd64 #1 SMP Debian 3.2.46-1+deb7u1 x86_64
root@test-fw-01:~#
working tcpdump for port 53
# tcpdump -n port 53
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
17:05:27.294506 IP 10.2.4.5.59917 > 10.2.4.51.53: 34233+ AAAA?
test-fw-01.example.org. (59)
17:05:27.295398 IP 10.2.4.51.53 > 10.2.4.5.59917: 34233* 1/0/0 AAAA
2607:fa78:1051:2001::1:26 (87)
17:05:27.295762 IP 10.2.4.5.42664 > 10.2.4.51.53: 42285+ AAAA?
test-fw-01.example.org. (59)
17:05:27.295970 IP 10.2.4.51.53 > 10.2.4.5.42664: 42285 1/0/0 AAAA
2607:fa78:1051:2001::1:26 (87)
When I use AddressFamily any or AddressFamily inet I see this.
broken ssh_config
Host test-fw-01 test-fw-01.example.org
HostKeyAlias test-fw-01.example.org
HostName test-fw-01.example.org
AddressFamily any #supposed to use any?
broken console output
# ssh -v test-fw-01.example.org
OpenSSH_6.0p1 Debian-4, OpenSSL 1.0.1e 11 Feb 2013
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 122: Applying options for
test-fw-01.example.org
debug1: /etc/ssh/ssh_config line 370: Applying options for *
ssh: Could not resolve hostname test-fw-01.example.org.: Name or service
not known
tcpdump for port 53 on broken connection
# tcpdump -n port 53
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
17:03:30.814876 IP 10.2.4.5.33824 > 10.2.4.51.53: 23711+ A?
test-fw-01.esd189.org. (59)
17:03:30.815276 IP 10.2.4.5.33824 > 10.2.4.51.53: 65399+ AAAA?
test-fw-01.esd189.org. (59)
17:03:30.815746 IP 10.2.4.51.53 > 10.2.4.5.33824: 65399* 1/0/0 AAAA
2607:fa78:1051:2001::1:26 (87)
17:03:35.819158 IP 10.2.4.5.33824 > 10.2.4.51.53: 23711+ A?
test-fw-01.esd189.org. (59)
17:03:39.481119 IP 10.2.4.51.53 > 10.2.4.5.33824: 23711 ServFail 0/0/0 (59)
17:03:40.819636 IP 10.2.4.5.33824 > 10.2.4.51.53: 23711+ A?
test-fw-01.esd189.org. (59)
17:03:45.824898 IP 10.2.4.5.51629 > 10.2.4.51.53: 63582+ A?
test-fw-01.esd189.org.esd189.org. (70)
17:03:45.825252 IP 10.2.4.51.53 > 10.2.4.5.51629: 63582 NXDomain* 0/1/0 (137)
17:03:45.825423 IP 10.2.4.5.51629 > 10.2.4.51.53: 12711+ AAAA?
test-fw-01.esd189.org.esd189.org. (70)
17:03:45.825669 IP 10.2.4.51.53 > 10.2.4.5.51629: 12711 NXDomain* 0/1/0 (137)
17:03:45.825874 IP 10.2.4.5.56246 > 10.2.4.51.53: 64150+ A?
test-fw-01.esd189.org.nwesd.org. (69)
17:03:45.826062 IP 10.2.4.51.53 > 10.2.4.5.56246: 64150 NXDomain* 0/1/0 (139)
17:03:45.826177 IP 10.2.4.5.56246 > 10.2.4.51.53: 21391+ AAAA?
test-fw-01.esd189.org.nwesd.org. (69)
17:03:45.826302 IP 10.2.4.51.53 > 10.2.4.5.56246: 21391 NXDomain* 0/1/0 (139)
17:03:49.621048 IP 10.2.4.51.53 > 10.2.4.5.33824: 23711 ServFail 0/0/0 (59)
Dig output for the test server.
# dig -t aaaa @10.2.4.51 test-fw-01.example.org.
; <<>> DiG 9.8.4-rpz2+rl005.12-P1 <<>> -t aaaa @10.2.4.51
test-fw-01.example.org.
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 33798
;; flags: qr aa ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
;; QUESTION SECTION:
;test-fw-01.example.org. IN AAAA
;; ANSWER SECTION:
test-fw-01.example.org. 0 IN AAAA 2607:fa78:1051:2001::1:26
;; Query time: 1 msec
;; SERVER: 10.2.4.51#53(10.2.4.51)
;; WHEN: Mon Sep 30 17:01:41 2013
;; MSG SIZE rcvd: 87
I will have about 70 hosts using this IPv6 VPN. I want to simply put the
AddressFamily any in the Host * section of my ssh_config and then have my
connections get established. I don't want to have to explicitly list all
my IPv6 hosts in my SSH config. There will be no consistent naming pattern
so I can't do something like Host *.ipv6. I don't want to have to type the
-6 to connect via IPv6. Am I missing something obvious? What do I have to
do to get OpenSSH to connect use the IPv6 address since it is available?
How to crop borders/white spaces from image?
How to crop borders/white spaces from image?
I have a lot of images which have white borders around it. I would like to
crop those borders in one batch, preferably from command line. I believe
that it can be done with ImageMagick, but I couldn't find suitable
command.
I know that it can be done with Windows program named Irfanview with "Auto
crop borders" option, but I am looking for Ubuntu-based and preferably
command-line based solution.
I have a lot of images which have white borders around it. I would like to
crop those borders in one batch, preferably from command line. I believe
that it can be done with ImageMagick, but I couldn't find suitable
command.
I know that it can be done with Windows program named Irfanview with "Auto
crop borders" option, but I am looking for Ubuntu-based and preferably
command-line based solution.
Return odd elements with/without block
Return odd elements with/without block
I'm trying to return odd elements using this method
def odd_elements(array)
retArr = Array.new
array.each_with_index do |item, index|
if block_given?
yield(item)
else
retArr << item
end if index % 2 != 0
end
return retArr
end
so that I could pass both these tests
it "should yield odd elements" do
res = odd_elements([1,2,3,4,5,6])
res.should be_an_instance_of Array
res.should have(3).items
res.should include(2)
res.should include(4)
res.should include(6)
end
it "should yield" do
res = odd_elements([1,2,3,4,5,6]) {|x| x**2 }
res.should be_an_instance_of Array
res.should have(3).items
res[0].should == 4
res[1].should == 16
res[2].should == 36
end
but I'm failing in the second one. It seems I don't understand how to
yield and I didn't manage to get it right in two hours trying so many
different things. Could you please explain me why it does not work?
I'm trying to return odd elements using this method
def odd_elements(array)
retArr = Array.new
array.each_with_index do |item, index|
if block_given?
yield(item)
else
retArr << item
end if index % 2 != 0
end
return retArr
end
so that I could pass both these tests
it "should yield odd elements" do
res = odd_elements([1,2,3,4,5,6])
res.should be_an_instance_of Array
res.should have(3).items
res.should include(2)
res.should include(4)
res.should include(6)
end
it "should yield" do
res = odd_elements([1,2,3,4,5,6]) {|x| x**2 }
res.should be_an_instance_of Array
res.should have(3).items
res[0].should == 4
res[1].should == 16
res[2].should == 36
end
but I'm failing in the second one. It seems I don't understand how to
yield and I didn't manage to get it right in two hours trying so many
different things. Could you please explain me why it does not work?
Looking for a "add input field" button function in my case
Looking for a "add input field" button function in my case
I'm looking for a way to have a button in my form that will add another
text input when clicked, similar to the attachments form in Yahoo Mail.
This way the user can have exactly as many input fields as they need.
Any ideas? Thanks, Luk
Here's my input field : (add.gif is the add.gif add icon for input field &
delete.gid which is remove the input field)
response.Write "<td align='left'><img src=""..\common_pic\add.gif""
border=0><input type='text' value='" & adoRecordset("production_unit") &
"'name='production_unit' size='10'><img src=""..\common_pic\delete.gif""
border=0></td>"
I'm looking for a way to have a button in my form that will add another
text input when clicked, similar to the attachments form in Yahoo Mail.
This way the user can have exactly as many input fields as they need.
Any ideas? Thanks, Luk
Here's my input field : (add.gif is the add.gif add icon for input field &
delete.gid which is remove the input field)
response.Write "<td align='left'><img src=""..\common_pic\add.gif""
border=0><input type='text' value='" & adoRecordset("production_unit") &
"'name='production_unit' size='10'><img src=""..\common_pic\delete.gif""
border=0></td>"
Sunday, 29 September 2013
Allow user post products
Allow user post products
I need to know if I can in prestashop or another eccommerce framework
allow the users to publish his own products.
I ask this because i need that feature to my site.
Thanks in advance !
I need to know if I can in prestashop or another eccommerce framework
allow the users to publish his own products.
I ask this because i need that feature to my site.
Thanks in advance !
How do I transform polygon into rect on hover?
How do I transform polygon into rect on hover?
I would like to create an interactive map of the USA. Whenever a user puts
their mouse over a state, I would like the polygon to transform into a
hovering rectangle filled with information that the user can click. Would
I need to create a rect that is normally invisible until a mouse hovers
over it or is there another way to go about this?
<polygon
points="19,133 81,152 67,210 132,309 134,319 134,330 127,340 126,350
81,348 79,339 79,329 69,322 60,310 46,299
35,296 37,285 24,256 22,247 27,239 20,234 20,226 20,221 19,214 9,195
8,183 8,172 8,166 13,162 15,140"/>
<rect x="33" y="220" rx="20" ry="20" width="250" height="150">
<animateTransform attributeName="x" from="10" to="200" dur="3s"
fill="freeze"/>
<animateTransform attributeName="transform" type="scale" from="0"
to="1" dur="3s"/>
</rect>
I would like to create an interactive map of the USA. Whenever a user puts
their mouse over a state, I would like the polygon to transform into a
hovering rectangle filled with information that the user can click. Would
I need to create a rect that is normally invisible until a mouse hovers
over it or is there another way to go about this?
<polygon
points="19,133 81,152 67,210 132,309 134,319 134,330 127,340 126,350
81,348 79,339 79,329 69,322 60,310 46,299
35,296 37,285 24,256 22,247 27,239 20,234 20,226 20,221 19,214 9,195
8,183 8,172 8,166 13,162 15,140"/>
<rect x="33" y="220" rx="20" ry="20" width="250" height="150">
<animateTransform attributeName="x" from="10" to="200" dur="3s"
fill="freeze"/>
<animateTransform attributeName="transform" type="scale" from="0"
to="1" dur="3s"/>
</rect>
Console states method not available but it seems like it should be
Console states method not available but it seems like it should be
I've got a rails app and I'm trying to add a thumbnail scroller. It prints
the div, but the js is not working. Here's the file:
<div id="tS2" class="jThumbnailScroller">
<div class="jTscrollerContainer">
<div class="jTscroller">
<% @illustrations.each do |illustration| %>
<% if illustration.aws_image_thumbnail_url %>
<%= link_to
image_tag(illustration.aws_image_thumbnail_url, :title =>
illustration.name), illustration %>
<% else %>
<%= link_to image_tag(illustration.image.url(:thumb),
:title => illustration.name), illustration %>
<% end %>
<% end %>
</div>
</div>
</div>
<script>
jQuery.noConflict();
(function($){
window.onload=function(){
$("#tS2").thumbnailScroller({
scrollerType:"hoverPrecise",
scrollerOrientation:"horizontal",
scrollSpeed:2,
scrollEasing:"easeOutCirc",
scrollEasingAmount:600,
acceleration:4,
scrollSpeed:800,
noScrollCenterSpace:10,
autoScrolling:0,
autoScrollingSpeed:2000,
autoScrollingEasing:"easeInOutQuad",
autoScrollingDelay:500
});
}
})(jQuery);
</script>
Here's the error in the console:
Uncaught TypeError: Object [object Object] has no method
'thumbnailScroller' 138:168
window.onload 138:168
window.onload
Here's the thumbnailScroller method within jquery.thumbnailScroller.js:
(function($){
$.fn.thumbnailScroller=function(options){
var defaults={ //default options
scrollerType:"hoverPrecise", //values: "hoverPrecise",
"hoverAccelerate", "clickButtons"
scrollerOrientation:"horizontal", //values: "horizontal", "vertical"
scrollEasing:"easeOutCirc", //easing type
scrollEasingAmount:800, //value: milliseconds
acceleration:2, //value: integer
scrollSpeed:600, //value: milliseconds
noScrollCenterSpace:0, //value: pixels
autoScrolling:0, //value: integer
autoScrollingSpeed:8000, //value: milliseconds
autoScrollingEasing:"easeInOutQuad", //easing type
autoScrollingDelay:2500 //value: milliseconds
};
And here you can see that that js file is being loaded in to the rails app
(output from chrome developmnet tools 'resources' tab:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
...
<link href="/assets/jquery.thumbnailscroller.css?body=1" media="all"
rel="stylesheet" type="text/css" />
...
<script src="/assets/jquery.thumbnailScroller.js?body=1"
type="text/javascript"></script>
...
</head>
Does anyone see why this method is not available?
I've got a rails app and I'm trying to add a thumbnail scroller. It prints
the div, but the js is not working. Here's the file:
<div id="tS2" class="jThumbnailScroller">
<div class="jTscrollerContainer">
<div class="jTscroller">
<% @illustrations.each do |illustration| %>
<% if illustration.aws_image_thumbnail_url %>
<%= link_to
image_tag(illustration.aws_image_thumbnail_url, :title =>
illustration.name), illustration %>
<% else %>
<%= link_to image_tag(illustration.image.url(:thumb),
:title => illustration.name), illustration %>
<% end %>
<% end %>
</div>
</div>
</div>
<script>
jQuery.noConflict();
(function($){
window.onload=function(){
$("#tS2").thumbnailScroller({
scrollerType:"hoverPrecise",
scrollerOrientation:"horizontal",
scrollSpeed:2,
scrollEasing:"easeOutCirc",
scrollEasingAmount:600,
acceleration:4,
scrollSpeed:800,
noScrollCenterSpace:10,
autoScrolling:0,
autoScrollingSpeed:2000,
autoScrollingEasing:"easeInOutQuad",
autoScrollingDelay:500
});
}
})(jQuery);
</script>
Here's the error in the console:
Uncaught TypeError: Object [object Object] has no method
'thumbnailScroller' 138:168
window.onload 138:168
window.onload
Here's the thumbnailScroller method within jquery.thumbnailScroller.js:
(function($){
$.fn.thumbnailScroller=function(options){
var defaults={ //default options
scrollerType:"hoverPrecise", //values: "hoverPrecise",
"hoverAccelerate", "clickButtons"
scrollerOrientation:"horizontal", //values: "horizontal", "vertical"
scrollEasing:"easeOutCirc", //easing type
scrollEasingAmount:800, //value: milliseconds
acceleration:2, //value: integer
scrollSpeed:600, //value: milliseconds
noScrollCenterSpace:0, //value: pixels
autoScrolling:0, //value: integer
autoScrollingSpeed:8000, //value: milliseconds
autoScrollingEasing:"easeInOutQuad", //easing type
autoScrollingDelay:2500 //value: milliseconds
};
And here you can see that that js file is being loaded in to the rails app
(output from chrome developmnet tools 'resources' tab:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
...
<link href="/assets/jquery.thumbnailscroller.css?body=1" media="all"
rel="stylesheet" type="text/css" />
...
<script src="/assets/jquery.thumbnailScroller.js?body=1"
type="text/javascript"></script>
...
</head>
Does anyone see why this method is not available?
Parse shortcode to array
Parse shortcode to array
i need to parse WordPress shortcode to array, in php, for example:
[parrent_shortcode attribute='1' attribute2='a']
[shortcode atrribute1=true attribute2=true]This is first
content[/shortcode]
[shortcode atrribute1=false]This is second content[/shortcode]
[/parrent_shortcode]
to become:
Array(
[name] => 'parrent_shortcode'
[atts] => Array(
[attribute] => '1'
[attribute2] => 'a'
)
[content] => Array(
[child1] => Array(
[name] => 'shortcode'
[atts] => Array(
[atrribute1] => true
[attribute2] => true
)
[content] => 'This is first content'
)
[child2] => Array(
[name] => 'shortcode'
[atts] => Array(
[atrribute1] => false
)
[content] => 'This is second content'
)
)
)
Also shortcodes can be without parrent wrapper and can be single
(selfclosing) without content. Also attribute can have spaces in it.
I try to accomplish it using explode but ther are so many combinations..
i need to parse WordPress shortcode to array, in php, for example:
[parrent_shortcode attribute='1' attribute2='a']
[shortcode atrribute1=true attribute2=true]This is first
content[/shortcode]
[shortcode atrribute1=false]This is second content[/shortcode]
[/parrent_shortcode]
to become:
Array(
[name] => 'parrent_shortcode'
[atts] => Array(
[attribute] => '1'
[attribute2] => 'a'
)
[content] => Array(
[child1] => Array(
[name] => 'shortcode'
[atts] => Array(
[atrribute1] => true
[attribute2] => true
)
[content] => 'This is first content'
)
[child2] => Array(
[name] => 'shortcode'
[atts] => Array(
[atrribute1] => false
)
[content] => 'This is second content'
)
)
)
Also shortcodes can be without parrent wrapper and can be single
(selfclosing) without content. Also attribute can have spaces in it.
I try to accomplish it using explode but ther are so many combinations..
Saturday, 28 September 2013
Modifying my SharePoint upper ribbon boarder color is not working well
Modifying my SharePoint upper ribbon boarder color is not working well
I have a Ribbon in side my SharePoint , which have different board color,
depending on the tab i am displaying, so i want to have the ribbon boarder
to always be blue. So using Firebug i have detected the classes which is
responsible for the ribbon as follow:-
I added the following code to my cusotm CSS:-
.ms-cui-tabBody{
border-color:#008CD2 #008CD2 #008CD2 #008CD2 !important;
border-top-color:#008CD2 !important;
}
.ms-cui-tabBody.ms-cui-tabBody-gr{
border-color:#008CD2 #008CD2 #008CD2 #008CD2 !important;
border-top-color:#008CD2 !important;
}
But unfortunately this has changed only the buttom boarder colour to be
blue, while the "Calendar" tab still have green upper boarder, and "Page
Option" tab have no upper boarder color ? can anyone advice on how I can
change the boarder to be all blue? Thanks.
I have a Ribbon in side my SharePoint , which have different board color,
depending on the tab i am displaying, so i want to have the ribbon boarder
to always be blue. So using Firebug i have detected the classes which is
responsible for the ribbon as follow:-
I added the following code to my cusotm CSS:-
.ms-cui-tabBody{
border-color:#008CD2 #008CD2 #008CD2 #008CD2 !important;
border-top-color:#008CD2 !important;
}
.ms-cui-tabBody.ms-cui-tabBody-gr{
border-color:#008CD2 #008CD2 #008CD2 #008CD2 !important;
border-top-color:#008CD2 !important;
}
But unfortunately this has changed only the buttom boarder colour to be
blue, while the "Calendar" tab still have green upper boarder, and "Page
Option" tab have no upper boarder color ? can anyone advice on how I can
change the boarder to be all blue? Thanks.
C# regex building
C# regex building
I have an encode string in my C# web app:
<a href="/product.aspx?zpid=564">Item One </a>-10 -
10<br /><a href="/product.aspx?zpid=647">Item Two
</a>-1 - 1<br /> <br />
That is decoded to:
"<a href=\"/product.aspx?zpid=564\">American Arborvitae</a>-10 - 10<br
/><a href=\"/product.aspx?zpid=647\">Black Walnut </a>-1 - 1<br /> <br />"
Is there a relatively easy way to use a regex to get the values between
the </a>-10 - 10<br /> and </a>-1 - 1<br />? I am not really the best at
building regexes and I am not sure really how to define a pattern for
something like this. Or can the values be put into a string array easier?
The number of entries can vary between like 1-30.
I have an encode string in my C# web app:
<a href="/product.aspx?zpid=564">Item One </a>-10 -
10<br /><a href="/product.aspx?zpid=647">Item Two
</a>-1 - 1<br /> <br />
That is decoded to:
"<a href=\"/product.aspx?zpid=564\">American Arborvitae</a>-10 - 10<br
/><a href=\"/product.aspx?zpid=647\">Black Walnut </a>-1 - 1<br /> <br />"
Is there a relatively easy way to use a regex to get the values between
the </a>-10 - 10<br /> and </a>-1 - 1<br />? I am not really the best at
building regexes and I am not sure really how to define a pattern for
something like this. Or can the values be put into a string array easier?
The number of entries can vary between like 1-30.
techgig july edition part 3
techgig july edition part 3
There is problem statement on techgig :
Davis is playing a very interesting mathematical game. He has collection
of sticks of length 1,2,3,....,N. He is making hexagon out of his
collection by using 6 sticks for each hexagon. He considers a hexagon
"good" if the biggest stick has length at least L and lengths of all the
other sticks are not more than X. A "good" hexagon does not have sticks of
the same length more than K times.
How many ways he can make a "Good" hexagon?
Input/Output Specifications Input Specification: Input contains four
integers-
N( 2 <= N <= 10^9)
L ( 2 <= L <= N and N-L<=100)
X( 1<=X< L )
K ( 1 <= K <= 5)
Output Specification: Output the number of different ways to make a "Good"
hexagon % 1000000007
Examples
Example:1 when N=8, L=7, X=5, K=3: { 1,2,2,5,5,7 } is a good hexagon but
{1,2,2,2,2,7}, { 1,2,3,4,5,6},{1,2,3,4,6,7} are not.Two hexagons are
considered different if their side length sets are different.
For example {1,2,3,4,5,6} , {1,1,1,2,2,3} and {1,1,2,2,2,3} are all
different hexagons. But {1,2,3,4,5,6} and { 2,4,6,1,3,5} are not
different.
Example:2 When N=10, L=8, X=6, K=2 Output: Total hexagons= 374
Note: Please return -1 for invalid cases.
I am trying to solve it by calculating different combinations and adding
it together, my approach(probably wrong) is as below :
def factorial(x):
if x<=1:
return 1
else:
return x*factorial(x-1)
def combination(n,r):
return (factorial(n)/(factorial(n-r)*factorial(r)))
def goodHexa(N,L,X,K):
a=combination(N-L+1,1)
c=0
if K>=1: #total no. of combination without repeating any number
b=combination(X,5)
print b
if K>=2:
b+=combination(X,3)*3 #one number occurs twice
print b
b+=combination(X,4)*4 #two number occurs twice
print b
if K>=3:
b+=combination(X,2)*2 #one number occurs 3 times and one 2 times
b+=combination(X,3)*3 #one number occurs 3 times
if K>=4:
b+=combination(X,2)*2 #one number occurs 4 times
if K>=5:
b+=X #one number occurs 5 times
return (a*b)
what is wrong in my approach? what are other ways to solve this problem ?
There is problem statement on techgig :
Davis is playing a very interesting mathematical game. He has collection
of sticks of length 1,2,3,....,N. He is making hexagon out of his
collection by using 6 sticks for each hexagon. He considers a hexagon
"good" if the biggest stick has length at least L and lengths of all the
other sticks are not more than X. A "good" hexagon does not have sticks of
the same length more than K times.
How many ways he can make a "Good" hexagon?
Input/Output Specifications Input Specification: Input contains four
integers-
N( 2 <= N <= 10^9)
L ( 2 <= L <= N and N-L<=100)
X( 1<=X< L )
K ( 1 <= K <= 5)
Output Specification: Output the number of different ways to make a "Good"
hexagon % 1000000007
Examples
Example:1 when N=8, L=7, X=5, K=3: { 1,2,2,5,5,7 } is a good hexagon but
{1,2,2,2,2,7}, { 1,2,3,4,5,6},{1,2,3,4,6,7} are not.Two hexagons are
considered different if their side length sets are different.
For example {1,2,3,4,5,6} , {1,1,1,2,2,3} and {1,1,2,2,2,3} are all
different hexagons. But {1,2,3,4,5,6} and { 2,4,6,1,3,5} are not
different.
Example:2 When N=10, L=8, X=6, K=2 Output: Total hexagons= 374
Note: Please return -1 for invalid cases.
I am trying to solve it by calculating different combinations and adding
it together, my approach(probably wrong) is as below :
def factorial(x):
if x<=1:
return 1
else:
return x*factorial(x-1)
def combination(n,r):
return (factorial(n)/(factorial(n-r)*factorial(r)))
def goodHexa(N,L,X,K):
a=combination(N-L+1,1)
c=0
if K>=1: #total no. of combination without repeating any number
b=combination(X,5)
print b
if K>=2:
b+=combination(X,3)*3 #one number occurs twice
print b
b+=combination(X,4)*4 #two number occurs twice
print b
if K>=3:
b+=combination(X,2)*2 #one number occurs 3 times and one 2 times
b+=combination(X,3)*3 #one number occurs 3 times
if K>=4:
b+=combination(X,2)*2 #one number occurs 4 times
if K>=5:
b+=X #one number occurs 5 times
return (a*b)
what is wrong in my approach? what are other ways to solve this problem ?
format 12 by 12 multiplication table
format 12 by 12 multiplication table
My program outputs the table like this:
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
I need to make it look a little better. Need your help.
This is my code:
int a;
int b;
for (a=1; a<=12; ++a)
{
for (b=1; b<=12; ++b)
{
System.out.print(a*b+" ");
}
System.out.println();
}
My program outputs the table like this:
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144
I need to make it look a little better. Need your help.
This is my code:
int a;
int b;
for (a=1; a<=12; ++a)
{
for (b=1; b<=12; ++b)
{
System.out.print(a*b+" ");
}
System.out.println();
}
Friday, 27 September 2013
How do you create SSL socket factory in new Apache Http Client 4.3?
How do you create SSL socket factory in new Apache Http Client 4.3?
How do you create SSL socket factory in new Apache Http Client 4.3 ?
Here is how I was creating it before 4.3
val ts = new TrustStrategy() {
def isTrusted(chain: Array[X509Certificate], authType: String): Boolean
= true
}
new SSLSocketFactory(ts, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
Now SSLSocketFactory marked as deprecated. What is the new way of defining
custom TrustStrategy ? I couldn't figure it out.
How do you create SSL socket factory in new Apache Http Client 4.3 ?
Here is how I was creating it before 4.3
val ts = new TrustStrategy() {
def isTrusted(chain: Array[X509Certificate], authType: String): Boolean
= true
}
new SSLSocketFactory(ts, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
Now SSLSocketFactory marked as deprecated. What is the new way of defining
custom TrustStrategy ? I couldn't figure it out.
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given [duplicate]
Warning: mysql_num_rows() expects parameter 1 to be resource, boolean
given [duplicate]
This question already has an answer here:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in
select 21 answers
I don't know why it keeps telling me
mysql_num_rows() expects parameter 1 to be resource, boolean given in
C:\xampp\htdocs\schedule2\course.php on line 44
if(isset ($_POST['course']) && isset($_POST['coursedesc']))
{
$course = $_POST['course'];
$coursedesc = $_POST['coursedesc'];
$query = mysql_query("SELECT * FROM ".tblurser." WHERE CourseCode
='".$course."' and CourseDescription = '".$coursedesc."'");
if(mysql_num_rows($query) > 0)
{
echo"<script>alert('Data already exist.');</script>";
}else{
if(empty($course) or empty($coursedesc))
{
echo "<script>
alert(\"all fields are
required \");
</script>";
}else{
if(mysql_query("INSERT INTO tblcourse
VALUES('','$course','$coursedesc')"))
{
}ELSE{
echo"<script>
alert(\"Please try again\");
</script>";
}
}
}
}
given [duplicate]
This question already has an answer here:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in
select 21 answers
I don't know why it keeps telling me
mysql_num_rows() expects parameter 1 to be resource, boolean given in
C:\xampp\htdocs\schedule2\course.php on line 44
if(isset ($_POST['course']) && isset($_POST['coursedesc']))
{
$course = $_POST['course'];
$coursedesc = $_POST['coursedesc'];
$query = mysql_query("SELECT * FROM ".tblurser." WHERE CourseCode
='".$course."' and CourseDescription = '".$coursedesc."'");
if(mysql_num_rows($query) > 0)
{
echo"<script>alert('Data already exist.');</script>";
}else{
if(empty($course) or empty($coursedesc))
{
echo "<script>
alert(\"all fields are
required \");
</script>";
}else{
if(mysql_query("INSERT INTO tblcourse
VALUES('','$course','$coursedesc')"))
{
}ELSE{
echo"<script>
alert(\"Please try again\");
</script>";
}
}
}
}
Echo out the PHP Function Or Return?
Echo out the PHP Function Or Return?
I am not good with functions and classes in PHP. I am echoing a function
instead of return because it gives me desired results. But it also echo
out the result value to my desired page. This function is in class. Just
see this screenshot and you will understand what i want.
Echo out the total numbers:
<?php
echo $results->get_total_marks_subjects($subject_detail['subject_id']);
?>
Here is function code in class:
while($rec = mysql_fetch_array($link)) {
//i think the code below echoes out that message.
echo $rec['total_marks']." | ";
//return $rec['total_marks'];
}
}
I am not good with functions and classes in PHP. I am echoing a function
instead of return because it gives me desired results. But it also echo
out the result value to my desired page. This function is in class. Just
see this screenshot and you will understand what i want.
Echo out the total numbers:
<?php
echo $results->get_total_marks_subjects($subject_detail['subject_id']);
?>
Here is function code in class:
while($rec = mysql_fetch_array($link)) {
//i think the code below echoes out that message.
echo $rec['total_marks']." | ";
//return $rec['total_marks'];
}
}
ASP.NET C# - NavigateURL with RecordID combine
ASP.NET C# - NavigateURL with RecordID combine
I am new to ASP.NET. What I try to do is very basic, but I couldn't get it
to work. If you see the NavigateURL link below, I try to combine the URL
with "RefNum" from the database Recordset, but it keeps failing with "The
server tag is not well formed." error.
I am not sure how to combine the URL with a record from recordset.
Please help, Thanks.
<asp:TemplateField HeaderText="UploadDate" SortExpression="UploadDate"
HeaderStyle-ForeColor="White" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HyperLink
ID="HyperLink1"
runat="server" ForeColor="Blue"
Text='<%# Eval("UploadDate") %>'
NavigateUrl="/ASPX/UploadContact/UploadContact.aspx?RefNum='<%#
Bind("RefNum")%>'"
/>
</ItemTemplate>
</asp:TemplateField>
I am new to ASP.NET. What I try to do is very basic, but I couldn't get it
to work. If you see the NavigateURL link below, I try to combine the URL
with "RefNum" from the database Recordset, but it keeps failing with "The
server tag is not well formed." error.
I am not sure how to combine the URL with a record from recordset.
Please help, Thanks.
<asp:TemplateField HeaderText="UploadDate" SortExpression="UploadDate"
HeaderStyle-ForeColor="White" ItemStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:HyperLink
ID="HyperLink1"
runat="server" ForeColor="Blue"
Text='<%# Eval("UploadDate") %>'
NavigateUrl="/ASPX/UploadContact/UploadContact.aspx?RefNum='<%#
Bind("RefNum")%>'"
/>
</ItemTemplate>
</asp:TemplateField>
Configuring biplot in Matlab to distinguish in scatter
Configuring biplot in Matlab to distinguish in scatter
My original data is a 195x22 record set containing vocal measurements of
people having Parkinson's disease or not. In a vector, 195x1, I have a
status which is either 1/0.
Now, I have performed a PCA and I do a biplot, which turns out well. The
problem is that I can't tell which dots from my scatter plot origin of a
sick or a healthy person (I can't link it with status). I would like for
my scatter plot to have a red dot if healthy (status=0) and green if sick
(status=1).
How would I do that? My biplot code is:
biplot(coeff(:,1:2), ...
'Scores', score(:,1:2), ...
'VarLabels', Labels, ...
'markersize', 15 ...
);
xlabel('Bi-Plot: Standardized Data');
xlabel('PCA1');
ylabel('PCA2');
My original data is a 195x22 record set containing vocal measurements of
people having Parkinson's disease or not. In a vector, 195x1, I have a
status which is either 1/0.
Now, I have performed a PCA and I do a biplot, which turns out well. The
problem is that I can't tell which dots from my scatter plot origin of a
sick or a healthy person (I can't link it with status). I would like for
my scatter plot to have a red dot if healthy (status=0) and green if sick
(status=1).
How would I do that? My biplot code is:
biplot(coeff(:,1:2), ...
'Scores', score(:,1:2), ...
'VarLabels', Labels, ...
'markersize', 15 ...
);
xlabel('Bi-Plot: Standardized Data');
xlabel('PCA1');
ylabel('PCA2');
php return wrong value
php return wrong value
I am trying to calculate this in php :
echo (int)((0.1 + 0.7) * 20);
why it return 15
Expected result: 16
Actual result:15
I am trying to calculate this in php :
echo (int)((0.1 + 0.7) * 20);
why it return 15
Expected result: 16
Actual result:15
Thursday, 26 September 2013
Maven wsdl generation memmory consuption
Maven wsdl generation memmory consuption
During maven build, I have also wsdl generation process that generate
sources from wsdl file. During this generation java (maven) process can
take about 850 Mb. Is there way to reduce this consumption?
During maven build, I have also wsdl generation process that generate
sources from wsdl file. During this generation java (maven) process can
take about 850 Mb. Is there way to reduce this consumption?
Thursday, 19 September 2013
How to print a list without it showing brackets and "" in the output ? Python 3.3.2
How to print a list without it showing brackets and "" in the output ?
Python 3.3.2
So say I have a list named myList and it looks something like this :
myList = ["a", "b", "c"]
How would you print it to the screen so it prints :
abc (yes, no space inbetween)
If I use print (myList) It prints the following:
['a', 'b', 'c']
Help would be much appreciated.
Python 3.3.2
So say I have a list named myList and it looks something like this :
myList = ["a", "b", "c"]
How would you print it to the screen so it prints :
abc (yes, no space inbetween)
If I use print (myList) It prints the following:
['a', 'b', 'c']
Help would be much appreciated.
Setting up loops in a query and/or array
Setting up loops in a query and/or array
This may be my most advanced question yet. Using the stupid Hill climb
game to learn more mySql and php.
`$varVeh=$_POST['Veh_num'];
$sql_HiScores = "SELECT c.course_name as course, e.distance as distance,
e.score as score
from hc_entries e
left join hc_course c on e.course=c.course_num
WHERE e.vehicle=$varVeh
ORDER BY score DESC";
$result_HiScores = mysql_query($sql_HiScores);
echo "<table>";
while($row = mysql_fetch_array($result_HiScores))
{
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
}
echo "</table>";`
I would get this table...
Best Scores for Jeep Course Score Distance Desert 123060 1825 Desert
105760 1661 Desert 86865 1499 Desert 79555 1375 Desert 64434 1254 Desert
53212 1157 Desert 52144 1201 Countryside 57890 1342 Countryside 48455 1303
Countryside 18770 888 Countryside 7275 519 Countryside 6555 525
So I want to get fancy :) and not sure how to do it.
Suppose I want to display the top 5 scores per course. So the last few
Desert is no longer displayed. Also there is a lot more courses as well.
Where would I begin on this?
This may be my most advanced question yet. Using the stupid Hill climb
game to learn more mySql and php.
`$varVeh=$_POST['Veh_num'];
$sql_HiScores = "SELECT c.course_name as course, e.distance as distance,
e.score as score
from hc_entries e
left join hc_course c on e.course=c.course_num
WHERE e.vehicle=$varVeh
ORDER BY score DESC";
$result_HiScores = mysql_query($sql_HiScores);
echo "<table>";
while($row = mysql_fetch_array($result_HiScores))
{
echo "<tr>";
echo "<td>" .$row['course'] . "</td>";
echo "<td>" .$row['score'] . "</td>";
echo "<td>" .$row['distance'] . "</td>";
}
echo "</table>";`
I would get this table...
Best Scores for Jeep Course Score Distance Desert 123060 1825 Desert
105760 1661 Desert 86865 1499 Desert 79555 1375 Desert 64434 1254 Desert
53212 1157 Desert 52144 1201 Countryside 57890 1342 Countryside 48455 1303
Countryside 18770 888 Countryside 7275 519 Countryside 6555 525
So I want to get fancy :) and not sure how to do it.
Suppose I want to display the top 5 scores per course. So the last few
Desert is no longer displayed. Also there is a lot more courses as well.
Where would I begin on this?
how to get the appropriate version of pip
how to get the appropriate version of pip
Problem
I can't seem to get my packages to install to the correct site-packages
directory.
Background
I wanted to upgrade to python 3.3 but I found that I still need python2.6
in order to use yum (it isn't configured for python3). And so I have both
on my system.
Separate pip and easy_install for each version???
The issue is that when I download a package, and run "python setup.py
install" I find that it is installed in python2.6. I have tried using pip
and easy_install but they do the same. I have read that a solution is to
have different versions of pip (pip_2.6 and pip_3.3). But I can't find a
way to download the separate versions. One work around is to give the "-d
PathToSitePackages" argument in pip but this is inelegant.
other programs not using the newer version
Another issue is that I find that when I use systems such as sphinx, they
use the old version of python. I can't seem to figure out how to get them
to use the newer version of python.
Problem
I can't seem to get my packages to install to the correct site-packages
directory.
Background
I wanted to upgrade to python 3.3 but I found that I still need python2.6
in order to use yum (it isn't configured for python3). And so I have both
on my system.
Separate pip and easy_install for each version???
The issue is that when I download a package, and run "python setup.py
install" I find that it is installed in python2.6. I have tried using pip
and easy_install but they do the same. I have read that a solution is to
have different versions of pip (pip_2.6 and pip_3.3). But I can't find a
way to download the separate versions. One work around is to give the "-d
PathToSitePackages" argument in pip but this is inelegant.
other programs not using the newer version
Another issue is that I find that when I use systems such as sphinx, they
use the old version of python. I can't seem to figure out how to get them
to use the newer version of python.
Multiple dropdowns with dependancy
Multiple dropdowns with dependancy
I want to display 4 dropdowns, the items in each dropdown, depends on
selected item in previous dropdown.
I want to implement everything in javascript, meaning the servlet should
access DB (everything is stored in one reference table, where a column
"represents" a dropwdown ) only once and fetch all the relevant data.
The maximum number of possible combinations is about 9k.
How can I achieve that?
I guess the main problem is the data structure that should be used for
this. Maybe use of nested Maps?
I want to display 4 dropdowns, the items in each dropdown, depends on
selected item in previous dropdown.
I want to implement everything in javascript, meaning the servlet should
access DB (everything is stored in one reference table, where a column
"represents" a dropwdown ) only once and fetch all the relevant data.
The maximum number of possible combinations is about 9k.
How can I achieve that?
I guess the main problem is the data structure that should be used for
this. Maybe use of nested Maps?
Copy C Struct with char pointer
Copy C Struct with char pointer
Firstly, I am really sorry if this has already been asked and resolved - I
have spent ages searching and trying to adapt code samples to give me what
I need... but sadly to no avail. Essentially I am just trying to copy the
contents of one struct to another (which is documented here elsewhere but
I cannot get it to work).
A scanner populates the following struct when it reads a barcode:
struct barcode
{
char *text;
int length;
int id;
int min;
int max;
};
This is instantiated as:
static struct barcode code = {0};
I instantiate another one of the same type:
struct barcode *barcodeHolder;
This is intended to store a copy of the scanned barcode. This is because
other codes will then be scanned that indicated other steps such as
barcodes to indicate numbers or stages (eg. end, start, etc). Once I want
to write the struct contents to disk I use the "copy" of the struct as
that is what I want.
However, the char *text property always equals 'c' and not the value of
the barcode.
I copy them as follows:
barcodeHolder = malloc(sizeof(code));
barcodeHolder->text = malloc(strlen(code->text) + 1);
strcpy(barcodeHolder->text, code->text);
barcodeHolder->id = code->id;
barcodeHolder->length = code->length;
barcodeHolder->max = code->max;
barcodeHolder->min = code->min;
This is what I have got from other posts on a similar topic.
However, I am clearly doing something stupidly wrong and would welcome any
help anyone might be able to offer so that my copy of the struct text
element does actually get the right value copied.
Thank you!
Firstly, I am really sorry if this has already been asked and resolved - I
have spent ages searching and trying to adapt code samples to give me what
I need... but sadly to no avail. Essentially I am just trying to copy the
contents of one struct to another (which is documented here elsewhere but
I cannot get it to work).
A scanner populates the following struct when it reads a barcode:
struct barcode
{
char *text;
int length;
int id;
int min;
int max;
};
This is instantiated as:
static struct barcode code = {0};
I instantiate another one of the same type:
struct barcode *barcodeHolder;
This is intended to store a copy of the scanned barcode. This is because
other codes will then be scanned that indicated other steps such as
barcodes to indicate numbers or stages (eg. end, start, etc). Once I want
to write the struct contents to disk I use the "copy" of the struct as
that is what I want.
However, the char *text property always equals 'c' and not the value of
the barcode.
I copy them as follows:
barcodeHolder = malloc(sizeof(code));
barcodeHolder->text = malloc(strlen(code->text) + 1);
strcpy(barcodeHolder->text, code->text);
barcodeHolder->id = code->id;
barcodeHolder->length = code->length;
barcodeHolder->max = code->max;
barcodeHolder->min = code->min;
This is what I have got from other posts on a similar topic.
However, I am clearly doing something stupidly wrong and would welcome any
help anyone might be able to offer so that my copy of the struct text
element does actually get the right value copied.
Thank you!
A few questions about node.js
A few questions about node.js
Am I right in thinking that node.js is a "total" development platform, in
much the same way as asp.NET, PHP and even classic ASP are?
There seems to be a lot of excitement about node.js which makes me a
little nervious about it being yet another "flash in the pan" type
technology that will fade away?
If I was going to go about learning node.js have you got any tips how I
might start out, without frying my brian?
Am I right in thinking that node.js is a "total" development platform, in
much the same way as asp.NET, PHP and even classic ASP are?
There seems to be a lot of excitement about node.js which makes me a
little nervious about it being yet another "flash in the pan" type
technology that will fade away?
If I was going to go about learning node.js have you got any tips how I
might start out, without frying my brian?
Java: changing variable of calling thread
Java: changing variable of calling thread
I have the following code:
public class Shell {
String status;
public void runCmd(final String cmd,String status) throws Exception{
this.status = status;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
process = rtime.exec(cmd);
process.waitFor();
this.status = "check out done";
} catch (IOException e) {
} catch (InterruptedException e) {
}
}
});
t.start();
}
}
but java doesn't let me change the status variable inside the new thread
t.May be I need some sort of inter thread communication.I am new to
threads,please tell me how to do this.
I have the following code:
public class Shell {
String status;
public void runCmd(final String cmd,String status) throws Exception{
this.status = status;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
process = rtime.exec(cmd);
process.waitFor();
this.status = "check out done";
} catch (IOException e) {
} catch (InterruptedException e) {
}
}
});
t.start();
}
}
but java doesn't let me change the status variable inside the new thread
t.May be I need some sort of inter thread communication.I am new to
threads,please tell me how to do this.
Open an image from asset folder in android
Open an image from asset folder in android
I need to get the images from asset folder by specifying the name of the
image and set it to Drawable.
drw =
Drawable.createFromStream(getAssets().open("/assets/images/"+drawables[i]),null);
But I get File not found exception.(images is subfolder of assets and
drawables[i]- name of the image(say "ball.jpg").
I need to get the images from asset folder by specifying the name of the
image and set it to Drawable.
drw =
Drawable.createFromStream(getAssets().open("/assets/images/"+drawables[i]),null);
But I get File not found exception.(images is subfolder of assets and
drawables[i]- name of the image(say "ball.jpg").
Wednesday, 18 September 2013
UIApplicationDidBecomeActiveNotification filter notifications
UIApplicationDidBecomeActiveNotification filter notifications
I registered my main view controller for listening to
UIApplicationDidBecomeActiveNotification because I want to display a
UIAlertView each time the user enters my app :
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(someMethod:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
It's working like a charm, my only problem is if my app gets interrupted
(by an UIAletView, such as a calendar event, or a popup asking for picture
access confirmation), the notification gets called once the alert view's
dismissed.
Any idea on how to detect ONLY when my app comes back from background mode ?
I registered my main view controller for listening to
UIApplicationDidBecomeActiveNotification because I want to display a
UIAlertView each time the user enters my app :
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(someMethod:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
It's working like a charm, my only problem is if my app gets interrupted
(by an UIAletView, such as a calendar event, or a popup asking for picture
access confirmation), the notification gets called once the alert view's
dismissed.
Any idea on how to detect ONLY when my app comes back from background mode ?
How long does a GCal AuthSubHttpClient token last?
How long does a GCal AuthSubHttpClient token last?
I've integrated the Google Calendar API and am able to retrieve the token
returned when a use grants access to their calendar, then using this token
I call:
getAuthSubHttpClient($token);
I then store the resulting string in the database. I am then able to use
this string as the client variable to push events to the users calendar.
My question is, will this expire at some point and I'll no longer be able
to push events to the users calendar? If so how can I get permanent
access?
I've integrated the Google Calendar API and am able to retrieve the token
returned when a use grants access to their calendar, then using this token
I call:
getAuthSubHttpClient($token);
I then store the resulting string in the database. I am then able to use
this string as the client variable to push events to the users calendar.
My question is, will this expire at some point and I'll no longer be able
to push events to the users calendar? If so how can I get permanent
access?
Using a workbook with VBA to open a saved workbook, modify that pre-existing workbook, save and close
Using a workbook with VBA to open a saved workbook, modify that
pre-existing workbook, save and close
I am fairly novice to VBA and am looking for some help. I would like to be
able to run a VBA command in an excel workbook that will call open a
saved, existing workbook, at a specified location (Desktop\ThisBook.xlsx).
After opening the ThisBook.xlsx, the command will take numerical values
from specified cells in the VBA workbok (A1), add them an existing cell in
ThisBook.xlsx (something like ThisBook.xlsx A1 = ThisBook.xlsx A1 +
ActiveDocument A1) and save them where the ThisBook.xlsx data was.
Finally, overwrite the previous save file for ThisBook.xlsx and overwrite
the new data.
Thanks in advance for any help or direction.
pre-existing workbook, save and close
I am fairly novice to VBA and am looking for some help. I would like to be
able to run a VBA command in an excel workbook that will call open a
saved, existing workbook, at a specified location (Desktop\ThisBook.xlsx).
After opening the ThisBook.xlsx, the command will take numerical values
from specified cells in the VBA workbok (A1), add them an existing cell in
ThisBook.xlsx (something like ThisBook.xlsx A1 = ThisBook.xlsx A1 +
ActiveDocument A1) and save them where the ThisBook.xlsx data was.
Finally, overwrite the previous save file for ThisBook.xlsx and overwrite
the new data.
Thanks in advance for any help or direction.
sql query to match all row with other row on same table
sql query to match all row with other row on same table
I have a table that hold my products and services. I want to match every
product with my services than i will assign base price to my services
according to my product.
My table is as follows
ID TypeID Title
=========================
1 1 Product1
2 1 Product2
3 1 Product3
4 2 Service1
5 2 Service2
6 2 Service3
I want this table to return.
ProductID ServiceID ProductTitle ServiceTitle
=========================================================
1 4 Product1 Service1
1 5 Product1 Service2
1 6 Product1 Service3
2 4 Product2 Service1
2 5 Product2 Service2
2 6 Product2 Service3
3 4 Product3 Service1
3 5 Product3 Service2
3 6 Product3 Service3
how can i do that with Ms SQL 2008??
I have a table that hold my products and services. I want to match every
product with my services than i will assign base price to my services
according to my product.
My table is as follows
ID TypeID Title
=========================
1 1 Product1
2 1 Product2
3 1 Product3
4 2 Service1
5 2 Service2
6 2 Service3
I want this table to return.
ProductID ServiceID ProductTitle ServiceTitle
=========================================================
1 4 Product1 Service1
1 5 Product1 Service2
1 6 Product1 Service3
2 4 Product2 Service1
2 5 Product2 Service2
2 6 Product2 Service3
3 4 Product3 Service1
3 5 Product3 Service2
3 6 Product3 Service3
how can i do that with Ms SQL 2008??
Throw Error, Exception and Runtime Exception in child class
Throw Error, Exception and Runtime Exception in child class
I'm trying to understand the difference why a child class cannot override
a method implementation in the parent class to catch an Exception but no
problem while catching a Error,
For example in the below scenario, when I remove "Exception" from the
throws clause, it compiles fine.
class Supertest {
public void amethod(int i, String s) {
}
}
public class test extends Supertest {
public void amethod(int i, String s) throws Error, Exception {
}
}
I'm trying to understand the difference why a child class cannot override
a method implementation in the parent class to catch an Exception but no
problem while catching a Error,
For example in the below scenario, when I remove "Exception" from the
throws clause, it compiles fine.
class Supertest {
public void amethod(int i, String s) {
}
}
public class test extends Supertest {
public void amethod(int i, String s) throws Error, Exception {
}
}
how to merge array if field is same
how to merge array if field is same
Array
(
[Id] => 896
[item] => Combo Cheesesteak - Mushrooms & Peppers
)
Array
(
[Id] => 890
[item] => Burrito | Steak
)
Array
(
[Id] => 889
[item] => Burrito | Chicken
)
Array
(
[Id] => 888
[item] => Burrito | Chicken
)
Array
(
[Id] => 888
[item] => Burrito | Carnitas
)
Array
(
[Id] => 888
[item] => Nantucket Nectar | Apple
)
Array
(
[Id] => 887
[item] => Tempura
)
Array
(
[Id] => 887
[item] => Chicken Karaage
)
I want to merge the item if id is same if it is not simple echo in php???
Array
(
[Id] => 896
[item] => Combo Cheesesteak - Mushrooms & Peppers
)
Array
(
[Id] => 890
[item] => Burrito | Steak
)
Array
(
[Id] => 889
[item] => Burrito | Chicken
)
Array
(
[Id] => 888
[item] => Burrito | Chicken
)
Array
(
[Id] => 888
[item] => Burrito | Carnitas
)
Array
(
[Id] => 888
[item] => Nantucket Nectar | Apple
)
Array
(
[Id] => 887
[item] => Tempura
)
Array
(
[Id] => 887
[item] => Chicken Karaage
)
I want to merge the item if id is same if it is not simple echo in php???
Multipart file upload constrained for XML file type
Multipart file upload constrained for XML file type
In my project I have to upload xml files to server. while browsing for
files in directory only xml files in the directory should be listed. It
should constraint other file type. I have done for uploading any file type
using multipart. how to constraint my upload function to upload only xml
files?
In my project I have to upload xml files to server. while browsing for
files in directory only xml files in the directory should be listed. It
should constraint other file type. I have done for uploading any file type
using multipart. how to constraint my upload function to upload only xml
files?
render_template unable to jsonify object
render_template unable to jsonify object
I'm not doing a lot of web development, so my knowledge in this field is
pretty basic. However I have to write a simple web application using
python an flask.
In this application I have a simple class that looks like this:
class Task(object):
def __init__(self, id, title):
super(Task, self).__init__()
self.id = id
self.title = title
It can be assumed that id is an integer and title is a (unicode) string.
In a view function I want to render a template passing a list of Task
objects, like this:
@app.route('/tasklist')
@login_required
def tasklist():
tasklist = [
Task(1, u"Task 1"),
Task(2, u"Task 2"),
Task(3, u"Task 3"),
Task(4, u"Task 4")
]
return render_template( "tasklist.html", tasklist=tasklist)
When the view function is called, I get the following error message:
TypeError: <models.Task object at 0x103861210> is not JSON serializable
When I look around on the interwebs I see many examples, where they pass
lists of objects to views using render_template. So I wonder what am I
missing? My object only uses basic datatypes. Do I have to overload a
specific function?
Calling render_template with a list of simple strings (instead of class
instances) works fine.
I know, this is a very basic question, but I didn't find a satisfying
answer for now.
I'm not doing a lot of web development, so my knowledge in this field is
pretty basic. However I have to write a simple web application using
python an flask.
In this application I have a simple class that looks like this:
class Task(object):
def __init__(self, id, title):
super(Task, self).__init__()
self.id = id
self.title = title
It can be assumed that id is an integer and title is a (unicode) string.
In a view function I want to render a template passing a list of Task
objects, like this:
@app.route('/tasklist')
@login_required
def tasklist():
tasklist = [
Task(1, u"Task 1"),
Task(2, u"Task 2"),
Task(3, u"Task 3"),
Task(4, u"Task 4")
]
return render_template( "tasklist.html", tasklist=tasklist)
When the view function is called, I get the following error message:
TypeError: <models.Task object at 0x103861210> is not JSON serializable
When I look around on the interwebs I see many examples, where they pass
lists of objects to views using render_template. So I wonder what am I
missing? My object only uses basic datatypes. Do I have to overload a
specific function?
Calling render_template with a list of simple strings (instead of class
instances) works fine.
I know, this is a very basic question, but I didn't find a satisfying
answer for now.
Tuesday, 17 September 2013
Overriding methods in Java
Overriding methods in Java
Let
public class A{
public MyType myMethod(){...}
}
and
public class B extends A{
@Override
public MyType myMethod(){...}
}
be an arbitrary classes. Why MyType must be a parent type of
MyAdvancedType necessarily? What happened if we permitted that
MyAdvancedType can be an arbitrary type?
Let
public class A{
public MyType myMethod(){...}
}
and
public class B extends A{
@Override
public MyType myMethod(){...}
}
be an arbitrary classes. Why MyType must be a parent type of
MyAdvancedType necessarily? What happened if we permitted that
MyAdvancedType can be an arbitrary type?
wallpaper app using 1080p images in android
wallpaper app using 1080p images in android
this is my bitmap images load code case R.id.set: InputStream y =
getResources().openRawResource(toPhone); Bitmap b =
BitmapFactory.decodeStream(y); try { //wpm.setBitmap(t);
getApplicationContext().setWallpaper(b); Toast.makeText(this, "Wallpaper
Set!", Toast.LENGTH_SHORT) .show();enter code here } catch (IOException e)
{ e.printStackTrace(); }
this is my bitmap images load code case R.id.set: InputStream y =
getResources().openRawResource(toPhone); Bitmap b =
BitmapFactory.decodeStream(y); try { //wpm.setBitmap(t);
getApplicationContext().setWallpaper(b); Toast.makeText(this, "Wallpaper
Set!", Toast.LENGTH_SHORT) .show();enter code here } catch (IOException e)
{ e.printStackTrace(); }
Should I ignore schema.rb because extension differs on development/production OS?
Should I ignore schema.rb because extension differs on
development/production OS?
My database uses PostgreSQL. I develop on Mac and this line is needed:
# db/schema.rb on Mac environment
enable_extension "plpgsql"
However, the extension is not required on Linux.
In this case, should we just ignore schema.rb and generate that through
db:migrate for both dev and production environments?
development/production OS?
My database uses PostgreSQL. I develop on Mac and this line is needed:
# db/schema.rb on Mac environment
enable_extension "plpgsql"
However, the extension is not required on Linux.
In this case, should we just ignore schema.rb and generate that through
db:migrate for both dev and production environments?
Java Mixing variable String[] with String in one only array of strings
Java Mixing variable String[] with String in one only array of strings
Suppose this:
String s0 = "01234";
String[] S1 = {"jkl","abc","xyz"};
String[] S2 = {"OPQ","ghi","STU"};
String s3 = "56789";
get_AllStrings(s3, S1, S2, s0);
The returned String[] must be:
String[] NewArray = {"56789","OPQ","ghi","STU","01234"}
I want to obtain this strings like only one array of strings... Here my
method:
public String[] get_AllStrings(String... argString) { //Only String or
String[]
int TheSize = 0;
for (int i = 0; i<argString.length; i++) {
if(argString[i]!= null && argString[i].getClass().isArray()) {
String[] OneArray = (String [])argString[i];
TheSize += OneArray.length;
} else {
TheSize += 1;
}
}
String[] NewArray = new String[TheSize];
int ThePos = 0;
for (int i = 0; i<argString.length; i++) {
if(argString[i]!= null && argString[i].getClass().isArray()) {
String[] OneArray = argString[i];
System.arraycopy(OneArray, 0, NewArray, ThePos, OneArray.length);
ThePos += OneArray.length;
} else {
String[] OneArray = {argString[i]};
System.arraycopy(OneArray, 0, NewArray, ThePos, 1);
ThePos += OneArray.length;
}
}
return NewArray;
}
But, is not working...
Suppose this:
String s0 = "01234";
String[] S1 = {"jkl","abc","xyz"};
String[] S2 = {"OPQ","ghi","STU"};
String s3 = "56789";
get_AllStrings(s3, S1, S2, s0);
The returned String[] must be:
String[] NewArray = {"56789","OPQ","ghi","STU","01234"}
I want to obtain this strings like only one array of strings... Here my
method:
public String[] get_AllStrings(String... argString) { //Only String or
String[]
int TheSize = 0;
for (int i = 0; i<argString.length; i++) {
if(argString[i]!= null && argString[i].getClass().isArray()) {
String[] OneArray = (String [])argString[i];
TheSize += OneArray.length;
} else {
TheSize += 1;
}
}
String[] NewArray = new String[TheSize];
int ThePos = 0;
for (int i = 0; i<argString.length; i++) {
if(argString[i]!= null && argString[i].getClass().isArray()) {
String[] OneArray = argString[i];
System.arraycopy(OneArray, 0, NewArray, ThePos, OneArray.length);
ThePos += OneArray.length;
} else {
String[] OneArray = {argString[i]};
System.arraycopy(OneArray, 0, NewArray, ThePos, 1);
ThePos += OneArray.length;
}
}
return NewArray;
}
But, is not working...
Is there way to access a pdf through a java application
Is there way to access a pdf through a java application
I'm trying to build an application which would parse a pdf having question
papers. As the pdf is parsed and the question number (in the pdf that is
being parsed) changes, the application clicks a snapshot of the question
by checking the question no change. So my questions are:
Can the pdf text be extracted for comparison?
Can we take snapshots in a pdf?
Can the coordinates of a pdf be obtained ?
Can the snapshot be customised according to the coordinates?
I'm trying to build an application which would parse a pdf having question
papers. As the pdf is parsed and the question number (in the pdf that is
being parsed) changes, the application clicks a snapshot of the question
by checking the question no change. So my questions are:
Can the pdf text be extracted for comparison?
Can we take snapshots in a pdf?
Can the coordinates of a pdf be obtained ?
Can the snapshot be customised according to the coordinates?
From iCloud iCal to Google Calendar
From iCloud iCal to Google Calendar
I would like to export my iCloud iCal on my computer to import it into my
Google Calendar. I don't find a working solution. Here is the method I
just tried:
Log in on my iCloud account.
In iCal, I share publicly the considered calendar.
I copy the address in a browser but I replace the webcal:// by http://
It downloads a .ics file
When I try to import that file into my Google calendar, it fails...
Where am I wrong ?
Thanks for your help.
I would like to export my iCloud iCal on my computer to import it into my
Google Calendar. I don't find a working solution. Here is the method I
just tried:
Log in on my iCloud account.
In iCal, I share publicly the considered calendar.
I copy the address in a browser but I replace the webcal:// by http://
It downloads a .ics file
When I try to import that file into my Google calendar, it fails...
Where am I wrong ?
Thanks for your help.
Sunday, 15 September 2013
bootstrap with fontAwesome issue
bootstrap with fontAwesome issue
I m sonal. I am designing a website. In which i m using font-Awesome and
bootstrap combine. But some where confused in linking.
my linking files are:
<link rel="stylesheet" href="../goyal/bootstrap-3.0.0/dist/css/
bootstrap.min.css">
<link rel="stylesheet" href="../goyal/bootstrap-3.0.0/dist/css/
bootstrap-theme.min.css">
<script
src="../goyal/bootstrap-3.0.0/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet"
href="path/to/font-awesome/css/font-awesome.min.css">
<link
href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/
bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="../goyal/font-awesome/css/font-awesome.css"
rel="stylesheet">
<link rel="stylesheet" href="../goyal/font-awesome/css/font-
awesome.min.css">
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
/>
Where i am lacking. I am in new in this feild.
I m sonal. I am designing a website. In which i m using font-Awesome and
bootstrap combine. But some where confused in linking.
my linking files are:
<link rel="stylesheet" href="../goyal/bootstrap-3.0.0/dist/css/
bootstrap.min.css">
<link rel="stylesheet" href="../goyal/bootstrap-3.0.0/dist/css/
bootstrap-theme.min.css">
<script
src="../goyal/bootstrap-3.0.0/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet"
href="path/to/font-awesome/css/font-awesome.min.css">
<link
href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/
bootstrap-combined.no-icons.min.css" rel="stylesheet">
<link href="../goyal/font-awesome/css/font-awesome.css"
rel="stylesheet">
<link rel="stylesheet" href="../goyal/font-awesome/css/font-
awesome.min.css">
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"
/>
Where i am lacking. I am in new in this feild.
RewriteRule rewriting legacy slugs
RewriteRule rewriting legacy slugs
I'm working on updating a website, moving from Drupal to Wordpress MS. One
of the big challenges is taking all of our old URLs that have been indexed
by google, and making them a lot prettier and smaller.
The old structure looks something like this:
<domain>/CA/<location_name>-superflous-data-slapped-at-the-end
The catch is that often times <location_name> contains hyphen characters
as well that we want to strip.
The new structure should look like
<domain>/<hyphen-stripped-location-name> Where we've trimmed off the state
abbreviation, the superflouous data, and we've stripped out the hyphens
from our location name.
Just to be clear I'd like to catch forward from the old URLs, whenever
they're requested, to these new pretty URLs that already exist.
I have a beginner's understanding of rewrite rules and my regex isn't very
good either. I have no idea where to begin, any help is greatly
appreciated!
I'm working on updating a website, moving from Drupal to Wordpress MS. One
of the big challenges is taking all of our old URLs that have been indexed
by google, and making them a lot prettier and smaller.
The old structure looks something like this:
<domain>/CA/<location_name>-superflous-data-slapped-at-the-end
The catch is that often times <location_name> contains hyphen characters
as well that we want to strip.
The new structure should look like
<domain>/<hyphen-stripped-location-name> Where we've trimmed off the state
abbreviation, the superflouous data, and we've stripped out the hyphens
from our location name.
Just to be clear I'd like to catch forward from the old URLs, whenever
they're requested, to these new pretty URLs that already exist.
I have a beginner's understanding of rewrite rules and my regex isn't very
good either. I have no idea where to begin, any help is greatly
appreciated!
Flex PopUp Null Object Module
Flex PopUp Null Object Module
I'm doing a flex program, but i'm having some trouble when calling a pop
up from my module. These are the codes:
The function that calls the popUp.
[Bindable] private var popUp : newMemberPopUp;
private function btnNewClickHandler(event:MouseEvent):void {
popUp = newMemberPopUp(PopUpManager.createPopUp(this, newMemberPopUp,
true));
}
The popUp mxml
<?xml version="1.0" encoding="utf-8"?>
<s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="350" height="250"
title="Dados Cadastrais">
<fx:Declarations>
</fx:Declarations>
<s:VGroup width="100%">
<mx:Form width="100%">
<mx:FormItem label="Nome">
<mx:TextInput id="nameTextInput"/>
</mx:FormItem>
<mx:FormItem label="Telefone">
<mx:TextInput id="phoneTextInput"/>
</mx:FormItem>
<mx:FormItem label="Email">
<mx:TextInput id="emailTextInput"/>
</mx:FormItem>
<mx:FormItem label="Data de Nascimento">
<mx:DateField/>
</mx:FormItem>
<mx:FormItem label="Data de Cadastro">
<mx:DateField/>
</mx:FormItem>
</mx:Form>
<s:HGroup paddingTop="10" paddingLeft="10" paddingRight="10"
paddingBottom="10">
<s:Button label="Gravar"/>
<s:Button label="Cancelar"/>
</s:HGroup>
</s:VGroup>
</s:TitleWindow>
The error i'm getting is this one:
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
mx.managers::PopUpManagerImpl/http://www.adobe.com/2006/flex/mx/internal::createModalWindow()[E:\dev\4.0.0\frameworks\projects\framework\src\mx\managers\PopUpManagerImpl.as:682]
at
mx.managers::PopUpManagerImpl/addPopUp()[E:\dev\4.0.0\frameworks\projects\framework\src\mx\managers\PopUpManagerImpl.as:397]
at
mx.managers::PopUpManagerImpl/createPopUp()[E:\dev\4.0.0\frameworks\projects\framework\src\mx\managers\PopUpManagerImpl.as:236]
at
mx.managers::PopUpManager$/createPopUp()[E:\dev\4.0.0\frameworks\projects\framework\src\mx\managers\PopUpManager.as:139]
at
view::Members/btnNewClickHandler()[E:\MyFlexWorkspace\CTCA\src\model\Members.as:29]
at
view::Members/__btnNew_click()[E:\MyFlexWorkspace\CTCA\src\view\Members.mxml:39]
If i call the pop up from the application it works fine, but if i call it
from the module i have this error.
I'm doing a flex program, but i'm having some trouble when calling a pop
up from my module. These are the codes:
The function that calls the popUp.
[Bindable] private var popUp : newMemberPopUp;
private function btnNewClickHandler(event:MouseEvent):void {
popUp = newMemberPopUp(PopUpManager.createPopUp(this, newMemberPopUp,
true));
}
The popUp mxml
<?xml version="1.0" encoding="utf-8"?>
<s:TitleWindow xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
width="350" height="250"
title="Dados Cadastrais">
<fx:Declarations>
</fx:Declarations>
<s:VGroup width="100%">
<mx:Form width="100%">
<mx:FormItem label="Nome">
<mx:TextInput id="nameTextInput"/>
</mx:FormItem>
<mx:FormItem label="Telefone">
<mx:TextInput id="phoneTextInput"/>
</mx:FormItem>
<mx:FormItem label="Email">
<mx:TextInput id="emailTextInput"/>
</mx:FormItem>
<mx:FormItem label="Data de Nascimento">
<mx:DateField/>
</mx:FormItem>
<mx:FormItem label="Data de Cadastro">
<mx:DateField/>
</mx:FormItem>
</mx:Form>
<s:HGroup paddingTop="10" paddingLeft="10" paddingRight="10"
paddingBottom="10">
<s:Button label="Gravar"/>
<s:Button label="Cancelar"/>
</s:HGroup>
</s:VGroup>
</s:TitleWindow>
The error i'm getting is this one:
TypeError: Error #1009: Cannot access a property or method of a null
object reference. at
mx.managers::PopUpManagerImpl/http://www.adobe.com/2006/flex/mx/internal::createModalWindow()[E:\dev\4.0.0\frameworks\projects\framework\src\mx\managers\PopUpManagerImpl.as:682]
at
mx.managers::PopUpManagerImpl/addPopUp()[E:\dev\4.0.0\frameworks\projects\framework\src\mx\managers\PopUpManagerImpl.as:397]
at
mx.managers::PopUpManagerImpl/createPopUp()[E:\dev\4.0.0\frameworks\projects\framework\src\mx\managers\PopUpManagerImpl.as:236]
at
mx.managers::PopUpManager$/createPopUp()[E:\dev\4.0.0\frameworks\projects\framework\src\mx\managers\PopUpManager.as:139]
at
view::Members/btnNewClickHandler()[E:\MyFlexWorkspace\CTCA\src\model\Members.as:29]
at
view::Members/__btnNew_click()[E:\MyFlexWorkspace\CTCA\src\view\Members.mxml:39]
If i call the pop up from the application it works fine, but if i call it
from the module i have this error.
Asymptotic running time in Big Theta notation
Asymptotic running time in Big Theta notation
Considering the below algorithm,
Loop1 until(i<n^2)
Loop2 until(j<i^2)
....
j=j+4
End Loop2
i=i*3
End Loop1
I think this is Theta(n^2*log(n)). This is correct or is the Big Theta
higher than this?
Considering the below algorithm,
Loop1 until(i<n^2)
Loop2 until(j<i^2)
....
j=j+4
End Loop2
i=i*3
End Loop1
I think this is Theta(n^2*log(n)). This is correct or is the Big Theta
higher than this?
SAS: Add asterix in Compute block (Traffic Lighting)
SAS: Add asterix in Compute block (Traffic Lighting)
I have a PROC REPORT output and want to add an asterick based on the value
of the cell being less than 1.96. I don't want colours, just an asterick
after the number. Can this be done with a format, or do I need an
'IF/ELSE' clause in the COMPUTE block?
data have1;
input username $ betdate : datetime. stake winnings winner;
dateOnly = datepart(betdate) ;
format betdate DATETIME.;
format dateOnly ddmmyy8.;
datalines;
player1 12NOV2008:12:04:01 90 -90 0
player1 04NOV2008:09:03:44 100 40 1
player2 07NOV2008:14:03:33 120 -120 0
player1 05NOV2008:09:00:00 50 15 1
player1 05NOV2008:09:05:00 30 5 1
player1 05NOV2008:09:00:05 20 10 1
player2 09NOV2008:10:05:10 10 -10 0
player2 09NOV2008:10:05:40 15 -15 0
player2 09NOV2008:10:05:45 15 -15 0
player2 09NOV2008:10:05:45 15 45 1
player2 15NOV2008:15:05:33 35 -35 0
player1 15NOV2008:15:05:33 35 15 1
player1 15NOV2008:15:05:33 35 15 1
run;
PROC PRINT; RUN;
Proc rank data=have1 ties=mean out=ranksout1 groups=2;
var stake winner;
ranks stakeRank winnerRank;
run;
proc sql;
create table withCubedDeviations as
select *,
((stake - (select avg(stake) from ranksout1 where stakeRank =
main.stakeRank and winnerRank = main.winnerRank))/(select std(stake)
from ranksout1 where stakeRank = main.stakeRank and winnerRank =
main.winnerRank)) **3 format=8.2 as cubeddeviations
from ranksout1 main;
quit;
PROC REPORT DATA=withCubedDeviations NOWINDOWS out=report;
COLUMN stakerank winnerrank, ( N stake=avg cubeddeviations skewness);
DEFINE stakerank / GROUP ORDER=INTERNAL '';
DEFINE winnerrank / ACROSS ORDER=INTERNAL '';
DEFINE cubeddeviations / analysis 'SumCD' noprint;
DEFINE N / 'Bettors';
DEFINE avg / analysis mean 'Avg' format=8.2;
DEFINE skewness / computed format=8.2 'Skewness';
COMPUTE skewness;
_C5_ = _C4_ * (_C2_ / ((_C2_ -1) * (_C2_ - 2)));
_C9_ = _C8_ * (_C6_ / ((_C6_ -1) * (_C6_ - 2)));
ENDCOMP;
RUN;
This is just an example, so this won't make statistical sense, but if the
value for SKEWNESS is greater than 1 I need to put a single asterick, two
asterix if it's greater than 5 and three asterix if the value is greater
than ten.
Thanks for any help.
I have a PROC REPORT output and want to add an asterick based on the value
of the cell being less than 1.96. I don't want colours, just an asterick
after the number. Can this be done with a format, or do I need an
'IF/ELSE' clause in the COMPUTE block?
data have1;
input username $ betdate : datetime. stake winnings winner;
dateOnly = datepart(betdate) ;
format betdate DATETIME.;
format dateOnly ddmmyy8.;
datalines;
player1 12NOV2008:12:04:01 90 -90 0
player1 04NOV2008:09:03:44 100 40 1
player2 07NOV2008:14:03:33 120 -120 0
player1 05NOV2008:09:00:00 50 15 1
player1 05NOV2008:09:05:00 30 5 1
player1 05NOV2008:09:00:05 20 10 1
player2 09NOV2008:10:05:10 10 -10 0
player2 09NOV2008:10:05:40 15 -15 0
player2 09NOV2008:10:05:45 15 -15 0
player2 09NOV2008:10:05:45 15 45 1
player2 15NOV2008:15:05:33 35 -35 0
player1 15NOV2008:15:05:33 35 15 1
player1 15NOV2008:15:05:33 35 15 1
run;
PROC PRINT; RUN;
Proc rank data=have1 ties=mean out=ranksout1 groups=2;
var stake winner;
ranks stakeRank winnerRank;
run;
proc sql;
create table withCubedDeviations as
select *,
((stake - (select avg(stake) from ranksout1 where stakeRank =
main.stakeRank and winnerRank = main.winnerRank))/(select std(stake)
from ranksout1 where stakeRank = main.stakeRank and winnerRank =
main.winnerRank)) **3 format=8.2 as cubeddeviations
from ranksout1 main;
quit;
PROC REPORT DATA=withCubedDeviations NOWINDOWS out=report;
COLUMN stakerank winnerrank, ( N stake=avg cubeddeviations skewness);
DEFINE stakerank / GROUP ORDER=INTERNAL '';
DEFINE winnerrank / ACROSS ORDER=INTERNAL '';
DEFINE cubeddeviations / analysis 'SumCD' noprint;
DEFINE N / 'Bettors';
DEFINE avg / analysis mean 'Avg' format=8.2;
DEFINE skewness / computed format=8.2 'Skewness';
COMPUTE skewness;
_C5_ = _C4_ * (_C2_ / ((_C2_ -1) * (_C2_ - 2)));
_C9_ = _C8_ * (_C6_ / ((_C6_ -1) * (_C6_ - 2)));
ENDCOMP;
RUN;
This is just an example, so this won't make statistical sense, but if the
value for SKEWNESS is greater than 1 I need to put a single asterick, two
asterix if it's greater than 5 and three asterix if the value is greater
than ten.
Thanks for any help.
PHP security what is really necessary
PHP security what is really necessary
I was searching a bit and I found a line like this, in PHP;
$mots =
mysql_real_escape_string(stripslashes(strip_tags(htmlspecialchars($_POST['mots']))));
I was wondering how much of this was really necessary to protect a $_POST
entry as good as possible.
Thanks
I was searching a bit and I found a line like this, in PHP;
$mots =
mysql_real_escape_string(stripslashes(strip_tags(htmlspecialchars($_POST['mots']))));
I was wondering how much of this was really necessary to protect a $_POST
entry as good as possible.
Thanks
Omit one parameter from view in Django?
Omit one parameter from view in Django?
In urls.py urlpatterns I have such declaration:
url(r'^product-(\d+)-([a-zA-Z_]+)$', 'product', name="product"),
Second group in regexp is SEO name not needed in view.
In view I have:
def product(request, product_id, suffix):
but suffix is neither required nor used by me. It's there only for SEO.
Is there any way to get rid of this parameter?
In urls.py urlpatterns I have such declaration:
url(r'^product-(\d+)-([a-zA-Z_]+)$', 'product', name="product"),
Second group in regexp is SEO name not needed in view.
In view I have:
def product(request, product_id, suffix):
but suffix is neither required nor used by me. It's there only for SEO.
Is there any way to get rid of this parameter?
how to extract opcode sequence from executable file?
how to extract opcode sequence from executable file?
I want to do some experiment with opcode sequence in my project. Does
anyone know how to extract opcode sequence from executable file ?
I want to do some experiment with opcode sequence in my project. Does
anyone know how to extract opcode sequence from executable file ?
Saturday, 14 September 2013
PHP form submission and AJAX validation
PHP form submission and AJAX validation
Below is basic script to check a username availability.
How can I prevent the form from being submitted if a username is already
taken. Ideally i would like to have a JS alert box pop up.
I've tried to add this to the JS but didn't work:
document.getElementById('submit').disabled
Also I've tried to add onclick="return validate();" to the form itself,
but no luck either: the form still can still get submitted.
<form id="edit" action="edit.php" method="post">
<fieldset>
<label>Username</label> <input type="text" class="input" name="username"
id="username"/><span id="status"></span>
<button type="submit" id="submit" value="add">Save</button>
</fielset>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#username").change(function() {
var username = $("#username").val();
var msgbox = $("#status");
if (username.length >= 4) {
$("#status").html('<img src="images/gif/ajax-loading.gif">');
$.ajax({
type: "POST",
url: "ajax_check.php",
data: "username=" + username,
success: function(msg) {
if (msg == 'OK') {
msgbox.html('<img src="/images/yes.png">');
return true;
} else {
msgbox.html(msg);
return false;
}
}
});
} else {
$("#status").html('<img src="/images/no.png"><font
color="#cc0000">too
long!</font>');
return false;
}
return false;
});
});
edit.php and ajax_check.php only contains some SQL queries.
Also, some users have JavaScript disabled on their browser, how could I
get around this?
Below is basic script to check a username availability.
How can I prevent the form from being submitted if a username is already
taken. Ideally i would like to have a JS alert box pop up.
I've tried to add this to the JS but didn't work:
document.getElementById('submit').disabled
Also I've tried to add onclick="return validate();" to the form itself,
but no luck either: the form still can still get submitted.
<form id="edit" action="edit.php" method="post">
<fieldset>
<label>Username</label> <input type="text" class="input" name="username"
id="username"/><span id="status"></span>
<button type="submit" id="submit" value="add">Save</button>
</fielset>
</form>
<script type="text/javascript">
$(document).ready(function() {
$("#username").change(function() {
var username = $("#username").val();
var msgbox = $("#status");
if (username.length >= 4) {
$("#status").html('<img src="images/gif/ajax-loading.gif">');
$.ajax({
type: "POST",
url: "ajax_check.php",
data: "username=" + username,
success: function(msg) {
if (msg == 'OK') {
msgbox.html('<img src="/images/yes.png">');
return true;
} else {
msgbox.html(msg);
return false;
}
}
});
} else {
$("#status").html('<img src="/images/no.png"><font
color="#cc0000">too
long!</font>');
return false;
}
return false;
});
});
edit.php and ajax_check.php only contains some SQL queries.
Also, some users have JavaScript disabled on their browser, how could I
get around this?
CSS @font-face working for one font but not another
CSS @font-face working for one font but not another
I have successfully used the font face declarations for two fonts and it
works for all browsers except IE8 and below. I am using the code from
http://www.fontspring.com/blog/further-hardening-of-the-bulletproof-syntax.
The strange thing is on IE8, one font is working and the other is not.
Here is the CSS:
@font-face {
font-family: 'FreestyleScriptRegular';
src: url('freescpt.eot'); /* IE9 Compat Modes */
src: url('freescpt.eot?#iefix') format('embedded-opentype'), /*
IE6-IE8 */
url('freescpt.woff') format('woff'), /* Modern Browsers */
url('freescpt.ttf') format('truetype'), /* Safari, Android, iOS */
url('freescpt.svg#FreestyleScriptRegular') format('svg'); /*
Legacy iOS */
}
@font-face {
font-family: 'GillSansMTCondensed';
src:url(Gill_Sans_MT_Condensed.eot);/* IE9 Compat Modes */
src: url('Gill_Sans_MT_Condensed.eot?#iefix')
format('embedded-opentype'),
url('Gill_Sans_MT_Condensed.woff') format('woff'),
url('Gill_Sans_MT_Condensed.ttf') format('truetype'),
url('Gill_Sans_MT_Condensed.svg#GillSansMTCondensed') format('svg');
}
The FreestyleScriptRegular is not rendering correctly but the
GillSansMTCondensed is. I have tried everything I can think of and every
hack I can think of. I even used regenerated the eot file for the font
concerned using a different application but it didn't make any difference.
Is there anything peculiar to IE8 that would prevent the second font from
working? Any ideas?
Thanks
I have successfully used the font face declarations for two fonts and it
works for all browsers except IE8 and below. I am using the code from
http://www.fontspring.com/blog/further-hardening-of-the-bulletproof-syntax.
The strange thing is on IE8, one font is working and the other is not.
Here is the CSS:
@font-face {
font-family: 'FreestyleScriptRegular';
src: url('freescpt.eot'); /* IE9 Compat Modes */
src: url('freescpt.eot?#iefix') format('embedded-opentype'), /*
IE6-IE8 */
url('freescpt.woff') format('woff'), /* Modern Browsers */
url('freescpt.ttf') format('truetype'), /* Safari, Android, iOS */
url('freescpt.svg#FreestyleScriptRegular') format('svg'); /*
Legacy iOS */
}
@font-face {
font-family: 'GillSansMTCondensed';
src:url(Gill_Sans_MT_Condensed.eot);/* IE9 Compat Modes */
src: url('Gill_Sans_MT_Condensed.eot?#iefix')
format('embedded-opentype'),
url('Gill_Sans_MT_Condensed.woff') format('woff'),
url('Gill_Sans_MT_Condensed.ttf') format('truetype'),
url('Gill_Sans_MT_Condensed.svg#GillSansMTCondensed') format('svg');
}
The FreestyleScriptRegular is not rendering correctly but the
GillSansMTCondensed is. I have tried everything I can think of and every
hack I can think of. I even used regenerated the eot file for the font
concerned using a different application but it didn't make any difference.
Is there anything peculiar to IE8 that would prevent the second font from
working? Any ideas?
Thanks
jplayer isn't showing progress bar or seek bar on IE
jplayer isn't showing progress bar or seek bar on IE
I am using jplayer to play mp3 files and for some reason, the seek bar
isn't showing up on IE9, and on IE8, I am not seeing the progress bar or
the seek bar... has anyone experienced this issue before?
I am using jplayer to play mp3 files and for some reason, the seek bar
isn't showing up on IE9, and on IE8, I am not seeing the progress bar or
the seek bar... has anyone experienced this issue before?
How to display join result in view
How to display join result in view
I need to join three tables using inner join and i did as follows
@posts = SubCategory.joins(products: :posts)
Now I am trying to list the fields for posts table but it is throwing
error as
undefined method `title' for
#<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Post:0x9932f84>
i tried something like this i my view but it doen't help
<% @posts.each do |post| %>
<h4><%= post.posts.title %></h4>
<% end %>
Any suggestions
I need to join three tables using inner join and i did as follows
@posts = SubCategory.joins(products: :posts)
Now I am trying to list the fields for posts table but it is throwing
error as
undefined method `title' for
#<ActiveRecord::Associations::CollectionProxy::ActiveRecord_Associations_CollectionProxy_Post:0x9932f84>
i tried something like this i my view but it doen't help
<% @posts.each do |post| %>
<h4><%= post.posts.title %></h4>
<% end %>
Any suggestions
Cannot click link nestd in multiple
Cannot click link nestd in multiple
I have a link that I cannot seem to be able to click. The text for the
link shows an underline, but nothing else. Is this a CSS thing or
something flawed with my html?
<body>
<div id="box_Border">
<div id="wrapper">
<div id="backgroundwrapper">
<div id="heading">
<h1><a href="index.html"><i>SilkNails</i></a></h1>
</div>
</div>
</div>
</div>
<body>
I have a link that I cannot seem to be able to click. The text for the
link shows an underline, but nothing else. Is this a CSS thing or
something flawed with my html?
<body>
<div id="box_Border">
<div id="wrapper">
<div id="backgroundwrapper">
<div id="heading">
<h1><a href="index.html"><i>SilkNails</i></a></h1>
</div>
</div>
</div>
</div>
<body>
Is transaction needed when insert single line in mysql with InnoDB engine?
Is transaction needed when insert single line in mysql with InnoDB engine?
I used to use
<?php
$sql = "insert into test (owner) values ('owen')";
$db->autocommit(false);
if (!$db->query($sql))
$db->rollback();
else
$db->commit();
$db->close();
?>
However, today I run two insert php files in a same tables, without any
action. It is simple like:
<?php
$sql = "insert into test (owner) values ('owen')"; //the other php is the
same but replacing 'owen' to 'huhu'
for ($i = 0; $i < 100 * 1000; $i++) {
$db->query($sql);
}
$db->close();
?>
I run two php files in two different consoles. Then I got 200,000 records
without any error. Does that mean using transaction manually is really not
needed. As there are no conflicts.
I used to use
<?php
$sql = "insert into test (owner) values ('owen')";
$db->autocommit(false);
if (!$db->query($sql))
$db->rollback();
else
$db->commit();
$db->close();
?>
However, today I run two insert php files in a same tables, without any
action. It is simple like:
<?php
$sql = "insert into test (owner) values ('owen')"; //the other php is the
same but replacing 'owen' to 'huhu'
for ($i = 0; $i < 100 * 1000; $i++) {
$db->query($sql);
}
$db->close();
?>
I run two php files in two different consoles. Then I got 200,000 records
without any error. Does that mean using transaction manually is really not
needed. As there are no conflicts.
cant get this code to run twice
cant get this code to run twice
private void txtlogin_userid_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Enter key is down
//Capture the text
if (sender is TextBox)
{
TextBox txb = (TextBox)sender;
dc.SelectCommand = new SqlCommand("select * from
UserMaster where UserID='" + txb.Text + "'", sc);
dc.Fill(ds);
dg.DataSource = ds.Tables[0];
txtlogin_name.Text = ds.Tables[0].Rows[0][1].ToString();
txtlogin_mailid.Text = ds.Tables[0].Rows[0][2].ToString();
sc.Open();
SqlCommand cmd = new SqlCommand("select Location from
UserMaster where UserID='" + txb.Text + "'", sc);
string a = Convert.ToString(cmd.ExecuteScalar());
sc.Close();
string b = "MIND";
if (a.Trim() == b)
{
radiomind.Checked = true;
}
else
{
radioMSSL.Checked = true;
}
}
}
}
this code is fetching me values from database when i just hit enter after
entering the userid.But it does that only once,when i click on refresh
button on the form ,and again enter the userid and hit enter ,it brings me
the same old values instead of new values from the database for the new
userid i enetered. the refresh button has the code "textbox.clear()" for
all textboxes on the form and "radiobtn.clear()" for radio buttons on the
form" please suggest how to solve this.
private void txtlogin_userid_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//Enter key is down
//Capture the text
if (sender is TextBox)
{
TextBox txb = (TextBox)sender;
dc.SelectCommand = new SqlCommand("select * from
UserMaster where UserID='" + txb.Text + "'", sc);
dc.Fill(ds);
dg.DataSource = ds.Tables[0];
txtlogin_name.Text = ds.Tables[0].Rows[0][1].ToString();
txtlogin_mailid.Text = ds.Tables[0].Rows[0][2].ToString();
sc.Open();
SqlCommand cmd = new SqlCommand("select Location from
UserMaster where UserID='" + txb.Text + "'", sc);
string a = Convert.ToString(cmd.ExecuteScalar());
sc.Close();
string b = "MIND";
if (a.Trim() == b)
{
radiomind.Checked = true;
}
else
{
radioMSSL.Checked = true;
}
}
}
}
this code is fetching me values from database when i just hit enter after
entering the userid.But it does that only once,when i click on refresh
button on the form ,and again enter the userid and hit enter ,it brings me
the same old values instead of new values from the database for the new
userid i enetered. the refresh button has the code "textbox.clear()" for
all textboxes on the form and "radiobtn.clear()" for radio buttons on the
form" please suggest how to solve this.
Friday, 13 September 2013
Macro issue,and what may be the output?
Macro issue,and what may be the output?
#define CUBE(x)(x*x*x)
int main()
{
int a,b;
b=3;
a=CUBE(b++)/b++;
printf(a=%d b=%d\n",a,b);
return 0;
}
i have a confusion in this Macro defining statement? and i need output too?
#define CUBE(x)(x*x*x)
int main()
{
int a,b;
b=3;
a=CUBE(b++)/b++;
printf(a=%d b=%d\n",a,b);
return 0;
}
i have a confusion in this Macro defining statement? and i need output too?
MSVCR100.DLL not found on Android Studio launch
MSVCR100.DLL not found on Android Studio launch
I have just installed Android Studio and tried to launch it. But appears
the following message and it doesn't start:
MSVCR100.DLL not found
Do I need to install anything else?
Thanks
I have just installed Android Studio and tried to launch it. But appears
the following message and it doesn't start:
MSVCR100.DLL not found
Do I need to install anything else?
Thanks
PHP: Unable to see variables from POST of a form
PHP: Unable to see variables from POST of a form
I have a very basic form with two fields (a login form). The variables are
posted to a script (shown below), however I am unable to see any posted
vars. I have no idea what I am doing wrong, can somebody help me out?
<?php
add_page_content();
function add_page_content() {
$error = true;
echo ' <div id="page_content">
<h3>Login</h3>
<div id="login_form">
'
. ($error ? '<p class="text_red">Wrong username and/or
password.</p>' : '') . '
<form action="login.php" method="post" enctype="text/plain">
<div id="login_fields">
<div>
<label>Username:</label>
<input id="admin_user_input" type="text"
name="username" ' . ($error ? ('value="' .
htmlspecialchars($_POST["username"]) . '"') : '')
. '>
</div>
<div>
<label>Password:</label>
<input id="admin_pass_input" type="password"
name="password">
</div>
</div>
<input id="login_submit_button" type="submit"
name="submit" value="Go">
</form>
' . 'username: ' . $_POST["username"] . '
</div>
</div>';
}
?>
EDIT: Ops, I have no idea what happened, I lost half of my post... here I
go retyping it:
If I trace the post vars of the request using httpfox addon, here is what
I get: -let's assume I will fill "user" into the username field, "pass"
into password. RAW:
username=user
password=pass
submit=Go
PRETTY:
Parameter Value
username userpassword
Thanks a lot for feedback!
I have a very basic form with two fields (a login form). The variables are
posted to a script (shown below), however I am unable to see any posted
vars. I have no idea what I am doing wrong, can somebody help me out?
<?php
add_page_content();
function add_page_content() {
$error = true;
echo ' <div id="page_content">
<h3>Login</h3>
<div id="login_form">
'
. ($error ? '<p class="text_red">Wrong username and/or
password.</p>' : '') . '
<form action="login.php" method="post" enctype="text/plain">
<div id="login_fields">
<div>
<label>Username:</label>
<input id="admin_user_input" type="text"
name="username" ' . ($error ? ('value="' .
htmlspecialchars($_POST["username"]) . '"') : '')
. '>
</div>
<div>
<label>Password:</label>
<input id="admin_pass_input" type="password"
name="password">
</div>
</div>
<input id="login_submit_button" type="submit"
name="submit" value="Go">
</form>
' . 'username: ' . $_POST["username"] . '
</div>
</div>';
}
?>
EDIT: Ops, I have no idea what happened, I lost half of my post... here I
go retyping it:
If I trace the post vars of the request using httpfox addon, here is what
I get: -let's assume I will fill "user" into the username field, "pass"
into password. RAW:
username=user
password=pass
submit=Go
PRETTY:
Parameter Value
username userpassword
Thanks a lot for feedback!
How can I tell whether a numpy boolean array contains only a single block of `True`s?
How can I tell whether a numpy boolean array contains only a single block
of `True`s?
If I have a numpy array containing booleans, say the output of some math
comparison, what's the best way of determining whether that array contains
only a single contiguous block of Trues, e.g.
array([False, False, False, True, True, True, False, False, False],
dtype=bool)
i.e. where the sequence ...,True, False, ..., True... never occurs?
of `True`s?
If I have a numpy array containing booleans, say the output of some math
comparison, what's the best way of determining whether that array contains
only a single contiguous block of Trues, e.g.
array([False, False, False, True, True, True, False, False, False],
dtype=bool)
i.e. where the sequence ...,True, False, ..., True... never occurs?
Unable to get images on my web page while using ServletFilter
Unable to get images on my web page while using ServletFilter
I am unbale to get images on my jsp page while using ServletFilters on the
url pattern. Please Help so that I can get images on my web page.
Filter CODE:
package com.peckuk.filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class AdminFilter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String test = filterConfig.getInitParameter("test-param");
System.out.println("Init Method" + test);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
PrintWriter out = response.getWriter();
System.out.println("doFilter Method");
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
String role = session.getAttribute("role").toString();
if (role.equals("admin")) {
chain.doFilter(request, response);
} else {
out.println("Invalid user role");
}
}
@Override
public void destroy() {
System.out.println("destroy Method");
}
}
I am unbale to get images on my jsp page while using ServletFilters on the
url pattern. Please Help so that I can get images on my web page.
Filter CODE:
package com.peckuk.filter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class AdminFilter implements javax.servlet.Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String test = filterConfig.getInitParameter("test-param");
System.out.println("Init Method" + test);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
PrintWriter out = response.getWriter();
System.out.println("doFilter Method");
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
String role = session.getAttribute("role").toString();
if (role.equals("admin")) {
chain.doFilter(request, response);
} else {
out.println("Invalid user role");
}
}
@Override
public void destroy() {
System.out.println("destroy Method");
}
}
Dynamic Gradient Background based on int value
Dynamic Gradient Background based on int value
for an order overview I have a list of multiple orders with different
priorities. They reach from -10 => very high priority to +20 => low
priority. Based on this priority I want to return a Gradient brush Color
dynamically.
For example:
From -10 to -0.5 it should it fade from darkred into orange
From -0.5 to +0.5 it should fade from orange into yellow into lime
From +0.5 to +10 it should fade from lime to green
I have never made this before and absolutly no clue how to solve this.
Even if you don't have a complete solution for me it would be very nice to
give me a hint.
Regards Johannes
for an order overview I have a list of multiple orders with different
priorities. They reach from -10 => very high priority to +20 => low
priority. Based on this priority I want to return a Gradient brush Color
dynamically.
For example:
From -10 to -0.5 it should it fade from darkred into orange
From -0.5 to +0.5 it should fade from orange into yellow into lime
From +0.5 to +10 it should fade from lime to green
I have never made this before and absolutly no clue how to solve this.
Even if you don't have a complete solution for me it would be very nice to
give me a hint.
Regards Johannes
Thursday, 12 September 2013
DataTable slow Loading of Data from Database
DataTable slow Loading of Data from Database
Hi guys need a help i need to load 10 thousand data from my database and
here is my Data table code how can i load my data FAST i read some
$('#example').dataTable({
"bPaginate": true,
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"bAutoWidth": false,
"bDestroy": false,
"bJQueryUI": false,
"sPaginationType": "full_numbers"
});
but i dont find the right solution to load fast a 10,000 data from data base
Hi guys need a help i need to load 10 thousand data from my database and
here is my Data table code how can i load my data FAST i read some
$('#example').dataTable({
"bPaginate": true,
"bLengthChange": true,
"bFilter": true,
"bSort": true,
"bInfo": true,
"bAutoWidth": false,
"bDestroy": false,
"bJQueryUI": false,
"sPaginationType": "full_numbers"
});
but i dont find the right solution to load fast a 10,000 data from data base
Calling getLoaderManager().restartLoader(...) from onLoadFinished(...)
Calling getLoaderManager().restartLoader(...) from onLoadFinished(...)
This is my problem: I want to init/restart a second loader from
onLoadFinished(...) method after the first loader has finished his job
(load finished), since i need some values from first loaders cursor. So
the second loader depends on some values, which the first loader delivers.
It works... but if a configuration change appears (rotation), it crashes
because while in this call, since it can happen after an activity's state
is saved. So there is no activity attached. If you call getActivity() for
example it returns null. Same thing happens if you call
getLoaderManager().XXX of course.
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(FIRST_LOADER, null, this);
(...)
}
...
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case FIRST_LOADER:
data.moveToFirst();
value1 =
data.getString(data.getColumnIndex(DBHelper.COLUMN_FIRST));
value2 =
data.getString(data.getColumnIndex(DBHelper.COLUMN_SECOND));
getLoaderManager().restartLoader(SECOND_LOADER, null, this);
break;
case SECOND_LOADER:
(...)
}
}
But if I destroy loaders manually in onDestroy(...) method there are no
problems. Ok, it works that way, but it dont make me happy. So there must
be some other way to solve this.
(And Im sorry for my poor english :) i hope it is understandable :P)
This is my problem: I want to init/restart a second loader from
onLoadFinished(...) method after the first loader has finished his job
(load finished), since i need some values from first loaders cursor. So
the second loader depends on some values, which the first loader delivers.
It works... but if a configuration change appears (rotation), it crashes
because while in this call, since it can happen after an activity's state
is saved. So there is no activity attached. If you call getActivity() for
example it returns null. Same thing happens if you call
getLoaderManager().XXX of course.
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getLoaderManager().initLoader(FIRST_LOADER, null, this);
(...)
}
...
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
switch (loader.getId()) {
case FIRST_LOADER:
data.moveToFirst();
value1 =
data.getString(data.getColumnIndex(DBHelper.COLUMN_FIRST));
value2 =
data.getString(data.getColumnIndex(DBHelper.COLUMN_SECOND));
getLoaderManager().restartLoader(SECOND_LOADER, null, this);
break;
case SECOND_LOADER:
(...)
}
}
But if I destroy loaders manually in onDestroy(...) method there are no
problems. Ok, it works that way, but it dont make me happy. So there must
be some other way to solve this.
(And Im sorry for my poor english :) i hope it is understandable :P)
recursively adding xml elements to a database
recursively adding xml elements to a database
I'm trying to create a multidimensional array from xml code, in the format
[element type, children], so that it creates a value and a reference to
child nodes, if there are any.
so if my xml looked like this:
<name>
<firstName>Mary</firstName>
</name>
my database array would look like this:
[name, firstName] and if you looked at firstName you would see: [Mary
(Youngest)]
So using my limited knowledge of recursive functions and DOM methods, I
came up with this code:
function buildDatabase(nodesAtLevel)
{
//ignore this code
alert(nodesAtLevel.length);
//if the element is a dead end
if (nodesAtLevel.length == 0 && nodesAtLevel[0].nextChild.length == 0)
//return the child node
{
youngestChild = new Array(nodesAtLevel.nodeName + "
(Youngest)", nodesAtLevel[0].firstChild.data);
return youngestChild;
}
//if this element has children
for (var i = 0; i < nodesAtLevel.length; i++)
{
//add the name of the element and its children to the array
var children = new Array(nodesAtLevel.nodeName,
nodesAtLevel[i].childNodes);
//return the array ,
buildDatabase(children);
}
}
And here's the function that tests it:
function test()
{
//load the document
var document = loadXMLDoc("testXML.xml");
elements = document.childNodes;
//give the database object to buildDatabase
database = buildDatabase(elements);
}
I keep getting "nodesAtLevel[i] is undefined"
So the problem statement seems to be this line:
var children = [nodesAtLevel.nodeName, nodesAtLevel[i].childNodes];
My logic is that if an element has multiple children, it will go through
each element of the array, and if that element is a reference to another
variable it will treat that as an array as well to continue down the tree.
I'm trying to create a multidimensional array from xml code, in the format
[element type, children], so that it creates a value and a reference to
child nodes, if there are any.
so if my xml looked like this:
<name>
<firstName>Mary</firstName>
</name>
my database array would look like this:
[name, firstName] and if you looked at firstName you would see: [Mary
(Youngest)]
So using my limited knowledge of recursive functions and DOM methods, I
came up with this code:
function buildDatabase(nodesAtLevel)
{
//ignore this code
alert(nodesAtLevel.length);
//if the element is a dead end
if (nodesAtLevel.length == 0 && nodesAtLevel[0].nextChild.length == 0)
//return the child node
{
youngestChild = new Array(nodesAtLevel.nodeName + "
(Youngest)", nodesAtLevel[0].firstChild.data);
return youngestChild;
}
//if this element has children
for (var i = 0; i < nodesAtLevel.length; i++)
{
//add the name of the element and its children to the array
var children = new Array(nodesAtLevel.nodeName,
nodesAtLevel[i].childNodes);
//return the array ,
buildDatabase(children);
}
}
And here's the function that tests it:
function test()
{
//load the document
var document = loadXMLDoc("testXML.xml");
elements = document.childNodes;
//give the database object to buildDatabase
database = buildDatabase(elements);
}
I keep getting "nodesAtLevel[i] is undefined"
So the problem statement seems to be this line:
var children = [nodesAtLevel.nodeName, nodesAtLevel[i].childNodes];
My logic is that if an element has multiple children, it will go through
each element of the array, and if that element is a reference to another
variable it will treat that as an array as well to continue down the tree.
javascript post data to the another server and can i get what the server returned
javascript post data to the another server and can i get what the server
returned
Is there a way to post data to the another server and then get what server
returned? NOTE: yotube performs ajax search with the google's domain
returned
Is there a way to post data to the another server and then get what server
returned? NOTE: yotube performs ajax search with the google's domain
Multiple Dynamic Javascript Dropdowns?
Multiple Dynamic Javascript Dropdowns?
I have currently got a 2-tier javascript drop down box attached to my
form, and i am looking to add another 3-tiers, but completely seperate to
my current javascript and can't unfortunately figure it out (quite new to
javascript :( )
Here what I have so far, it all works ( not even sure what framework to
select on fiddle for it to display properly lol :( the embarassment haha
http://jsfiddle.net/CEuZY/
function setOptions(chosen) {
var selbox = document.myform.opttwo;
selbox.options.length = 0;
if (chosen == " ") {
selbox.options[selbox.options.length] = new Option('Please Select
Prompty Category', ' ');
}
if (chosen == "1") {
selbox.options[selbox.options.length] = new Option('123213123123',
'oneone');
selbox.options[selbox.options.length] = new Option('23123123123',
'onetwo');
}
if (chosen == "2") {
selbox.options[selbox.options.length] = new Option('23121312312',
'twoone');
selbox.options[selbox.options.length] = new Option('3211231232',
'twotwo');
selbox.options[selbox.options.length] = new Option('2131223213',
'twothree');
selbox.options[selbox.options.length] = new Option('32123213213',
'twofour');
}
if (chosen == "3") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'threeone');
}
if (chosen == "4") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'fourone');
}
if (chosen == "5") {
selbox.options[selbox.options.length] = new Option('23213123123',
'fiveone');
selbox.options[selbox.options.length] = new Option('2312132312',
'fivetwo');
selbox.options[selbox.options.length] = new Option('12312123213',
'fivethree');
selbox.options[selbox.options.length] = new Option('21213231321',
'fivefour');
selbox.options[selbox.options.length] = new Option('213213213',
'fivefive');
selbox.options[selbox.options.length] = new Option('23213132123',
'fivesix');
}
if (chosen == "6") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'sixone');
}
if (chosen == "7") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'sevenone');
}
if (chosen == "8") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'eighone');
}
if (chosen == "9") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'nineone');
}
if (chosen == "10") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'tenone');
}
if (chosen == "11") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'elevenone');
}
if (chosen == "12") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'twelveone');
}
if (chosen == "13") {
selbox.options[selbox.options.length] = new Option('Email',
'thirteenone');
selbox.options[selbox.options.length] = new Option('Letter',
'thirteentwo');
selbox.options[selbox.options.length] = new Option('Phone Call',
'thirteenthree');
selbox.options[selbox.options.length] = new Option('Text',
'thirteenfour');
}
if (chosen == "14") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'fourteenone');
}
if (chosen == "15") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'fifteenone');
}
if (chosen == "16") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'sixteenone');
}
if (chosen == "17") {
selbox.options[selbox.options.length] = new Option('Camera',
'seventeenone');
selbox.options[selbox.options.length] = new Option('Power',
'seventeentwo');
selbox.options[selbox.options.length] = new
Option('Keypad/Buttons', 'seventeenthree');
selbox.options[selbox.options.length] = new Option('Screen',
'seventeenfour');
selbox.options[selbox.options.length] = new Option('Microphone',
'seventeenfive');
selbox.options[selbox.options.length] = new Option('Speaker',
'seventeensix');
selbox.options[selbox.options.length] = new Option('Software',
'seventeenseven');
selbox.options[selbox.options.length] = new Option('Other',
'seventeeneight');
}
if (chosen == "18") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'eighteenone');
}
if (chosen == "19") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'nineteenone');
}
}
Any help is appreciated <3
I have currently got a 2-tier javascript drop down box attached to my
form, and i am looking to add another 3-tiers, but completely seperate to
my current javascript and can't unfortunately figure it out (quite new to
javascript :( )
Here what I have so far, it all works ( not even sure what framework to
select on fiddle for it to display properly lol :( the embarassment haha
http://jsfiddle.net/CEuZY/
function setOptions(chosen) {
var selbox = document.myform.opttwo;
selbox.options.length = 0;
if (chosen == " ") {
selbox.options[selbox.options.length] = new Option('Please Select
Prompty Category', ' ');
}
if (chosen == "1") {
selbox.options[selbox.options.length] = new Option('123213123123',
'oneone');
selbox.options[selbox.options.length] = new Option('23123123123',
'onetwo');
}
if (chosen == "2") {
selbox.options[selbox.options.length] = new Option('23121312312',
'twoone');
selbox.options[selbox.options.length] = new Option('3211231232',
'twotwo');
selbox.options[selbox.options.length] = new Option('2131223213',
'twothree');
selbox.options[selbox.options.length] = new Option('32123213213',
'twofour');
}
if (chosen == "3") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'threeone');
}
if (chosen == "4") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'fourone');
}
if (chosen == "5") {
selbox.options[selbox.options.length] = new Option('23213123123',
'fiveone');
selbox.options[selbox.options.length] = new Option('2312132312',
'fivetwo');
selbox.options[selbox.options.length] = new Option('12312123213',
'fivethree');
selbox.options[selbox.options.length] = new Option('21213231321',
'fivefour');
selbox.options[selbox.options.length] = new Option('213213213',
'fivefive');
selbox.options[selbox.options.length] = new Option('23213132123',
'fivesix');
}
if (chosen == "6") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'sixone');
}
if (chosen == "7") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'sevenone');
}
if (chosen == "8") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'eighone');
}
if (chosen == "9") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'nineone');
}
if (chosen == "10") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'tenone');
}
if (chosen == "11") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'elevenone');
}
if (chosen == "12") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'twelveone');
}
if (chosen == "13") {
selbox.options[selbox.options.length] = new Option('Email',
'thirteenone');
selbox.options[selbox.options.length] = new Option('Letter',
'thirteentwo');
selbox.options[selbox.options.length] = new Option('Phone Call',
'thirteenthree');
selbox.options[selbox.options.length] = new Option('Text',
'thirteenfour');
}
if (chosen == "14") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'fourteenone');
}
if (chosen == "15") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'fifteenone');
}
if (chosen == "16") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'sixteenone');
}
if (chosen == "17") {
selbox.options[selbox.options.length] = new Option('Camera',
'seventeenone');
selbox.options[selbox.options.length] = new Option('Power',
'seventeentwo');
selbox.options[selbox.options.length] = new
Option('Keypad/Buttons', 'seventeenthree');
selbox.options[selbox.options.length] = new Option('Screen',
'seventeenfour');
selbox.options[selbox.options.length] = new Option('Microphone',
'seventeenfive');
selbox.options[selbox.options.length] = new Option('Speaker',
'seventeensix');
selbox.options[selbox.options.length] = new Option('Software',
'seventeenseven');
selbox.options[selbox.options.length] = new Option('Other',
'seventeeneight');
}
if (chosen == "18") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'eighteenone');
}
if (chosen == "19") {
selbox.options[selbox.options.length] = new Option('Not
Applicable', 'nineteenone');
}
}
Any help is appreciated <3
Choose between implementations at compile time
Choose between implementations at compile time
Say one wants to create a C++ class with two separate implementations (say
one to run on a CPU and on a GPU) and one wants this to happen at compile
time.
What design pattern can be used for this?
Say one wants to create a C++ class with two separate implementations (say
one to run on a CPU and on a GPU) and one wants this to happen at compile
time.
What design pattern can be used for this?
Trying to make a web application send info to an executable on my machine using Java
Trying to make a web application send info to an executable on my machine
using Java
I have some java code that communicates with an executable that is on my
machine which codes certain orders based on four files and user input the
code for that is as follows:
void coder(File exe, File ord, File cod, File msg, File rls, String tcc )
throws ProcessException {
String[] cmd = {
exe.getPath(), // Executable
ord.getPath(), // InputOrder (IN)
cod.getPath(), // ResultsCodedOrder (OUT)
msg.getPath(), // Messages (OUT)
rls.getPath(), // Releases (IN)
tcc //User input
};
Process proc = null;
try {
proc = Runtime.getRuntime().exec(cmd); // Code the order.
} catch (IOException ioe) {
ioe.printStackTrace();
throw new ProcessException("IOException. Could not exec command.");
}
Within the same file I have coder actually putting in certain values for
the user input string and for the user made files here:
// This illustrates the (idealized) steps neccessary to code an order.
Order codeOrder(File taskdir, Order order) throws ProcessException {
String ordername = order.getName();
// Create temp 'input' files.
File orderFile = createTriconOrderFile(taskdir, order);
File releaseFile = createTriconReleaseFile(taskdir, order);
// Define temp 'output' files.
File messageFile = new File(taskdir, ordername + msgExt);
File codedFile = new File(taskdir, ordername + codExt);
// Code order.
coder(exe,
orderFile,
codedFile,
messageFile,
releaseFile,
"valsel");
I would like to change this based on a user's preference and not have it
hard coded as 'valsel' and rather whatever the user decides...Any ideas on
how this may be implemented...
// Delete temp files.
// If there is an exception while coding the Task, these won't be
deleted.
// This is good because we can examine these files.
deleteTempFile(releaseFile);
deleteTempFile(codedFile );
deleteTempFile(messageFile);
deleteTempFile(orderFile );
return codedOrder;
}
using Java
I have some java code that communicates with an executable that is on my
machine which codes certain orders based on four files and user input the
code for that is as follows:
void coder(File exe, File ord, File cod, File msg, File rls, String tcc )
throws ProcessException {
String[] cmd = {
exe.getPath(), // Executable
ord.getPath(), // InputOrder (IN)
cod.getPath(), // ResultsCodedOrder (OUT)
msg.getPath(), // Messages (OUT)
rls.getPath(), // Releases (IN)
tcc //User input
};
Process proc = null;
try {
proc = Runtime.getRuntime().exec(cmd); // Code the order.
} catch (IOException ioe) {
ioe.printStackTrace();
throw new ProcessException("IOException. Could not exec command.");
}
Within the same file I have coder actually putting in certain values for
the user input string and for the user made files here:
// This illustrates the (idealized) steps neccessary to code an order.
Order codeOrder(File taskdir, Order order) throws ProcessException {
String ordername = order.getName();
// Create temp 'input' files.
File orderFile = createTriconOrderFile(taskdir, order);
File releaseFile = createTriconReleaseFile(taskdir, order);
// Define temp 'output' files.
File messageFile = new File(taskdir, ordername + msgExt);
File codedFile = new File(taskdir, ordername + codExt);
// Code order.
coder(exe,
orderFile,
codedFile,
messageFile,
releaseFile,
"valsel");
I would like to change this based on a user's preference and not have it
hard coded as 'valsel' and rather whatever the user decides...Any ideas on
how this may be implemented...
// Delete temp files.
// If there is an exception while coding the Task, these won't be
deleted.
// This is good because we can examine these files.
deleteTempFile(releaseFile);
deleteTempFile(codedFile );
deleteTempFile(messageFile);
deleteTempFile(orderFile );
return codedOrder;
}
Django 1.7 migrations for User Profile
Django 1.7 migrations for User Profile
I'm fairly new to Django and I'm using the latest version 1.7 from git in
a virtual environment with python3.3.
I'm making a simple blog web app as a learning project and I'm running
into a migration issue using Django's new in-built migration tools.
When trying to run ./manage.py migrate blog I'm getting the following
error (trimmed):
"...first_blog/django-trunk/django/db/migrations/graph.py", line 40, in
add_dependency
raise KeyError("Dependency references nonexistent parent node %r" %
(parent,))
KeyError: "Dependency references nonexistent parent node ('auth',
'0001_initial')"
The model that is causing the error is this one, presumably because of the
relation to the User model
from django.contrib.auth.models import User
...
class Author(models.Model):
user = models.OneToOneField(User, related_name='profile')
def gravatar_url(self):
return "http://www.gravatar.com/avatar/%s?s=50" %
hashlib.md5(self.user.email).hexdigest()
User.profile = property(lambda u: Author.objects.get_or_create(user=u)[0])
I realise that this is still in development but I couldn't work out if it
was an issue with my code (more likely) or an issue with the new built-in
migration tools.
Database is SQLite and let me know if there is any other parts of my
(limited) code you need to see. This is also my first post on SO, so
hopefully I've formatted it all ok.
Thanks in advance for any help. (Just set up the project in github so you
can see the entire picture if desired:
https://github.com/simonwillcock/django-learning-blog)
I'm fairly new to Django and I'm using the latest version 1.7 from git in
a virtual environment with python3.3.
I'm making a simple blog web app as a learning project and I'm running
into a migration issue using Django's new in-built migration tools.
When trying to run ./manage.py migrate blog I'm getting the following
error (trimmed):
"...first_blog/django-trunk/django/db/migrations/graph.py", line 40, in
add_dependency
raise KeyError("Dependency references nonexistent parent node %r" %
(parent,))
KeyError: "Dependency references nonexistent parent node ('auth',
'0001_initial')"
The model that is causing the error is this one, presumably because of the
relation to the User model
from django.contrib.auth.models import User
...
class Author(models.Model):
user = models.OneToOneField(User, related_name='profile')
def gravatar_url(self):
return "http://www.gravatar.com/avatar/%s?s=50" %
hashlib.md5(self.user.email).hexdigest()
User.profile = property(lambda u: Author.objects.get_or_create(user=u)[0])
I realise that this is still in development but I couldn't work out if it
was an issue with my code (more likely) or an issue with the new built-in
migration tools.
Database is SQLite and let me know if there is any other parts of my
(limited) code you need to see. This is also my first post on SO, so
hopefully I've formatted it all ok.
Thanks in advance for any help. (Just set up the project in github so you
can see the entire picture if desired:
https://github.com/simonwillcock/django-learning-blog)
Wednesday, 11 September 2013
Does the MongoDb C# driver query support Except()?
Does the MongoDb C# driver query support Except()?
var querycodes= new string[] {"aaa", "bbb", "ccc"};
var query = collection.AsQueryable<Source>()
.Where(d => (d.codes.Count == querycodes.Count() &&
!d.codes.Except(querycodes).Any()));
It's throwing error:
Unable to determine the serialization information for the expression:
Enumerable.Count(Enumerable.Except(d.codes, String[]:{ "aaa", "bbb" ...
})).
How can I achieve query targets?
var querycodes= new string[] {"aaa", "bbb", "ccc"};
var query = collection.AsQueryable<Source>()
.Where(d => (d.codes.Count == querycodes.Count() &&
!d.codes.Except(querycodes).Any()));
It's throwing error:
Unable to determine the serialization information for the expression:
Enumerable.Count(Enumerable.Except(d.codes, String[]:{ "aaa", "bbb" ...
})).
How can I achieve query targets?
Printing 'long' or 'short' form of a string
Printing 'long' or 'short' form of a string
Hey guys I'm writing a program that has an abstract class 'Order' that is
extended by three classes 'NonProfitOrder', 'RegularOrder', and
'OverseasOrder'. Each implement the abstract method printOrder in the
abstract class.
The method accepts a string with is either "Long" or "Short"
If "Long" would look like:
Non-Profit Order
Location: CA
Total Price: 200.0
If "Short" would look like:
Non-Profit Order-Location: CA, Total Price: 200.0
public class NonProfitOrder extends Order {
public NonProfitOrder(double price, String location) {
super(price, location);
}
public double calculateBill() {
return getPrice();
}
public String printOrder(String format){
String Long = "Non-Profit Order" + "\nLocation: " + getLocation() +
"\nTotal Price: " + getPrice();
return Long;
}
}
This is the code I have so far, which works fine to print "Long", my
question is how can I get it to print depending on which "Long" or "Short"
is called.
Is there a built in java method to do this? Or is there a certain way to
write this string?
Thanks for any and all help!
Hey guys I'm writing a program that has an abstract class 'Order' that is
extended by three classes 'NonProfitOrder', 'RegularOrder', and
'OverseasOrder'. Each implement the abstract method printOrder in the
abstract class.
The method accepts a string with is either "Long" or "Short"
If "Long" would look like:
Non-Profit Order
Location: CA
Total Price: 200.0
If "Short" would look like:
Non-Profit Order-Location: CA, Total Price: 200.0
public class NonProfitOrder extends Order {
public NonProfitOrder(double price, String location) {
super(price, location);
}
public double calculateBill() {
return getPrice();
}
public String printOrder(String format){
String Long = "Non-Profit Order" + "\nLocation: " + getLocation() +
"\nTotal Price: " + getPrice();
return Long;
}
}
This is the code I have so far, which works fine to print "Long", my
question is how can I get it to print depending on which "Long" or "Short"
is called.
Is there a built in java method to do this? Or is there a certain way to
write this string?
Thanks for any and all help!
json encode returning only partial data
json encode returning only partial data
Here is what I have:
public function get_model_by_make($make = null){
$model_data = $this->vehicle_model->get_model($make);
echo json_encode($model_data);
}
public function get_model($make){
$this->db->select('models_id, models_name');
$this->db->where('makes_id', $make);
$models_data = $this->db->get('Models');
$rows = array();
$rows[0] = '-Select-';
foreach($models_data->result() as $value){
$rows[$value->models_id] = $value->models_name;
}
return $rows;
}
The problem I'm having is if I pass a 0 or 1 to the get_model_by_make()
function the json data that is returned without the array key.
Example:
$data = get_model_by_make(1)
echo $data;
Result:
["-Select-","CL","CSX","EL","Integra","Legend","MDX","NSX","RDX","RL","RSX",
"SLX","TL","TSX","Vigor"]
If the number passed is greater than 1 then its returned like this:
$data = get_model_by_make(2)
echo $data;
Result:
{"0":"-Select-","35":"Alliance","36":"Ambassador","37":"AMX","38":"Classic"}
Why is json_encode not returning the key/value pair for 0 or 1? If I
var_dump the data the key/value is there.
Here is what I have:
public function get_model_by_make($make = null){
$model_data = $this->vehicle_model->get_model($make);
echo json_encode($model_data);
}
public function get_model($make){
$this->db->select('models_id, models_name');
$this->db->where('makes_id', $make);
$models_data = $this->db->get('Models');
$rows = array();
$rows[0] = '-Select-';
foreach($models_data->result() as $value){
$rows[$value->models_id] = $value->models_name;
}
return $rows;
}
The problem I'm having is if I pass a 0 or 1 to the get_model_by_make()
function the json data that is returned without the array key.
Example:
$data = get_model_by_make(1)
echo $data;
Result:
["-Select-","CL","CSX","EL","Integra","Legend","MDX","NSX","RDX","RL","RSX",
"SLX","TL","TSX","Vigor"]
If the number passed is greater than 1 then its returned like this:
$data = get_model_by_make(2)
echo $data;
Result:
{"0":"-Select-","35":"Alliance","36":"Ambassador","37":"AMX","38":"Classic"}
Why is json_encode not returning the key/value pair for 0 or 1? If I
var_dump the data the key/value is there.
Play 2.1.3 application with Maven enhanced models not loading lazy objects
Play 2.1.3 application with Maven enhanced models not loading lazy objects
I have a Play application that is been refactored. The play models have
been refactored out to its own Maven project so they can be shared with
other projects, and the ant-run plugin is being used to enhance the model
classes.
The models work ok up to the point that it involves loading the lazy
references (I'm using field enhancement with public fields). The
references are simply not loaded and an empty object is beeing returned.
The example code is:
@Entity
class A extends Model {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int id;
@ManyToOne
public B b;
public static Finder<Integer,A> finder = new
Finder<Integer,A>(Integer.class, A.class);
}
@Entity
class B extends Model {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int id;
public String someField;
}
....
....
A a = A.finder.by(someId); // returns the correct object
B b = a.b; // Returns a not null but empty object
System.out.println(b.someField); // someField is alway null
When I try to use the referenced object the object is not null, but it
seems it hasn't been initialized with data from the DB.
Even the id field on the B is populated correctly, but the rest of the
fields are not.
Maven seems to be enhancing the objects correctly (ant-run) since I can
get the objects with queries, etc.
If I specify .fetch("b") on the Java side the object is returned
correctly, but it wasn't necessary before, and sometimes is not possible
to do so (in the Scala templates).
I've checked the DB and the related objects are there. Also the code was
working while it was inside the Play project, but a lot of code (not all)
has stopped doing so since I moved the models outside Play.
Are there any specific configs for application.conf to specify lazy
loading or am I missing something?
I have a Play application that is been refactored. The play models have
been refactored out to its own Maven project so they can be shared with
other projects, and the ant-run plugin is being used to enhance the model
classes.
The models work ok up to the point that it involves loading the lazy
references (I'm using field enhancement with public fields). The
references are simply not loaded and an empty object is beeing returned.
The example code is:
@Entity
class A extends Model {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int id;
@ManyToOne
public B b;
public static Finder<Integer,A> finder = new
Finder<Integer,A>(Integer.class, A.class);
}
@Entity
class B extends Model {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
public int id;
public String someField;
}
....
....
A a = A.finder.by(someId); // returns the correct object
B b = a.b; // Returns a not null but empty object
System.out.println(b.someField); // someField is alway null
When I try to use the referenced object the object is not null, but it
seems it hasn't been initialized with data from the DB.
Even the id field on the B is populated correctly, but the rest of the
fields are not.
Maven seems to be enhancing the objects correctly (ant-run) since I can
get the objects with queries, etc.
If I specify .fetch("b") on the Java side the object is returned
correctly, but it wasn't necessary before, and sometimes is not possible
to do so (in the Scala templates).
I've checked the DB and the related objects are there. Also the code was
working while it was inside the Play project, but a lot of code (not all)
has stopped doing so since I moved the models outside Play.
Are there any specific configs for application.conf to specify lazy
loading or am I missing something?
php variable gets null at the end of the script?
php variable gets null at the end of the script?
I have a problem that I really can't figure out. basically I'm working on
a blog and I have a variable from a cookie that returns a post id. the
problem is that at the end of the script, when I enter an if(isset)
statement, the variable seems to be null and I can't understand the reason
behind it. it won't add anything to the database and it won't redirect to
the post id. here's the script:
<?php
//display the post
$post_id = $_GET['post_id'];
$query = mysql_query("SELECT * FROM posts WHERE `post_id`='". $post_id.
"';") or die(mysql_error());
if(mysql_num_rows($query) != 0)
{
$currentrow = mysql_fetch_array($query);
echo $currentrow['title']. "<br>". $currentrow['text'];
}
else
{
echo "that post does not exist.";
}
?>
</div>
<div id="comments">
<br>
<h3>Comments</h3>
<br>
<?php
//display the comments
$comments = mysql_query("SELECT * FROM `comments` JOIN `posts`
ON(posts.post_id=comments.post_id) JOIN `users`
ON(users.user_id=comments.user_id) WHERE posts.post_id=". "'".
$_GET['post_id']. "'". ";")or die(mysql_error());;
while($currentRow = mysql_fetch_array($comments))
{
echo $currentRow['ctext']. "<br>";
echo "posted by <a href='/templates/profile.php?name=".
$currentRow['name']. "'>". $currentRow['name']. "</a> at ".
$currentRow['cdate']. " -- ". $currentRow['ctime']. "<br><br>";
}
?>
</div>
<Form Name ="submitform" Method ="POST" ACTION = "post.php">
<div id="commentbox">
<textarea name="textarea1" rows="10" cols="30">
<?php
echo $post_id;
?>
</textarea>
<br>
<input type="submit" name="submitcomment" value="Submit"><br>
</div>
</Form>
<?php
if(isset($_POST['submitcomment']))
{
$comment = $_POST['textarea1'];
$user_id = $_COOKIE['userid'];
mysql_query("INSERT INTO comments(`ctext`, `cdate`, `ctime`,
`user_id`, `post_id`) VALUES('$comment', 'CURDATE()', 'CURTIME()',
'$user_id', '$post_id')") or die(mysql_error());
header('Location: /post.php?post_id='. $post_id);
}
?>
</body>
</html>
as you can see, I'm echoing that variable in the textarea1 just before the
if statement and it returns the correct value, but at the end it's null.
thanks in advance.
I have a problem that I really can't figure out. basically I'm working on
a blog and I have a variable from a cookie that returns a post id. the
problem is that at the end of the script, when I enter an if(isset)
statement, the variable seems to be null and I can't understand the reason
behind it. it won't add anything to the database and it won't redirect to
the post id. here's the script:
<?php
//display the post
$post_id = $_GET['post_id'];
$query = mysql_query("SELECT * FROM posts WHERE `post_id`='". $post_id.
"';") or die(mysql_error());
if(mysql_num_rows($query) != 0)
{
$currentrow = mysql_fetch_array($query);
echo $currentrow['title']. "<br>". $currentrow['text'];
}
else
{
echo "that post does not exist.";
}
?>
</div>
<div id="comments">
<br>
<h3>Comments</h3>
<br>
<?php
//display the comments
$comments = mysql_query("SELECT * FROM `comments` JOIN `posts`
ON(posts.post_id=comments.post_id) JOIN `users`
ON(users.user_id=comments.user_id) WHERE posts.post_id=". "'".
$_GET['post_id']. "'". ";")or die(mysql_error());;
while($currentRow = mysql_fetch_array($comments))
{
echo $currentRow['ctext']. "<br>";
echo "posted by <a href='/templates/profile.php?name=".
$currentRow['name']. "'>". $currentRow['name']. "</a> at ".
$currentRow['cdate']. " -- ". $currentRow['ctime']. "<br><br>";
}
?>
</div>
<Form Name ="submitform" Method ="POST" ACTION = "post.php">
<div id="commentbox">
<textarea name="textarea1" rows="10" cols="30">
<?php
echo $post_id;
?>
</textarea>
<br>
<input type="submit" name="submitcomment" value="Submit"><br>
</div>
</Form>
<?php
if(isset($_POST['submitcomment']))
{
$comment = $_POST['textarea1'];
$user_id = $_COOKIE['userid'];
mysql_query("INSERT INTO comments(`ctext`, `cdate`, `ctime`,
`user_id`, `post_id`) VALUES('$comment', 'CURDATE()', 'CURTIME()',
'$user_id', '$post_id')") or die(mysql_error());
header('Location: /post.php?post_id='. $post_id);
}
?>
</body>
</html>
as you can see, I'm echoing that variable in the textarea1 just before the
if statement and it returns the correct value, but at the end it's null.
thanks in advance.
Subscribe to:
Comments (Atom)