Forward DNS requests from router
I've got a server behind a router and I'm trying to use my server as my
DNS and DHCP service. I have them configured correctly, and I can connect
out through, but I cannot seem to get my router to forward DNS requests to
the server. In my router settings I've disabled DHCP, I port forwarded
port 53 to the server and I set the DNS to my IP of the server, and If I
set a user computer to statically use the DNS in the adapter settings I
can connect fine, but if I use dynamic settings, I get an error in the
network and sharing center saying I could not find the DNS server.
I have a netgear R6300v2 router and a server running windows server 2008
r2. So, what gives? what settings do I have to change in my router for it
get the DNS correctly? Statically coding the computers isn't really an
option so please help? Thanks!
Monday, 30 September 2013
For what values of n the set of divisors of n under partial order relation divides is a complemented lattice
For what values of n the set of divisors of n under partial order relation
divides is a complemented lattice
pFor what values of n the set of divisors of n under partial order
relation divides is a complemented lattice?/p pComplemented lattice: If
every element of a lattice has at least one complement, it is called
complemented lattice./p
divides is a complemented lattice
pFor what values of n the set of divisors of n under partial order
relation divides is a complemented lattice?/p pComplemented lattice: If
every element of a lattice has at least one complement, it is called
complemented lattice./p
How to install both Windows and Open Source Kinect drivers
How to install both Windows and Open Source Kinect drivers
I'm able to get both the open source kinect drivers and the Windows
drivers working correctly for my xbox kinect, but I am not able to keep
both on the same machine when using one or the other. What is the reason
for that? And what can I do so that I don't have to totally uninstall all
Kinect related things when I am testing out a gesture library that might
be open source or require the Windows Kinect SDK?
I'm able to get both the open source kinect drivers and the Windows
drivers working correctly for my xbox kinect, but I am not able to keep
both on the same machine when using one or the other. What is the reason
for that? And what can I do so that I don't have to totally uninstall all
Kinect related things when I am testing out a gesture library that might
be open source or require the Windows Kinect SDK?
using ajax in zend to populate database in view
using ajax in zend to populate database in view
I'm using ZendFramework and I need to populate the data I store in
database in a table in the view but I need to do that using Ajax and json
I have a web service that print the following
{"cat":[{"id":"1","name":"Meat","image_url":"meat.jpg"},
{"id":"2","name":"Soup","image_url":"soup.jpg"},
{"id":"3","name":"drink","image_url":"drink.jpg"},
{"id":"8","name":"Pastries","image_url":"Pastries.jpg"},
{"id":"9","name":"Ice-cream","image_url":"ice_cream.jpg"},
{"id":"10","name":"salad","image_url":"salad.jpg"}]}
the url for this web service is
http://localhost/resturant/public/categories/show-categories
how can I using this web service and Ajax populate the data in Table I'm
so begineer in Ajax actually and I search google but still stuck please
any Idea thnxx all
I'm using ZendFramework and I need to populate the data I store in
database in a table in the view but I need to do that using Ajax and json
I have a web service that print the following
{"cat":[{"id":"1","name":"Meat","image_url":"meat.jpg"},
{"id":"2","name":"Soup","image_url":"soup.jpg"},
{"id":"3","name":"drink","image_url":"drink.jpg"},
{"id":"8","name":"Pastries","image_url":"Pastries.jpg"},
{"id":"9","name":"Ice-cream","image_url":"ice_cream.jpg"},
{"id":"10","name":"salad","image_url":"salad.jpg"}]}
the url for this web service is
http://localhost/resturant/public/categories/show-categories
how can I using this web service and Ajax populate the data in Table I'm
so begineer in Ajax actually and I search google but still stuck please
any Idea thnxx all
Sunday, 29 September 2013
Bitcoin API - CloudFlare 403 Response
Bitcoin API - CloudFlare 403 Response
I am creating a php application with the Coinbase API and the
blockchain.info API. My (000webhost.com) webhost's communications with
coinbase.com and blockchain.info API servers are getting a HTTP 403
CloudFlare Captcha. This completely cripples the API. I tried connecting
with HTTPS, and tried changing the user agent, tried curl(), tried
file_get_contents(), but I can't seem to get a real response from the API
servers.
This is the error I get:
http://s10.postimg.org/ff8ggm6yx/Cloud_Flare_error2.jpg
Thanks for any help, I've been trying to figure this out for days.
I am creating a php application with the Coinbase API and the
blockchain.info API. My (000webhost.com) webhost's communications with
coinbase.com and blockchain.info API servers are getting a HTTP 403
CloudFlare Captcha. This completely cripples the API. I tried connecting
with HTTPS, and tried changing the user agent, tried curl(), tried
file_get_contents(), but I can't seem to get a real response from the API
servers.
This is the error I get:
http://s10.postimg.org/ff8ggm6yx/Cloud_Flare_error2.jpg
Thanks for any help, I've been trying to figure this out for days.
How to emulate a mouse scroll for the current window opened?
How to emulate a mouse scroll for the current window opened?
I'm currently trying to emulate a mouse scroll event on the current window
opened.I'm implementing it using setscrollpos() fucntion in visual C++.
SetScrollPos(hwnd,SB_VERT,0,TRUE);
UpdateWindow(hwnd);
How does one pass the current window opened to the parameter hwnd?
I'm currently trying to emulate a mouse scroll event on the current window
opened.I'm implementing it using setscrollpos() fucntion in visual C++.
SetScrollPos(hwnd,SB_VERT,0,TRUE);
UpdateWindow(hwnd);
How does one pass the current window opened to the parameter hwnd?
Can I Save and load process?
Can I Save and load process?
I have a math calculation C code which is running on the embedded system.
It calculates output using many inputs (about 4,000) and many intermediate
variables.
To simulate my code I'd like to migrate my code to the Windows system.
And I'm going to make a new function which can save and load specific points.
The first solution that I know is tracking all variables and add new
save/load function.
But it has much of variables and I thinks this solution is not efficient.
The second solution I think is save/load process's heap/stack memory.
It seems more easy if I can save/load heap and stack memory.
Do you think is it possible?
And if possible how can I do that?
Thanks in advance.
I have a math calculation C code which is running on the embedded system.
It calculates output using many inputs (about 4,000) and many intermediate
variables.
To simulate my code I'd like to migrate my code to the Windows system.
And I'm going to make a new function which can save and load specific points.
The first solution that I know is tracking all variables and add new
save/load function.
But it has much of variables and I thinks this solution is not efficient.
The second solution I think is save/load process's heap/stack memory.
It seems more easy if I can save/load heap and stack memory.
Do you think is it possible?
And if possible how can I do that?
Thanks in advance.
MvxBind:Error - View type not found - fragment
MvxBind:Error - View type not found - fragment
I'm trying to add map as a part of my activity. Unfortunately when I put
fragment among other control I got the following error:
<fragment
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="250.0dp"
class="com.google.android.gms.maps.SupportMapFragment" />
MvxBind:Error: 26.04 View type not found - fragment
I'm trying to start it with Android 2.3 device using:
MonoDroid
googleplayservicesfroyo12-12.0.0 - GooglePlayServicesFroyoLib.dll
Mono.Android.Support.v4.dll
What could be the issue here? TIA!
I'm trying to add map as a part of my activity. Unfortunately when I put
fragment among other control I got the following error:
<fragment
android:id="@+id/map"
android:layout_width="fill_parent"
android:layout_height="250.0dp"
class="com.google.android.gms.maps.SupportMapFragment" />
MvxBind:Error: 26.04 View type not found - fragment
I'm trying to start it with Android 2.3 device using:
MonoDroid
googleplayservicesfroyo12-12.0.0 - GooglePlayServicesFroyoLib.dll
Mono.Android.Support.v4.dll
What could be the issue here? TIA!
Saturday, 28 September 2013
How can I add my personal abbreviation to emmet-mode in Emacs?
How can I add my personal abbreviation to emmet-mode in Emacs?
I'm using emmet-mode in Emacs24.
I want to expand php to <?php ?>, but Emmet doesn't support php abbreviation.
I thought if I insert a line (puthash "php" "<?php ?>;" tbl) between some
other addreviation, but it doesn't work. Above all I don't want to write
directly emmet-mode.el.
How can I define my abbreviation outside of mode elisp file?
I'm using emmet-mode in Emacs24.
I want to expand php to <?php ?>, but Emmet doesn't support php abbreviation.
I thought if I insert a line (puthash "php" "<?php ?>;" tbl) between some
other addreviation, but it doesn't work. Above all I don't want to write
directly emmet-mode.el.
How can I define my abbreviation outside of mode elisp file?
3 colors loop in a grid
3 colors loop in a grid
I cannot post any picture because I just created this account but this is
the link to it:
https://www.cs.umd.edu/class/fall2013/cmsc131-12/Fall2013Proj2/InformationAndPictures.htm
if (countryCode == 2){
if (height % 3 == 0 && width % 3 == 0 ){
for (int col = 0; col < width; col = col + 1){
for (int row = 0; row < height; row = row + 1){
grid.setColor(row , col, Color.YELLOW);
}
}
for (int col = 0; col < width; col = col + 1){
for (int row = height / 3; row < height; row = row + 1){
grid.setColor(row, col, Color.GREEN);
}
}
for (int col = 0; col < width; col = col + 1){
for (int row = height / 2 + 1; row < height; row = row + 1){
grid.setColor(row , col, Color.RED);
}
}
}
}
So far this is what I have but I just can't get the red and green color to
balance correctly I know I something is wrong with my equation but I just
cannot figure it out.
I cannot post any picture because I just created this account but this is
the link to it:
https://www.cs.umd.edu/class/fall2013/cmsc131-12/Fall2013Proj2/InformationAndPictures.htm
if (countryCode == 2){
if (height % 3 == 0 && width % 3 == 0 ){
for (int col = 0; col < width; col = col + 1){
for (int row = 0; row < height; row = row + 1){
grid.setColor(row , col, Color.YELLOW);
}
}
for (int col = 0; col < width; col = col + 1){
for (int row = height / 3; row < height; row = row + 1){
grid.setColor(row, col, Color.GREEN);
}
}
for (int col = 0; col < width; col = col + 1){
for (int row = height / 2 + 1; row < height; row = row + 1){
grid.setColor(row , col, Color.RED);
}
}
}
}
So far this is what I have but I just can't get the red and green color to
balance correctly I know I something is wrong with my equation but I just
cannot figure it out.
Java swing - painted rectangles not showing up
Java swing - painted rectangles not showing up
I've been trying for quite a while to get this to work and done a lot of
research but I can't work out why it's not happening: My end goal is get a
grid of x by y green squares, and when you click on a square it changes
colour. (this is part of a bigger project)
Now I am aware that this is probably a very inefficient way of doing so,
but I've tried different ways and nothing seems to work.
In my Grid class I have this:
squares = new Square[width][height];
for (int i = 0; i < width; i++){
for (int j = 0; j < height; j++){
squares[i][j] = new Square(i,j);
frame.getContentPane().add(squares[i][j]);
}
}
And this is my Square class:
public class Square extends JLabel implements MouseListener{
private int x,y,width,height, mouseX,mouseY;
private Color colour = Color.GREEN;
public Square(int width, int height){
this.x = width*45;
this.y = height*45;
addMouseListener(this);
this.setBounds(x, y, 45, 45);
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setColor(colour);
g2.fillRect(x, y, 45, 45);
}
@Override
public void mouseClicked(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
if(mouseX > x && mouseX < x+45 && mouseY > y && mouseY < y+45){
if(colour.equals(Color.GREEN)){
colour = Color.RED;
} else{
colour = Color.GREEN;
}
repaint();
}
}
}
However when I run the code, all I see is the first square and the last
square, HOW COMES?
Also if you have any tips of how I could have done this far more
efficiently, please do tell and criticize this code.
Thank you for taking the time to read this, and a further thank you if you
care to respond <3
I've been trying for quite a while to get this to work and done a lot of
research but I can't work out why it's not happening: My end goal is get a
grid of x by y green squares, and when you click on a square it changes
colour. (this is part of a bigger project)
Now I am aware that this is probably a very inefficient way of doing so,
but I've tried different ways and nothing seems to work.
In my Grid class I have this:
squares = new Square[width][height];
for (int i = 0; i < width; i++){
for (int j = 0; j < height; j++){
squares[i][j] = new Square(i,j);
frame.getContentPane().add(squares[i][j]);
}
}
And this is my Square class:
public class Square extends JLabel implements MouseListener{
private int x,y,width,height, mouseX,mouseY;
private Color colour = Color.GREEN;
public Square(int width, int height){
this.x = width*45;
this.y = height*45;
addMouseListener(this);
this.setBounds(x, y, 45, 45);
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
g2.setColor(colour);
g2.fillRect(x, y, 45, 45);
}
@Override
public void mouseClicked(MouseEvent e) {
mouseX = e.getX();
mouseY = e.getY();
if(mouseX > x && mouseX < x+45 && mouseY > y && mouseY < y+45){
if(colour.equals(Color.GREEN)){
colour = Color.RED;
} else{
colour = Color.GREEN;
}
repaint();
}
}
}
However when I run the code, all I see is the first square and the last
square, HOW COMES?
Also if you have any tips of how I could have done this far more
efficiently, please do tell and criticize this code.
Thank you for taking the time to read this, and a further thank you if you
care to respond <3
CLR profiler to see surviving objects
CLR profiler to see surviving objects
i'm not too sure if CLR profiler if the right tool or not.. but what i'm
trying to achieve is to be able to see the state of an object in memory
such as getting disposed or not after exiting a method..
if CLR profiler is not the right tool, can someone please suggest?
i'm not too sure if CLR profiler if the right tool or not.. but what i'm
trying to achieve is to be able to see the state of an object in memory
such as getting disposed or not after exiting a method..
if CLR profiler is not the right tool, can someone please suggest?
Friday, 27 September 2013
How to replace one instance of a character in a string and put the output in a text box with the VB language
How to replace one instance of a character in a string and put the output
in a text box with the VB language
We are trying to only replace the first instance of "a" to first second
third. Then it should loop and replace the second instance of "a" to a new
generated value of first second third and continue this loop til there are
no more "a" characters left and each "a" is a different value. However the
results of the output are not correct. The code is erasing all characters
before the last "a" then replacing that last "a".
Dim message As String
Dim start As Integer = 1
Dim letterfinder As String
Dim timesLooped As Integer = 1
Dim length As Integer
Dim first As Integer
Dim second As Integer
Dim third As Integer
Dim count As Integer = 1
message = inputBox.Text
length = Len(message)
timesLooped = 0
While length > timesLooped
Dim random As New Random
letterfinder = Mid$(message, start, 1)
If letterfinder = "a" Then
first = random.Next(3, 9)
second = 1 \ first
third = 1 - second
outputBox.Text = Replace(message, letterfinder, first & second
& third, [start], [count])
End If
timesLooped = timesLooped + 1
start = start + 1
End While
in a text box with the VB language
We are trying to only replace the first instance of "a" to first second
third. Then it should loop and replace the second instance of "a" to a new
generated value of first second third and continue this loop til there are
no more "a" characters left and each "a" is a different value. However the
results of the output are not correct. The code is erasing all characters
before the last "a" then replacing that last "a".
Dim message As String
Dim start As Integer = 1
Dim letterfinder As String
Dim timesLooped As Integer = 1
Dim length As Integer
Dim first As Integer
Dim second As Integer
Dim third As Integer
Dim count As Integer = 1
message = inputBox.Text
length = Len(message)
timesLooped = 0
While length > timesLooped
Dim random As New Random
letterfinder = Mid$(message, start, 1)
If letterfinder = "a" Then
first = random.Next(3, 9)
second = 1 \ first
third = 1 - second
outputBox.Text = Replace(message, letterfinder, first & second
& third, [start], [count])
End If
timesLooped = timesLooped + 1
start = start + 1
End While
Does the decorator store more than one returned value?
Does the decorator store more than one returned value?
I have the code:
def my_decorator(target):
def wrapper():
print('Calling function "%s"' % target.__name__)
return target() # 1
return wrapper # 2
@my_decorator
def my_target(): # 3
print('Hi. I am the target.')
my_target()
I will describe what i understand about this pattern disorderly.
#3 We are passing the function my_target as an argument to the decorator
my_decorator. No problems.
#1 Actually we are calling the function my_target.
#2 (my doubt). When we are calling the function in #1 it will print and
return to wrapper 'Hi. I am the target.' so wrapper now stores the print
from my_target function. Then, in #2 the (i do not understand this term
well ->) reference from wrapper() function is called. So after this
calling, wrapper reference will run the print('..') set in itself function
and will return the value stored before in it ('Hi. I am the target.', as
mentioned in the beginning). So, the wrapper function stores two values?
Sorry in advance for the messy thought and writing.
addendum: I do not need in #2 call the wrapper function as we call
"normal" functions with () for the same reason (that i do know why) when i
create a function and store it in a variable and when i want call it we
just type the variable and return it?
Like:
def say():
return('hello')
do = say()
>>> do
hello
I have the code:
def my_decorator(target):
def wrapper():
print('Calling function "%s"' % target.__name__)
return target() # 1
return wrapper # 2
@my_decorator
def my_target(): # 3
print('Hi. I am the target.')
my_target()
I will describe what i understand about this pattern disorderly.
#3 We are passing the function my_target as an argument to the decorator
my_decorator. No problems.
#1 Actually we are calling the function my_target.
#2 (my doubt). When we are calling the function in #1 it will print and
return to wrapper 'Hi. I am the target.' so wrapper now stores the print
from my_target function. Then, in #2 the (i do not understand this term
well ->) reference from wrapper() function is called. So after this
calling, wrapper reference will run the print('..') set in itself function
and will return the value stored before in it ('Hi. I am the target.', as
mentioned in the beginning). So, the wrapper function stores two values?
Sorry in advance for the messy thought and writing.
addendum: I do not need in #2 call the wrapper function as we call
"normal" functions with () for the same reason (that i do know why) when i
create a function and store it in a variable and when i want call it we
just type the variable and return it?
Like:
def say():
return('hello')
do = say()
>>> do
hello
Index range scan vs index skip scan vs index fast full scan
Index range scan vs index skip scan vs index fast full scan
I have table test_A(id1 number,id2 number,id3 number,name
varchar2(10),create_dt date), I have two indexes one composite index indx1
on (id1,id2) and indx2(id3). Now when I query this table test_A as
select * from test_A where id2=123 and create_dt=(select max(create_dt)
from test_A where test_A.id2=id2);
I ran explain plan for this above SQL and it is using "index skip scan".
If I create another index on create_dt then it using index fast full scan
and over all cost and %cpu is showing higher than plan with Index skip
scan. It is also using Index range scan after creating index on create_dt.
I could not come to conclusion which should be could? Do I need to create
another Index on Create_dt or is Index skip scan good? I believe Index
skip is a feature of Oracle to run multiple index range scan?
I have table test_A(id1 number,id2 number,id3 number,name
varchar2(10),create_dt date), I have two indexes one composite index indx1
on (id1,id2) and indx2(id3). Now when I query this table test_A as
select * from test_A where id2=123 and create_dt=(select max(create_dt)
from test_A where test_A.id2=id2);
I ran explain plan for this above SQL and it is using "index skip scan".
If I create another index on create_dt then it using index fast full scan
and over all cost and %cpu is showing higher than plan with Index skip
scan. It is also using Index range scan after creating index on create_dt.
I could not come to conclusion which should be could? Do I need to create
another Index on Create_dt or is Index skip scan good? I believe Index
skip is a feature of Oracle to run multiple index range scan?
updating MySQL table - You can't specify target table for update in From clause
updating MySQL table - You can't specify target table for update in From
clause
I have the following query:
SELECT entity_id AS product_id FROM catalog_product_entity cpe
LEFT JOIN cataloginventory_stock_item csi ON csi.product_id = cpe.entity_id
WHERE cpe.type_id = 'configurable'
AND csi.is_in_stock = 0
AND (SELECT SUM(qty) FROM catalog_product_relation cpr LEFT JOIN
cataloginventory_stock_item cisi ON cisi.product_id = cpr.child_id WHERE
cpr.parent_id = cpe.entity_id) > 0
Which returns the following results:
product_id
-----------
912
906
894
559
364
I am trying to update the is_in_stock column within the
cataloginventory_stock_item table, based off of the product_id of the
table existing in the results of the above query.
What I tried to do was this:
UPDATE cataloginventory_stock_item
SET is_in_stock = 1
WHERE product_id IN (
SELECT entity_id AS product_id FROM catalog_product_entity cpe
LEFT JOIN cataloginventory_stock_item csi ON csi.product_id =
cpe.entity_id
WHERE cpe.type_id = 'configurable'
AND csi.is_in_stock = 0
AND (SELECT SUM(qty) FROM catalog_product_relation cpr LEFT JOIN
cataloginventory_stock_item cisi ON cisi.product_id = cpr.child_id
WHERE cpr.parent_id = cpe.entity_id) > 0
)
And I receive the following error:
You can't specify target table 'cataloginventory_stock_item' for update in
FROM clause
I can't seem to figure out how to restructure the query to work. Any help
is greatly appreciated.
clause
I have the following query:
SELECT entity_id AS product_id FROM catalog_product_entity cpe
LEFT JOIN cataloginventory_stock_item csi ON csi.product_id = cpe.entity_id
WHERE cpe.type_id = 'configurable'
AND csi.is_in_stock = 0
AND (SELECT SUM(qty) FROM catalog_product_relation cpr LEFT JOIN
cataloginventory_stock_item cisi ON cisi.product_id = cpr.child_id WHERE
cpr.parent_id = cpe.entity_id) > 0
Which returns the following results:
product_id
-----------
912
906
894
559
364
I am trying to update the is_in_stock column within the
cataloginventory_stock_item table, based off of the product_id of the
table existing in the results of the above query.
What I tried to do was this:
UPDATE cataloginventory_stock_item
SET is_in_stock = 1
WHERE product_id IN (
SELECT entity_id AS product_id FROM catalog_product_entity cpe
LEFT JOIN cataloginventory_stock_item csi ON csi.product_id =
cpe.entity_id
WHERE cpe.type_id = 'configurable'
AND csi.is_in_stock = 0
AND (SELECT SUM(qty) FROM catalog_product_relation cpr LEFT JOIN
cataloginventory_stock_item cisi ON cisi.product_id = cpr.child_id
WHERE cpr.parent_id = cpe.entity_id) > 0
)
And I receive the following error:
You can't specify target table 'cataloginventory_stock_item' for update in
FROM clause
I can't seem to figure out how to restructure the query to work. Any help
is greatly appreciated.
Asterisk in Java Play MVC Framework's Routes File
Asterisk in Java Play MVC Framework's Routes File
I've inherited a project in the Play Framework. I'm in the process of
modifying the conf/routes file and was wondering why asterisks were used
instead of the normal HTTP methods as described in the documentation here:
http://www.playframework.com/documentation/2.0/JavaRouting
Here's and example of what I mean:
# Top level pages
GET /how-tradjenta-works Application.about
GET /prescription-savings-card SavingsCard.index
* /prescription-savings-card/qualify SavingsCard.qualify
As you can see, the third route definition has that asterisk. What gives?
I've inherited a project in the Play Framework. I'm in the process of
modifying the conf/routes file and was wondering why asterisks were used
instead of the normal HTTP methods as described in the documentation here:
http://www.playframework.com/documentation/2.0/JavaRouting
Here's and example of what I mean:
# Top level pages
GET /how-tradjenta-works Application.about
GET /prescription-savings-card SavingsCard.index
* /prescription-savings-card/qualify SavingsCard.qualify
As you can see, the third route definition has that asterisk. What gives?
How to import large database and track its progress in windows os
How to import large database and track its progress in windows os
I have really large database to upload. its 5gb in size. I know command
line way to import such large files as-
mysql -u {uname} -p {password} {dbname} < {file name.sql}
It works but since database is so large I am not sure when it will finish
uploading. I have tried refreshing phpmyadmin but it always remains then
same like nothing happing.
So if anyone can tell me a way to track its progress on windows os i would
really appreciate that help.
Note: The command is working , it creates 5 tables and did 175 entries but
after that there is no change.
I have really large database to upload. its 5gb in size. I know command
line way to import such large files as-
mysql -u {uname} -p {password} {dbname} < {file name.sql}
It works but since database is so large I am not sure when it will finish
uploading. I have tried refreshing phpmyadmin but it always remains then
same like nothing happing.
So if anyone can tell me a way to track its progress on windows os i would
really appreciate that help.
Note: The command is working , it creates 5 tables and did 175 entries but
after that there is no change.
html from xml using xslt
html from xml using xslt
I am new to xslt and am trying to create html from xml using xslt.
I dont know why but my xslt works when only one element is there but not
when multiple.
I tried various ways but as said i am new to this and am not sure how to
do this any more.
Here is my xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<DestinationResults size="1">
<Destination name="Paris, FRA" order="1">
<HotelAvailabilityListResults size="10">
<Hotel order="1">
<hotelId>188139</hotelId>
<name>
<![CDATA[ Hotel Magenta Paris ]]>
</name>
<address1>38 Boulevard De Magenta</address1>
<address2/>
<address3/>
<city>Paris</city>
<stateProvince/>
<country>FR</country>
<postalCode>75010</postalCode>
<latitude>48.87203</latitude>
<longitude>2.35995</longitude>
<tripAdvisorRating>4.0</tripAdvisorRating>
<fromDate>10/11/2013</fromDate>
<toDate>10/12/2013</toDate>
<shortDescription>
<![CDATA[<p><b>Property Location</b> <br />With a
stay at Hotel Magenta Paris in Paris (Gare du Nord - Gare de L'Est),
you'll be minutes from Porte Saint-Martin and close to Louvre Museum.
This]]>
</shortDescription>
<thumbNailUrl>
http://origin-images.ian.com/hotels/1000000/890000/889000/888903/888903_22_t.jpg
</thumbNailUrl>
<propertyRating>3.0</propertyRating>
<referenceProximityDistance>-1.0</referenceProximityDistance>
<referenceProximityUnit/>
<HotelProperty>
<promoDescription>Stay 1 nights and save 10% off your
stay!</promoDescription>
<ValueAdds>
<valueAdd id="2048">Free Wireless Internet</valueAdd>
</ValueAdds>
<PromoRateInfo>
<displayCurrencyCode>USD</displayCurrencyCode>
<DisplayNightlyRates size="1">
<displayNightlyRate>152.02</displayNightlyRate>
</DisplayNightlyRates>
<displayRoomRate>168.68</displayRoomRate>
<chargeableRoomRateTotal>168.68</chargeableRoomRateTotal>
<chargeableRoomRateTaxesAndFees>16.66</chargeableRoomRateTaxesAndFees>
<taxesOnly>16.66</taxesOnly>
<salesTax>0</salesTax>
<hotelOccupancyTax>0</hotelOccupancyTax>
<nativeCurrencyCode>USD</nativeCurrencyCode>
<NativeNightlyRates size="1">
<nativeNightlyRate>152.02</nativeNightlyRate>
</NativeNightlyRates>
<nativeRoomRate>168.68</nativeRoomRate>
<rateFrequency>B</rateFrequency>
</PromoRateInfo>
<RateInfo>
<displayCurrencyCode>USD</displayCurrencyCode>
<DisplayNightlyRates size="1">
<displayNightlyRate>168.91</displayNightlyRate>
</DisplayNightlyRates>
<displayRoomRate>185.57</displayRoomRate>
<chargeableRoomRateTotal>185.57</chargeableRoomRateTotal>
<chargeableRoomRateTaxesAndFees>16.66</chargeableRoomRateTaxesAndFees>
<taxesOnly>16.66</taxesOnly>
<salesTax>0</salesTax>
<hotelOccupancyTax>0</hotelOccupancyTax>
<nativeCurrencyCode>USD</nativeCurrencyCode>
<NativeNightlyRates size="1">
<nativeNightlyRate>168.91</nativeNightlyRate>
</NativeNightlyRates>
<nativeRoomRate>185.57</nativeRoomRate>
<rateFrequency>B</rateFrequency>
</RateInfo>
</HotelProperty>
<hotelUrl>
http://booking.rated-hotels.co.uk/index.jsp?pageName=hotAvail&cid=409870&hotelID=188139&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=9&arrivalDay=11&departureMonth=9&departureDay=12&showInfo=true&locale=en_US¤cyCode=USD&mcicid=409870.HOTEL.XML.85419
</hotelUrl>
</Hotel>
</HotelAvailabilityListResults>
</Destination>
</DestinationResults>
and my xslt is
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
<xsl:for-each select="DestinationResults">
<xsl:for-each select="Destination">
<xsl:for-each select="HotelAvailabilityListResults">
<xsl:for-each select="Hotel">
<div style="background-color:teal;color:white;padding:4px">
<span style="font-weight:bold"><xsl:value-of select="name"/></span>
- <xsl:value-of select="city"/>
</div>
<div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
<p><xsl:value-of select="shortDescription"/>.
<span style="font-style:italic">
<xsl:value-of select="address1"/>
</span>.</p>
</div>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
</body>
</html>
This xslt works for the above xml but when there are multiple Hotel orders
in xml like below then the xslt does not produce any results.
<Hotel order="2">
<hotelId>188139</hotelId>
<name>
<![CDATA[ Hotel Magenta Paris ]]>
</name>
<address1>38 Boulevard De Magenta</address1>
<address2/>
<address3/>
<city>Paris</city>
<stateProvince/>
<country>FR</country>
<postalCode>75010</postalCode>
<latitude>48.87203</latitude>
<longitude>2.35995</longitude>
<tripAdvisorRating>4.0</tripAdvisorRating>
<fromDate>10/11/2013</fromDate>
<toDate>10/12/2013</toDate>
<shortDescription>
<![CDATA[<p><b>Property Location</b> <br
/>With a stay at Hotel Magenta Paris in Paris (Gare du Nord - Gare
de L'Est), you'll be minutes from Porte Saint-Martin and
close to Louvre Museum. This]]>
</shortDescription>
<thumbNailUrl>
http://origin-images.ian.com/hotels/1000000/890000/889000/888903/888903_22_t.jpg
</thumbNailUrl>
<propertyRating>3.0</propertyRating>
<referenceProximityDistance>-1.0</referenceProximityDistance>
<referenceProximityUnit/>
<HotelProperty>
<promoDescription>Stay 1 nights and save 10% off your
stay!</promoDescription>
<ValueAdds>
<valueAdd id="2048">Free Wireless Internet</valueAdd>
</ValueAdds>
<PromoRateInfo>
<displayCurrencyCode>USD</displayCurrencyCode>
<DisplayNightlyRates size="1">
<displayNightlyRate>152.02</displayNightlyRate>
</DisplayNightlyRates>
<displayRoomRate>168.68</displayRoomRate>
<chargeableRoomRateTotal>168.68</chargeableRoomRateTotal>
<chargeableRoomRateTaxesAndFees>16.66</chargeableRoomRateTaxesAndFees>
<taxesOnly>16.66</taxesOnly>
<salesTax>0</salesTax>
<hotelOccupancyTax>0</hotelOccupancyTax>
<nativeCurrencyCode>USD</nativeCurrencyCode>
<NativeNightlyRates size="1">
<nativeNightlyRate>152.02</nativeNightlyRate>
</NativeNightlyRates>
<nativeRoomRate>168.68</nativeRoomRate>
<rateFrequency>B</rateFrequency>
</PromoRateInfo>
<RateInfo>
<displayCurrencyCode>USD</displayCurrencyCode>
<DisplayNightlyRates size="1">
<displayNightlyRate>168.91</displayNightlyRate>
</DisplayNightlyRates>
<displayRoomRate>185.57</displayRoomRate>
<chargeableRoomRateTotal>185.57</chargeableRoomRateTotal>
<chargeableRoomRateTaxesAndFees>16.66</chargeableRoomRateTaxesAndFees>
<taxesOnly>16.66</taxesOnly>
<salesTax>0</salesTax>
<hotelOccupancyTax>0</hotelOccupancyTax>
<nativeCurrencyCode>USD</nativeCurrencyCode>
<NativeNightlyRates size="1">
<nativeNightlyRate>168.91</nativeNightlyRate>
</NativeNightlyRates>
<nativeRoomRate>185.57</nativeRoomRate>
<rateFrequency>B</rateFrequency>
</RateInfo>
</HotelProperty>
<hotelUrl>
http://booking.rated-hotels.co.uk/index.jsp?pageName=hotAvail&cid=409870&hotelID=188139&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=9&arrivalDay=11&departureMonth=9&departureDay=12&showInfo=true&locale=en_US¤cyCode=USD&mcicid=409870.HOTEL.XML.85419
</hotelUrl>
</Hotel>
Any help is much appreciated.
Regards, Jai
I am new to xslt and am trying to create html from xml using xslt.
I dont know why but my xslt works when only one element is there but not
when multiple.
I tried various ways but as said i am new to this and am not sure how to
do this any more.
Here is my xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<DestinationResults size="1">
<Destination name="Paris, FRA" order="1">
<HotelAvailabilityListResults size="10">
<Hotel order="1">
<hotelId>188139</hotelId>
<name>
<![CDATA[ Hotel Magenta Paris ]]>
</name>
<address1>38 Boulevard De Magenta</address1>
<address2/>
<address3/>
<city>Paris</city>
<stateProvince/>
<country>FR</country>
<postalCode>75010</postalCode>
<latitude>48.87203</latitude>
<longitude>2.35995</longitude>
<tripAdvisorRating>4.0</tripAdvisorRating>
<fromDate>10/11/2013</fromDate>
<toDate>10/12/2013</toDate>
<shortDescription>
<![CDATA[<p><b>Property Location</b> <br />With a
stay at Hotel Magenta Paris in Paris (Gare du Nord - Gare de L'Est),
you'll be minutes from Porte Saint-Martin and close to Louvre Museum.
This]]>
</shortDescription>
<thumbNailUrl>
http://origin-images.ian.com/hotels/1000000/890000/889000/888903/888903_22_t.jpg
</thumbNailUrl>
<propertyRating>3.0</propertyRating>
<referenceProximityDistance>-1.0</referenceProximityDistance>
<referenceProximityUnit/>
<HotelProperty>
<promoDescription>Stay 1 nights and save 10% off your
stay!</promoDescription>
<ValueAdds>
<valueAdd id="2048">Free Wireless Internet</valueAdd>
</ValueAdds>
<PromoRateInfo>
<displayCurrencyCode>USD</displayCurrencyCode>
<DisplayNightlyRates size="1">
<displayNightlyRate>152.02</displayNightlyRate>
</DisplayNightlyRates>
<displayRoomRate>168.68</displayRoomRate>
<chargeableRoomRateTotal>168.68</chargeableRoomRateTotal>
<chargeableRoomRateTaxesAndFees>16.66</chargeableRoomRateTaxesAndFees>
<taxesOnly>16.66</taxesOnly>
<salesTax>0</salesTax>
<hotelOccupancyTax>0</hotelOccupancyTax>
<nativeCurrencyCode>USD</nativeCurrencyCode>
<NativeNightlyRates size="1">
<nativeNightlyRate>152.02</nativeNightlyRate>
</NativeNightlyRates>
<nativeRoomRate>168.68</nativeRoomRate>
<rateFrequency>B</rateFrequency>
</PromoRateInfo>
<RateInfo>
<displayCurrencyCode>USD</displayCurrencyCode>
<DisplayNightlyRates size="1">
<displayNightlyRate>168.91</displayNightlyRate>
</DisplayNightlyRates>
<displayRoomRate>185.57</displayRoomRate>
<chargeableRoomRateTotal>185.57</chargeableRoomRateTotal>
<chargeableRoomRateTaxesAndFees>16.66</chargeableRoomRateTaxesAndFees>
<taxesOnly>16.66</taxesOnly>
<salesTax>0</salesTax>
<hotelOccupancyTax>0</hotelOccupancyTax>
<nativeCurrencyCode>USD</nativeCurrencyCode>
<NativeNightlyRates size="1">
<nativeNightlyRate>168.91</nativeNightlyRate>
</NativeNightlyRates>
<nativeRoomRate>185.57</nativeRoomRate>
<rateFrequency>B</rateFrequency>
</RateInfo>
</HotelProperty>
<hotelUrl>
http://booking.rated-hotels.co.uk/index.jsp?pageName=hotAvail&cid=409870&hotelID=188139&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=9&arrivalDay=11&departureMonth=9&departureDay=12&showInfo=true&locale=en_US¤cyCode=USD&mcicid=409870.HOTEL.XML.85419
</hotelUrl>
</Hotel>
</HotelAvailabilityListResults>
</Destination>
</DestinationResults>
and my xslt is
<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
<xsl:for-each select="DestinationResults">
<xsl:for-each select="Destination">
<xsl:for-each select="HotelAvailabilityListResults">
<xsl:for-each select="Hotel">
<div style="background-color:teal;color:white;padding:4px">
<span style="font-weight:bold"><xsl:value-of select="name"/></span>
- <xsl:value-of select="city"/>
</div>
<div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
<p><xsl:value-of select="shortDescription"/>.
<span style="font-style:italic">
<xsl:value-of select="address1"/>
</span>.</p>
</div>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
</body>
</html>
This xslt works for the above xml but when there are multiple Hotel orders
in xml like below then the xslt does not produce any results.
<Hotel order="2">
<hotelId>188139</hotelId>
<name>
<![CDATA[ Hotel Magenta Paris ]]>
</name>
<address1>38 Boulevard De Magenta</address1>
<address2/>
<address3/>
<city>Paris</city>
<stateProvince/>
<country>FR</country>
<postalCode>75010</postalCode>
<latitude>48.87203</latitude>
<longitude>2.35995</longitude>
<tripAdvisorRating>4.0</tripAdvisorRating>
<fromDate>10/11/2013</fromDate>
<toDate>10/12/2013</toDate>
<shortDescription>
<![CDATA[<p><b>Property Location</b> <br
/>With a stay at Hotel Magenta Paris in Paris (Gare du Nord - Gare
de L'Est), you'll be minutes from Porte Saint-Martin and
close to Louvre Museum. This]]>
</shortDescription>
<thumbNailUrl>
http://origin-images.ian.com/hotels/1000000/890000/889000/888903/888903_22_t.jpg
</thumbNailUrl>
<propertyRating>3.0</propertyRating>
<referenceProximityDistance>-1.0</referenceProximityDistance>
<referenceProximityUnit/>
<HotelProperty>
<promoDescription>Stay 1 nights and save 10% off your
stay!</promoDescription>
<ValueAdds>
<valueAdd id="2048">Free Wireless Internet</valueAdd>
</ValueAdds>
<PromoRateInfo>
<displayCurrencyCode>USD</displayCurrencyCode>
<DisplayNightlyRates size="1">
<displayNightlyRate>152.02</displayNightlyRate>
</DisplayNightlyRates>
<displayRoomRate>168.68</displayRoomRate>
<chargeableRoomRateTotal>168.68</chargeableRoomRateTotal>
<chargeableRoomRateTaxesAndFees>16.66</chargeableRoomRateTaxesAndFees>
<taxesOnly>16.66</taxesOnly>
<salesTax>0</salesTax>
<hotelOccupancyTax>0</hotelOccupancyTax>
<nativeCurrencyCode>USD</nativeCurrencyCode>
<NativeNightlyRates size="1">
<nativeNightlyRate>152.02</nativeNightlyRate>
</NativeNightlyRates>
<nativeRoomRate>168.68</nativeRoomRate>
<rateFrequency>B</rateFrequency>
</PromoRateInfo>
<RateInfo>
<displayCurrencyCode>USD</displayCurrencyCode>
<DisplayNightlyRates size="1">
<displayNightlyRate>168.91</displayNightlyRate>
</DisplayNightlyRates>
<displayRoomRate>185.57</displayRoomRate>
<chargeableRoomRateTotal>185.57</chargeableRoomRateTotal>
<chargeableRoomRateTaxesAndFees>16.66</chargeableRoomRateTaxesAndFees>
<taxesOnly>16.66</taxesOnly>
<salesTax>0</salesTax>
<hotelOccupancyTax>0</hotelOccupancyTax>
<nativeCurrencyCode>USD</nativeCurrencyCode>
<NativeNightlyRates size="1">
<nativeNightlyRate>168.91</nativeNightlyRate>
</NativeNightlyRates>
<nativeRoomRate>185.57</nativeRoomRate>
<rateFrequency>B</rateFrequency>
</RateInfo>
</HotelProperty>
<hotelUrl>
http://booking.rated-hotels.co.uk/index.jsp?pageName=hotAvail&cid=409870&hotelID=188139&mode=2&numberOfRooms=1&room-0-adult-total=2&room-0-child-total=0&arrivalMonth=9&arrivalDay=11&departureMonth=9&departureDay=12&showInfo=true&locale=en_US¤cyCode=USD&mcicid=409870.HOTEL.XML.85419
</hotelUrl>
</Hotel>
Any help is much appreciated.
Regards, Jai
Thursday, 26 September 2013
javascript input a specific character once
javascript input a specific character once
i made a function where you can only input alphabets , @ and ( . ) period.
how can i set that i can only input the "@" sign once and after that it
will automatically add "email.com" . for example i input my email like
"stackoverflow" and after i hit "@" it will automatically add "email.com"
and that "@" can only be inputted once..
here's my code
function fnEmailAlpha(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //Firefox
if ((key>96 && key<123) || (key>64 && key<90) || key==46 || key == 64
|| key == 95)
{
return true;
}
else
{
return false;
}
}
i made a function where you can only input alphabets , @ and ( . ) period.
how can i set that i can only input the "@" sign once and after that it
will automatically add "email.com" . for example i input my email like
"stackoverflow" and after i hit "@" it will automatically add "email.com"
and that "@" can only be inputted once..
here's my code
function fnEmailAlpha(e)
{
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //Firefox
if ((key>96 && key<123) || (key>64 && key<90) || key==46 || key == 64
|| key == 95)
{
return true;
}
else
{
return false;
}
}
Wednesday, 25 September 2013
ggplot2 line plot order
ggplot2 line plot order
I have a series of ordered points as shown below:
However when I try to connect the points by a line, I get the following
output:
The plot is connecting 26 to 1 and 25 to 9 and 10 (some of the errors),
instead of following the order. The code for plotting the points is given
below:
p<-ggplot(aes(x = x, y = y), data = spat_loc)
p<-p + labs(x = "x Coords (Km)", y="Y coords (Km)") +ggtitle("Locations")
p<-p + geom_point(aes(color="Red",size=2)) + geom_text(aes(label = X))
p + theme_bw()
And for plotting the line I am just using: p + geom_line((aes(x=x,
y=y)),colour="blue") + theme_bw()
The file which contains the locations have the following structure:
X x y
1 210 200
..
..
..
where X is the numeric ID and x and y are the pair of co-ordinates.
What do I need to do to make the line follow the ordering of points?
I have a series of ordered points as shown below:
However when I try to connect the points by a line, I get the following
output:
The plot is connecting 26 to 1 and 25 to 9 and 10 (some of the errors),
instead of following the order. The code for plotting the points is given
below:
p<-ggplot(aes(x = x, y = y), data = spat_loc)
p<-p + labs(x = "x Coords (Km)", y="Y coords (Km)") +ggtitle("Locations")
p<-p + geom_point(aes(color="Red",size=2)) + geom_text(aes(label = X))
p + theme_bw()
And for plotting the line I am just using: p + geom_line((aes(x=x,
y=y)),colour="blue") + theme_bw()
The file which contains the locations have the following structure:
X x y
1 210 200
..
..
..
where X is the numeric ID and x and y are the pair of co-ordinates.
What do I need to do to make the line follow the ordering of points?
Thursday, 19 September 2013
Spring oauth2 custom token issue
Spring oauth2 custom token issue
I have a requirement to generate a token manually in the code with a 3rd
party has been verified. I'm running into an issue when I have to
authenticate the token. I have created my own token store, which was
working great when not generating the manual token. I also extended the
The DefaultTokenService, but just added one method.
I have thrown in a few breakpoints and found that I'm hitting the
ProviderManager class when I'm creating my own tokens manually. But when
I'm not creating my own tokens, I'm hitting the UnanimousBased class. Not
sure if that detail helps. Going to backtrace it more, but I'm open to any
ideas.
Here is how I'm creating the token:
ConcurrentHashMap<String, String> authorizationParameters = new
ConcurrentHashMap<String, String>();
authorizationParameters.put("scope", "read");
authorizationParameters.put("username", "mobile_client");
authorizationParameters.put("client_id", "mobile-client");
authorizationParameters.put("grant", "password");
DefaultAuthorizationRequest authorizationRequest = new
DefaultAuthorizationRequest(authorizationParameters);
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
authorities.add(new GrantedAuthorityImpl("ROLE_UNTRUSTED_CLIENT"));
authorizationRequest.setAuthorities(authorities);
HashSet<String> resourceIds = new HashSet<String>();
resourceIds.add("mobile-client");
authorizationRequest.setResourceIds(resourceIds);
User userPrincipal = new User("mobile_client", "", true, true,
true, true, authorities);
UsernamePasswordAuthenticationToken authenticationToken = new
UsernamePasswordAuthenticationToken(userPrincipal, null,
authorities) ;
OAuth2Authentication authenticationRequest = new
OAuth2Authentication(authorizationRequest, authenticationToken);
authenticationRequest.setAuthenticated(true);
NoSQLTokenStore tokenStore = new NoSQLTokenStore();
CustomTokenServices tokenServices = new CustomTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore);
OAuth2AccessToken accessToken =
tokenServices.createAccessTokenForUser(authenticationRequest,
user);
This is the exception being thrown:
Mobile App 17:02:21.169 [WARN] LoggerListener - Authentication event
AuthenticationFailureProviderNotFoundEvent: mobile_client; details:
remoteAddress=::1, , tokenValue=<TOKEN>; exception: No
AuthenticationProvider found for
org.springframework.security.oauth2.provider.OAuth2Authentication
Mobile App 17:02:21.169 [DEBUG] ExceptionTranslationFilter -
Authentication exception occurred; redirecting to authentication entry
point
<org.springframework.security.authentication.ProviderNotFoundException: No
AuthenticationProvider found for
org.springframework.security.oauth2.provider.OAuth2Authentication>org.springframework.security.authentication.ProviderNotFoundException:
No AuthenticationProvider found for
org.springframework.security.oauth2.provider.OAuth2Authentication
at
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:196)
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.authenticateIfRequired(AbstractSecurityInterceptor.java:316)
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:202)
at
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
at
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:131)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
I have a requirement to generate a token manually in the code with a 3rd
party has been verified. I'm running into an issue when I have to
authenticate the token. I have created my own token store, which was
working great when not generating the manual token. I also extended the
The DefaultTokenService, but just added one method.
I have thrown in a few breakpoints and found that I'm hitting the
ProviderManager class when I'm creating my own tokens manually. But when
I'm not creating my own tokens, I'm hitting the UnanimousBased class. Not
sure if that detail helps. Going to backtrace it more, but I'm open to any
ideas.
Here is how I'm creating the token:
ConcurrentHashMap<String, String> authorizationParameters = new
ConcurrentHashMap<String, String>();
authorizationParameters.put("scope", "read");
authorizationParameters.put("username", "mobile_client");
authorizationParameters.put("client_id", "mobile-client");
authorizationParameters.put("grant", "password");
DefaultAuthorizationRequest authorizationRequest = new
DefaultAuthorizationRequest(authorizationParameters);
Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>();
authorities.add(new GrantedAuthorityImpl("ROLE_UNTRUSTED_CLIENT"));
authorizationRequest.setAuthorities(authorities);
HashSet<String> resourceIds = new HashSet<String>();
resourceIds.add("mobile-client");
authorizationRequest.setResourceIds(resourceIds);
User userPrincipal = new User("mobile_client", "", true, true,
true, true, authorities);
UsernamePasswordAuthenticationToken authenticationToken = new
UsernamePasswordAuthenticationToken(userPrincipal, null,
authorities) ;
OAuth2Authentication authenticationRequest = new
OAuth2Authentication(authorizationRequest, authenticationToken);
authenticationRequest.setAuthenticated(true);
NoSQLTokenStore tokenStore = new NoSQLTokenStore();
CustomTokenServices tokenServices = new CustomTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore);
OAuth2AccessToken accessToken =
tokenServices.createAccessTokenForUser(authenticationRequest,
user);
This is the exception being thrown:
Mobile App 17:02:21.169 [WARN] LoggerListener - Authentication event
AuthenticationFailureProviderNotFoundEvent: mobile_client; details:
remoteAddress=::1, , tokenValue=<TOKEN>; exception: No
AuthenticationProvider found for
org.springframework.security.oauth2.provider.OAuth2Authentication
Mobile App 17:02:21.169 [DEBUG] ExceptionTranslationFilter -
Authentication exception occurred; redirecting to authentication entry
point
<org.springframework.security.authentication.ProviderNotFoundException: No
AuthenticationProvider found for
org.springframework.security.oauth2.provider.OAuth2Authentication>org.springframework.security.authentication.ProviderNotFoundException:
No AuthenticationProvider found for
org.springframework.security.oauth2.provider.OAuth2Authentication
at
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:196)
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.authenticateIfRequired(AbstractSecurityInterceptor.java:316)
at
org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:202)
at
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
at
org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:131)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at
org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at
org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at
org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at
org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at
org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Why does my function keep failing my JUnit test?
Why does my function keep failing my JUnit test?
This is one of my classes that I am testing. It keeps failing the
calculateVolume() method and I am not sure why.
package shape3D;
public class Sphere implements Cloneable {
private double myRadius;
private double myVolume;
private double mySurfaceArea;
private final static double pi = 3.14;
public static void main(String args[]){
Sphere sphere = new Sphere();
}
public double calculateVolume(){
myVolume = (4/3)*pi*(Math.pow(myRadius,3));
return myVolume;
}
public double calculateSurfaceArea(){
mySurfaceArea = ((4)*(pi)*(Math.pow(myRadius,2)));
return mySurfaceArea;
}
public double getSurfaceArea(){
return this.calculateSurfaceArea();
}
public double getVolume(){
return this.calculateVolume();
}
public void setRadius(double radius2){
myRadius = radius2;
}
public String toString(){
return "Volume: " + this.getVolume() + " Surface area " +
this.getSurfaceArea();
}
public Sphere clone (){
Sphere p = new Sphere();
p.setRadius(myRadius);
return p;
}
}
Here is the JUnit test case I am using
public class sphereTest {
@Test
public void testSphere(){
shape3D.Sphere sphere = new shape3D.Sphere();
sphere.setRadius(6);
assertTrue(sphere.calculateSurfaceArea()== 452.16);
assertTrue(sphere.calculateVolume()== 904.32);
The calculateSurfaceArea() stuff passes fine but the volume is failing and
I am not sure why.
This is one of my classes that I am testing. It keeps failing the
calculateVolume() method and I am not sure why.
package shape3D;
public class Sphere implements Cloneable {
private double myRadius;
private double myVolume;
private double mySurfaceArea;
private final static double pi = 3.14;
public static void main(String args[]){
Sphere sphere = new Sphere();
}
public double calculateVolume(){
myVolume = (4/3)*pi*(Math.pow(myRadius,3));
return myVolume;
}
public double calculateSurfaceArea(){
mySurfaceArea = ((4)*(pi)*(Math.pow(myRadius,2)));
return mySurfaceArea;
}
public double getSurfaceArea(){
return this.calculateSurfaceArea();
}
public double getVolume(){
return this.calculateVolume();
}
public void setRadius(double radius2){
myRadius = radius2;
}
public String toString(){
return "Volume: " + this.getVolume() + " Surface area " +
this.getSurfaceArea();
}
public Sphere clone (){
Sphere p = new Sphere();
p.setRadius(myRadius);
return p;
}
}
Here is the JUnit test case I am using
public class sphereTest {
@Test
public void testSphere(){
shape3D.Sphere sphere = new shape3D.Sphere();
sphere.setRadius(6);
assertTrue(sphere.calculateSurfaceArea()== 452.16);
assertTrue(sphere.calculateVolume()== 904.32);
The calculateSurfaceArea() stuff passes fine but the volume is failing and
I am not sure why.
How can I use bootstrap-sass with spree?
How can I use bootstrap-sass with spree?
I want to do responsive the spree layouts using bootstrap.. I'm using
rails 3.2.14 with spree 2.0.4 and bootstrap-sass 2.3.2.2
I want to do responsive the spree layouts using bootstrap.. I'm using
rails 3.2.14 with spree 2.0.4 and bootstrap-sass 2.3.2.2
regex to parse out preceding backslash
regex to parse out preceding backslash
In JavaScript, I am trying to split a string by ';' if not preceded
(escaped) by '\'.
The string might look like:
asd;123;ä\;;33;
So the above string should be split into:
asd
123
ä\;
33
I thought [^\]; would do the trick but this selects the preceding
character of ';' as well if it is not a '\'. I want only the ';' though
without its preceding character.
In JavaScript, I am trying to split a string by ';' if not preceded
(escaped) by '\'.
The string might look like:
asd;123;ä\;;33;
So the above string should be split into:
asd
123
ä\;
33
I thought [^\]; would do the trick but this selects the preceding
character of ';' as well if it is not a '\'. I want only the ';' though
without its preceding character.
Error Creating SSL Context - Qt
Error Creating SSL Context - Qt
I tried everything mentioned in this Question
but nothing worked. The binary works fine on Windows 64-bit, but almost
always shows the error
Error Creating SSL Context()
on Windows 32-bit. I tried the demo http client example.
I tried everything mentioned in this Question
but nothing worked. The binary works fine on Windows 64-bit, but almost
always shows the error
Error Creating SSL Context()
on Windows 32-bit. I tried the demo http client example.
dynamic where clause when dropdown selected
dynamic where clause when dropdown selected
I have multiple dropdowns which is taking information from sql there I
have no problems and show as per below:
<asp:DropDownList ID="ports" runat="server" AutoPostBack="True"
DataSourceID="AccessDataSource4" DataTextField="ports"
DataValueField="ports">
</asp:DropDownList>
I have also a gridview which is showing information from other accessdata
source as per below:
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/kdatabase.accdb"
SelectCommand="SELECT * FROM [Devices] WHERE ([design] LIKE
@design) AND ([ports] LIKE @ports) ">
<SelectParameters>
<asp:ControlParameter DefaultValue="%" ControlID="design"
Name="design" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter DefaultValue="%" ControlID="ports"
Name="ports" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:AccessDataSource>
Which is working fine but not %100 that I am looking for.What I want is
that Where Clause is addded under Select command for the database only if
I change the dropdown list.If i did not change it I want that my gridview
show all the results.How I can do it.Static dropdown is easy but I have
dynamic dropdown.
I have multiple dropdowns which is taking information from sql there I
have no problems and show as per below:
<asp:DropDownList ID="ports" runat="server" AutoPostBack="True"
DataSourceID="AccessDataSource4" DataTextField="ports"
DataValueField="ports">
</asp:DropDownList>
I have also a gridview which is showing information from other accessdata
source as per below:
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="~/kdatabase.accdb"
SelectCommand="SELECT * FROM [Devices] WHERE ([design] LIKE
@design) AND ([ports] LIKE @ports) ">
<SelectParameters>
<asp:ControlParameter DefaultValue="%" ControlID="design"
Name="design" PropertyName="SelectedValue" Type="String" />
<asp:ControlParameter DefaultValue="%" ControlID="ports"
Name="ports" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:AccessDataSource>
Which is working fine but not %100 that I am looking for.What I want is
that Where Clause is addded under Select command for the database only if
I change the dropdown list.If i did not change it I want that my gridview
show all the results.How I can do it.Static dropdown is easy but I have
dynamic dropdown.
Apps UIWebView stuck on landscape on iPad on iOS 7
Apps UIWebView stuck on landscape on iPad on iOS 7
I have an iOS 5 + app I am getting ready for iOS 7.
I have a standard TabBar based app loading in viewcontrollers, one of
which loads in a webView.
This webview has a landscape and portrait mode as the app can be rotated,
this works fine on all devices except iPad running iOS 7.
The issue being the webview is always displayed as landscape on iPad on
iOS 7 irrespective of the orientation, iOS 7 gets rid of the 2x button
that you used to get with iPhone apps running on an iPad so it is faux
full screen.
The app opens in portrait mode, if I rotate the iPad everything else
rotates - all other views adjust and reposition - except the html in the
webview - it is stuck on landscape.
This happens on device and simulator
The question I suppose is why? has anyone else had experience of this?
Many thanks
I have an iOS 5 + app I am getting ready for iOS 7.
I have a standard TabBar based app loading in viewcontrollers, one of
which loads in a webView.
This webview has a landscape and portrait mode as the app can be rotated,
this works fine on all devices except iPad running iOS 7.
The issue being the webview is always displayed as landscape on iPad on
iOS 7 irrespective of the orientation, iOS 7 gets rid of the 2x button
that you used to get with iPhone apps running on an iPad so it is faux
full screen.
The app opens in portrait mode, if I rotate the iPad everything else
rotates - all other views adjust and reposition - except the html in the
webview - it is stuck on landscape.
This happens on device and simulator
The question I suppose is why? has anyone else had experience of this?
Many thanks
Wednesday, 18 September 2013
Angular.js with Jade and Express - data binding not working
Angular.js with Jade and Express - data binding not working
I'm learning AngularJS with Dan Wahlin's tutorial
(http://youtu.be/i9MHigUZKEM?t=13m35s). I have the following code in my
views/index.jade:
!!! 5
html(data-ng-app='')
head
title Angular Tutorial
body
| Name:
br
input(type='text', data-ng-model='name') | {{name}}
script(src='https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js',
type='text/javascript')
But when I run the app, and type anything in the Name box, it does not
display the text like it does in the tutorial. What am I doing wrong?
I'm learning AngularJS with Dan Wahlin's tutorial
(http://youtu.be/i9MHigUZKEM?t=13m35s). I have the following code in my
views/index.jade:
!!! 5
html(data-ng-app='')
head
title Angular Tutorial
body
| Name:
br
input(type='text', data-ng-model='name') | {{name}}
script(src='https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js',
type='text/javascript')
But when I run the app, and type anything in the Name box, it does not
display the text like it does in the tutorial. What am I doing wrong?
Error: no known conversion for
Error: no known conversion for
So this is what I currently have, with the Scanner provided by my professor.
#include "Similarity.h"
#include "Scanner.h"
using namespace std;
int Similarity::readData(Scanner inFile){
int similarityInputSize;
vector< vector<int> > containingVector;
bool nextValueFound;
similarityInputSize = inFile.nextInt();
int lineCount = 0;
while(inFile.hasNext()){
containingVector.push_back(vector<int>());
for(int i = 0; i < similarityInputSize; i++){
containingVector[lineCount].push_back(inFile.nextInt());
}
lineCount++;
}
for(int i = 0; i < containingVector.size(); i++){
for(int j = 0; j < similarityInputSize; i++){
cout << containingVector[i][j] << " ";
}
cout << endl;
}
return 0;
}
The Main class is given to us and involves a call by value not by
reference, which my professor got to work.
the errors I receive are:
In file included from /usr/include/c++/4.7/ios:43:0,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from ../../Utilities/Utils.h:17,
from Main.h:11:
/usr/include/c++/4.7/bits/ios_base.h: In copy constructor
'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)':
/usr/include/c++/4.7/bits/ios_base.h:788:5: error:
'std::ios_base::ios_base(const std::ios_base&)' is private
In file included from /usr/include/c++/4.7/ios:45:0,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from ../../Utilities/Utils.h:17,
from Main.h:11:
/usr/include/c++/4.7/bits/basic_ios.h:64:11: error: within this context
In file included from ../../Utilities/Utils.h:18:0,
from Main.h:11:
/usr/include/c++/4.7/fstream: In copy constructor
'std::basic_ifstream<char>::basic_ifstream(const
std::basic_ifstream<char>&)':
/usr/include/c++/4.7/fstream:420:11: note: synthesized method
'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)' first
required here
In file included from /usr/include/c++/4.7/ios:44:0,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from ../../Utilities/Utils.h:17,
from Main.h:11:
/usr/include/c++/4.7/streambuf: In copy constructor
'std::basic_filebuf<char>::basic_filebuf(const
std::basic_filebuf<char>&)':
/usr/include/c++/4.7/streambuf:800:7: error:
'std::basic_streambuf<_CharT, _Traits>::basic_streambuf(const
__streambuf_type&) [with _CharT = char; _Traits =
std::char_traits<char>; std::basic_streambuf<_CharT,
_Traits>::__streambuf_type = std::basic_streambuf<char>]' is private
In file included from ../../Utilities/Utils.h:18:0,
from Main.h:11:
/usr/include/c++/4.7/fstream:69:11: error: within this context
/usr/include/c++/4.7/fstream: In copy constructor
'std::basic_ifstream<char>::basic_ifstream(const
std::basic_ifstream<char>&)':
/usr/include/c++/4.7/fstream:420:11: note: synthesized method
'std::basic_filebuf<char>::basic_filebuf(const
std::basic_filebuf<char>&)' first required here
In file included from Main.h:12:0:
../../Utilities/Scanner.h: In copy constructor 'Scanner::Scanner(const
Scanner&)':
../../Utilities/Scanner.h:27:7: note: synthesized method
'std::basic_ifstream<char>::basic_ifstream(const
std::basic_ifstream<char>&)' first required here
Main.cpp: In function 'int main(int, char**)':
Main.cpp:58:31: note: synthesized method 'Scanner::Scanner(const
Scanner&)' first required here
In file included from Main.h:14:0:
Similarity.h:23:9: error: initializing argument 1 of 'int
Similarity::readData(Scanner)'
So I don't quite understand what happened. Everywhere I looked said that
the issue would be fixed by a call by reference not by value. However, his
provided code does not include any call by references, which makes me
assume its a more subtle error (or its so big that it's blinding me).
Nevertheless, I changed it anyways and it gave me these errors:
Similarity.cpp:12:5: error: prototype for 'int
Similarity::readData(Scanner&)' does not match any in class 'Similarity'
Similarity.h:23:9: error: candidate is: int Similarity::readData(Scanner)
Main.cpp: In function 'int main(int, char**)':
Main.cpp:58:32: error: no matching function for call to
'Similarity::readData(Scanner*)'
Main.cpp:58:32: note: candidate is:
In file included from Main.h:14:0:
Similarity.h:23:9: note: int Similarity::readData(Scanner)
Similarity.h:23:9: note: no known conversion for argument 1 from
'Scanner*' to 'Scanner'
Anything you can tell me at all will be a help.
Thanks in advance!
So this is what I currently have, with the Scanner provided by my professor.
#include "Similarity.h"
#include "Scanner.h"
using namespace std;
int Similarity::readData(Scanner inFile){
int similarityInputSize;
vector< vector<int> > containingVector;
bool nextValueFound;
similarityInputSize = inFile.nextInt();
int lineCount = 0;
while(inFile.hasNext()){
containingVector.push_back(vector<int>());
for(int i = 0; i < similarityInputSize; i++){
containingVector[lineCount].push_back(inFile.nextInt());
}
lineCount++;
}
for(int i = 0; i < containingVector.size(); i++){
for(int j = 0; j < similarityInputSize; i++){
cout << containingVector[i][j] << " ";
}
cout << endl;
}
return 0;
}
The Main class is given to us and involves a call by value not by
reference, which my professor got to work.
the errors I receive are:
In file included from /usr/include/c++/4.7/ios:43:0,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from ../../Utilities/Utils.h:17,
from Main.h:11:
/usr/include/c++/4.7/bits/ios_base.h: In copy constructor
'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)':
/usr/include/c++/4.7/bits/ios_base.h:788:5: error:
'std::ios_base::ios_base(const std::ios_base&)' is private
In file included from /usr/include/c++/4.7/ios:45:0,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from ../../Utilities/Utils.h:17,
from Main.h:11:
/usr/include/c++/4.7/bits/basic_ios.h:64:11: error: within this context
In file included from ../../Utilities/Utils.h:18:0,
from Main.h:11:
/usr/include/c++/4.7/fstream: In copy constructor
'std::basic_ifstream<char>::basic_ifstream(const
std::basic_ifstream<char>&)':
/usr/include/c++/4.7/fstream:420:11: note: synthesized method
'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)' first
required here
In file included from /usr/include/c++/4.7/ios:44:0,
from /usr/include/c++/4.7/ostream:40,
from /usr/include/c++/4.7/iostream:40,
from ../../Utilities/Utils.h:17,
from Main.h:11:
/usr/include/c++/4.7/streambuf: In copy constructor
'std::basic_filebuf<char>::basic_filebuf(const
std::basic_filebuf<char>&)':
/usr/include/c++/4.7/streambuf:800:7: error:
'std::basic_streambuf<_CharT, _Traits>::basic_streambuf(const
__streambuf_type&) [with _CharT = char; _Traits =
std::char_traits<char>; std::basic_streambuf<_CharT,
_Traits>::__streambuf_type = std::basic_streambuf<char>]' is private
In file included from ../../Utilities/Utils.h:18:0,
from Main.h:11:
/usr/include/c++/4.7/fstream:69:11: error: within this context
/usr/include/c++/4.7/fstream: In copy constructor
'std::basic_ifstream<char>::basic_ifstream(const
std::basic_ifstream<char>&)':
/usr/include/c++/4.7/fstream:420:11: note: synthesized method
'std::basic_filebuf<char>::basic_filebuf(const
std::basic_filebuf<char>&)' first required here
In file included from Main.h:12:0:
../../Utilities/Scanner.h: In copy constructor 'Scanner::Scanner(const
Scanner&)':
../../Utilities/Scanner.h:27:7: note: synthesized method
'std::basic_ifstream<char>::basic_ifstream(const
std::basic_ifstream<char>&)' first required here
Main.cpp: In function 'int main(int, char**)':
Main.cpp:58:31: note: synthesized method 'Scanner::Scanner(const
Scanner&)' first required here
In file included from Main.h:14:0:
Similarity.h:23:9: error: initializing argument 1 of 'int
Similarity::readData(Scanner)'
So I don't quite understand what happened. Everywhere I looked said that
the issue would be fixed by a call by reference not by value. However, his
provided code does not include any call by references, which makes me
assume its a more subtle error (or its so big that it's blinding me).
Nevertheless, I changed it anyways and it gave me these errors:
Similarity.cpp:12:5: error: prototype for 'int
Similarity::readData(Scanner&)' does not match any in class 'Similarity'
Similarity.h:23:9: error: candidate is: int Similarity::readData(Scanner)
Main.cpp: In function 'int main(int, char**)':
Main.cpp:58:32: error: no matching function for call to
'Similarity::readData(Scanner*)'
Main.cpp:58:32: note: candidate is:
In file included from Main.h:14:0:
Similarity.h:23:9: note: int Similarity::readData(Scanner)
Similarity.h:23:9: note: no known conversion for argument 1 from
'Scanner*' to 'Scanner'
Anything you can tell me at all will be a help.
Thanks in advance!
How to set the height of a floated div to the same height of its neighbour
How to set the height of a floated div to the same height of its neighbour
I am trying to create a simple 2 column layout with a header and a footer.
I have the following HTML
<body>
<div id="header">
<h1>Title Bar</h1>
</div>
<div id="content">
<div id="left">
left
</div>
<div id="right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc
elementum neque id eros auctor tristique. Fusce quam lorem,
vestibulum ut magna et, cursus molestie libero. Suspendisse sed
mauris vitae diam mattis pellentesque. Nulla neque tortor,
varius quis augue vel, commodo tincidunt elit. Maecenas vel odio
nec velit faucibus fringilla. Pellentesque habitant morbi
tristique senectus et netus et malesuada fames ac turpis
egestas. Vestibulum arcu libero, auctor vitae urna eget, blandit
fringilla justo. Fusce eu enim id nisi condimentum dictum sit
amet non lectus.
Aenean at nulla odio. Vestibulum eleifend massa vitae velit tempor, non
auctor velit imperdiet. Nunc ac odio eu justo pretium luctus. Nulla
vestibulum urna sed est fermentum aliquam. Etiam eget erat eu tortor
dictum rhoncus a nec justo. Sed eu dui ut leo lobortis laoreet quis sed
sem. Nulla consectetur augue tristique dignissim viverra. Proin tincidunt
tincidunt libero a iaculis. Etiam leo elit, cursus at velit sed, faucibus
pretium leo. Ut viverra mattis sodales. Morbi hendrerit quam eu est
dignissim congue. Pellentesque quis metus commodo sapien interdum rutrum
pellentesque at risus. Sed tempor, orci nec tincidunt dictum, turpis purus
mattis enim, ut sodales odio arcu quis sem. Praesent vitae justo lorem.
Nam ultrices enim at consectetur vehicula. Ut luctus interdum urna, rutrum
luctus orci varius vel.
Integer pharetra nisi vitae massa condimentum, ac hendrerit magna
commodo. Pellentesque sit amet neque ac mauris hendrerit scelerisque
quis nec sapien. Nullam tempor odio sed tristique interdum. Donec non
aliquet quam. Nunc ac adipiscing tortor. Mauris nec nisl accumsan,
ullamcorper metus eu, dictum mi. Mauris id adipiscing lectus. Morbi
dignissim scelerisque purus ut ullamcorper. Nu
nc placerat ipsum tortor, quis pretium est sagittis nec. In lacus eros,
volutpat eu convallis a, ullamcorper vel leo. Quisque vel orci ultricies,
molestie nisi non, congue leo. Nulla orci metus, vehicula at laoreet ut,
congue nec sem. Proin tempor justo ut odio vestibulum suscipit in a eros.
Sed fermentum et sapien id aliquam. Donec at erat bibendum, fringilla odio
sit amet, sagittis nibh.
Morbi accumsan ullamcorper leo vel viverra. In ac imperdiet
libero, id cursus eros. Morbi sed auctor quam, ac ullamcorper
metus. Morbi et vestibulum justo, et volutpat libero. Duis pretium
magna sapien, at porta justo sodales ve
l. Sed consequat magna odio, eu mattis risus malesuada vel. Aliquam
tristique accumsan fermentum. Morbi interdum nunc vitae viverra
pulvinar.
Donec neque magna, sodales dapibus imperdiet non, suscipit eget ipsum.
Etiam nec dolor ut nisi pharetra dictum non eget augue. Etiam
tincidunt mi id est euismod, ut venenatis neque tempus. Praesent
lacinia risus metus, at condimentum diam vestibulum et. Integer ac mi
nec enim facilisis pharetra. Nunc sed nibh libero. Duis imperdiet
sapien id euismod viverra. Integer aliquam metus a nulla tincidunt
eleifend. Donec a porttitor tortor. Cum sociis natoque penatibus et
magnis dis parturient montes, nascetur ridiculus mus. Aliquam
convallis aliquam dolor. Morbi eu velit quam. Nullam sed neque id
risus aliquam lobortis. Sed vel pulvinar velit, id varius mauris. Sed
justo nunc, laoreet eu velit et, pulvinar eleifend lacus. Phasellus
tristique orci vitae dignissim imperdiet.
</div>
</div>
<div id="footer">
<h5>Footer </h5>
</div>
</body>
and the following css
body {
background-color: red;
margin: 0px;
}
body h1 {
margin: 0px;
}
#header {
background-color: blue;
color: white;
height: 80px;
}
#content {
width: 700px;
}
#left {
background-color: black;
color: pink;
float: left;
width: 100px;
height: 100%;
}
#right {
background-color: lightgreen;
color: brown;
}
#footer {
background-color: yellow;
color: blue;
clear: both;
height: 40px;
}
I want to make sure that the height of the left Div is the same as the
height of the right div, regardless of what content is in the right div.
To do this I reverted to java script with this
$(document).ready(function () {
adjustLeftHeight();
});
$(window).resize(function () {
adjustLeftHeight();
});
function adjustLeftHeight() {
$("#left").height($("#content").height());
}
This doesn't quite work in that when the adjustLeftHeight is executed its
sets the lefts height to the height of the content div, but because of the
extra space taken up by the increase in the height of the left div the
content in the right div gets pushed down increasing the height of the
right div and leaving a gap between the height of the 2 divs.
see this fiddle for a worked example http://jsfiddle.net/W3P4U/
Is there a way to achieve a 2 column layout where the height of both
columns is the height of the tallest column.
I am trying to create a simple 2 column layout with a header and a footer.
I have the following HTML
<body>
<div id="header">
<h1>Title Bar</h1>
</div>
<div id="content">
<div id="left">
left
</div>
<div id="right">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc
elementum neque id eros auctor tristique. Fusce quam lorem,
vestibulum ut magna et, cursus molestie libero. Suspendisse sed
mauris vitae diam mattis pellentesque. Nulla neque tortor,
varius quis augue vel, commodo tincidunt elit. Maecenas vel odio
nec velit faucibus fringilla. Pellentesque habitant morbi
tristique senectus et netus et malesuada fames ac turpis
egestas. Vestibulum arcu libero, auctor vitae urna eget, blandit
fringilla justo. Fusce eu enim id nisi condimentum dictum sit
amet non lectus.
Aenean at nulla odio. Vestibulum eleifend massa vitae velit tempor, non
auctor velit imperdiet. Nunc ac odio eu justo pretium luctus. Nulla
vestibulum urna sed est fermentum aliquam. Etiam eget erat eu tortor
dictum rhoncus a nec justo. Sed eu dui ut leo lobortis laoreet quis sed
sem. Nulla consectetur augue tristique dignissim viverra. Proin tincidunt
tincidunt libero a iaculis. Etiam leo elit, cursus at velit sed, faucibus
pretium leo. Ut viverra mattis sodales. Morbi hendrerit quam eu est
dignissim congue. Pellentesque quis metus commodo sapien interdum rutrum
pellentesque at risus. Sed tempor, orci nec tincidunt dictum, turpis purus
mattis enim, ut sodales odio arcu quis sem. Praesent vitae justo lorem.
Nam ultrices enim at consectetur vehicula. Ut luctus interdum urna, rutrum
luctus orci varius vel.
Integer pharetra nisi vitae massa condimentum, ac hendrerit magna
commodo. Pellentesque sit amet neque ac mauris hendrerit scelerisque
quis nec sapien. Nullam tempor odio sed tristique interdum. Donec non
aliquet quam. Nunc ac adipiscing tortor. Mauris nec nisl accumsan,
ullamcorper metus eu, dictum mi. Mauris id adipiscing lectus. Morbi
dignissim scelerisque purus ut ullamcorper. Nu
nc placerat ipsum tortor, quis pretium est sagittis nec. In lacus eros,
volutpat eu convallis a, ullamcorper vel leo. Quisque vel orci ultricies,
molestie nisi non, congue leo. Nulla orci metus, vehicula at laoreet ut,
congue nec sem. Proin tempor justo ut odio vestibulum suscipit in a eros.
Sed fermentum et sapien id aliquam. Donec at erat bibendum, fringilla odio
sit amet, sagittis nibh.
Morbi accumsan ullamcorper leo vel viverra. In ac imperdiet
libero, id cursus eros. Morbi sed auctor quam, ac ullamcorper
metus. Morbi et vestibulum justo, et volutpat libero. Duis pretium
magna sapien, at porta justo sodales ve
l. Sed consequat magna odio, eu mattis risus malesuada vel. Aliquam
tristique accumsan fermentum. Morbi interdum nunc vitae viverra
pulvinar.
Donec neque magna, sodales dapibus imperdiet non, suscipit eget ipsum.
Etiam nec dolor ut nisi pharetra dictum non eget augue. Etiam
tincidunt mi id est euismod, ut venenatis neque tempus. Praesent
lacinia risus metus, at condimentum diam vestibulum et. Integer ac mi
nec enim facilisis pharetra. Nunc sed nibh libero. Duis imperdiet
sapien id euismod viverra. Integer aliquam metus a nulla tincidunt
eleifend. Donec a porttitor tortor. Cum sociis natoque penatibus et
magnis dis parturient montes, nascetur ridiculus mus. Aliquam
convallis aliquam dolor. Morbi eu velit quam. Nullam sed neque id
risus aliquam lobortis. Sed vel pulvinar velit, id varius mauris. Sed
justo nunc, laoreet eu velit et, pulvinar eleifend lacus. Phasellus
tristique orci vitae dignissim imperdiet.
</div>
</div>
<div id="footer">
<h5>Footer </h5>
</div>
</body>
and the following css
body {
background-color: red;
margin: 0px;
}
body h1 {
margin: 0px;
}
#header {
background-color: blue;
color: white;
height: 80px;
}
#content {
width: 700px;
}
#left {
background-color: black;
color: pink;
float: left;
width: 100px;
height: 100%;
}
#right {
background-color: lightgreen;
color: brown;
}
#footer {
background-color: yellow;
color: blue;
clear: both;
height: 40px;
}
I want to make sure that the height of the left Div is the same as the
height of the right div, regardless of what content is in the right div.
To do this I reverted to java script with this
$(document).ready(function () {
adjustLeftHeight();
});
$(window).resize(function () {
adjustLeftHeight();
});
function adjustLeftHeight() {
$("#left").height($("#content").height());
}
This doesn't quite work in that when the adjustLeftHeight is executed its
sets the lefts height to the height of the content div, but because of the
extra space taken up by the increase in the height of the left div the
content in the right div gets pushed down increasing the height of the
right div and leaving a gap between the height of the 2 divs.
see this fiddle for a worked example http://jsfiddle.net/W3P4U/
Is there a way to achieve a 2 column layout where the height of both
columns is the height of the tallest column.
Trouble reading next int
Trouble reading next int
so i failed on my last question -__-
So I want a program to read integers from a text file. The data file looks
like this:
5 4
3 5
4 5
3 2
(ignore the spaces between the lines)
The first number of each row is the par, and the second number is the
score. Because 5 - 4 = 1, the score is one under par (which is a birdie).
My code for the first line:
in = new Scanner (dataFile);
System.out.println("Golf Scores: ");
String line1 = in.nextLine();
System.out.println("Score 1: " + line1);
int par1 = in.nextInt();
System.out.println("Par is: " + par1);
When I run it, I get this:
Golf Scores: Score 1: 5 4 Par is: 3
So the par and score shows up correctly. However, the displayed par shows
the par of the next line from the text file. I want it to show "5" again.
I tried putting the in.nextInt before the in.nextLine, but when I tried
that I got this
Golf Scores: Score 1: 4 Par is: 5
so i failed on my last question -__-
So I want a program to read integers from a text file. The data file looks
like this:
5 4
3 5
4 5
3 2
(ignore the spaces between the lines)
The first number of each row is the par, and the second number is the
score. Because 5 - 4 = 1, the score is one under par (which is a birdie).
My code for the first line:
in = new Scanner (dataFile);
System.out.println("Golf Scores: ");
String line1 = in.nextLine();
System.out.println("Score 1: " + line1);
int par1 = in.nextInt();
System.out.println("Par is: " + par1);
When I run it, I get this:
Golf Scores: Score 1: 5 4 Par is: 3
So the par and score shows up correctly. However, the displayed par shows
the par of the next line from the text file. I want it to show "5" again.
I tried putting the in.nextInt before the in.nextLine, but when I tried
that I got this
Golf Scores: Score 1: 4 Par is: 5
android-how to detect key presses from a Service?
android-how to detect key presses from a Service?
it is possible to detect when the back key is pressed via overriding
onKeyDown in an Activity:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
//do your work
return true;
}
return super.onKeyDown(keyCode, event);
}
now, how to detect that from a Service?
it is possible to detect when the back key is pressed via overriding
onKeyDown in an Activity:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
//do your work
return true;
}
return super.onKeyDown(keyCode, event);
}
now, how to detect that from a Service?
replace a string of characters with the line number
replace a string of characters with the line number
I have a text file that has approximately 3,000 lines. 99% of the time I
need all 3,000 lines. However, periodically I will grep out the lines I
need and direct the output to another text file to use.
The only problem I have in doing so, is: Embedded in the text file is a 6
character string of numbers that indicate the line number. In order to use
the file, this area needs to be correctly renumbered...(I don't need to
re-sort the data, but I need to replace the current six characters with
the new line number. and it must be padded with zeros! Unfortuantely the
entire rows is one long row of data with no field separators!
For example, my first three rows might look something like:
20130918082020ZZ000001RANDOMDATAFOLLOWSAFTERTHISABCDEFGH
20130810112000ZZ000999MORERANDOMDATAFOLLOWSAFTERTHISABCD
20130810112000ZZ000027SILLMORERANDOMDATAFOLLOWSAFTERTHIS
The six characters at positions 17-22 (Immediately following the "ZZ"),
need be renumbered based on the current row number...so the above needs to
look like:
20130918082020ZZ000001RANDOMDATAFOLLOWSAFTERTHISABCDEFGH
20130810112000ZZ000002MORERANDOMDATAFOLLOWSAFTERTHISABCD
20130810112000ZZ000003SILLMORERANDOMDATAFOLLOWSAFTERTHIS
Any ideas would be greatly appreciated!
Thanks, KSL.
I have a text file that has approximately 3,000 lines. 99% of the time I
need all 3,000 lines. However, periodically I will grep out the lines I
need and direct the output to another text file to use.
The only problem I have in doing so, is: Embedded in the text file is a 6
character string of numbers that indicate the line number. In order to use
the file, this area needs to be correctly renumbered...(I don't need to
re-sort the data, but I need to replace the current six characters with
the new line number. and it must be padded with zeros! Unfortuantely the
entire rows is one long row of data with no field separators!
For example, my first three rows might look something like:
20130918082020ZZ000001RANDOMDATAFOLLOWSAFTERTHISABCDEFGH
20130810112000ZZ000999MORERANDOMDATAFOLLOWSAFTERTHISABCD
20130810112000ZZ000027SILLMORERANDOMDATAFOLLOWSAFTERTHIS
The six characters at positions 17-22 (Immediately following the "ZZ"),
need be renumbered based on the current row number...so the above needs to
look like:
20130918082020ZZ000001RANDOMDATAFOLLOWSAFTERTHISABCDEFGH
20130810112000ZZ000002MORERANDOMDATAFOLLOWSAFTERTHISABCD
20130810112000ZZ000003SILLMORERANDOMDATAFOLLOWSAFTERTHIS
Any ideas would be greatly appreciated!
Thanks, KSL.
JQuery $(this) is undefined in .each()
JQuery $(this) is undefined in .each()
Here is a function that take a divs id and an array of fields inside that
div.
Exemple:
section="div1",
fields=JSON.stringify({txtFNoneExp:$('#txtFNoneExp').val(),
txtFNoneDate:$('#txtFNoneDate').val()})
The function send those over to the server VIA AJAX:
function AJAXValidation(section, fields)
{
var request = $.ajax(
{
url: "ProcessJRT.php",
type: "POST",
contentType:"application/x-www-form-urlencoded;charset=UTF-8",
data:
{
validate:section,
array:fields
}
});
request.done(
function(message)
{
var div = document.createElement('div');
//create a separate document to append message
$(div).html(message);
//Append message
$('#' + section + " .AJAXValidate").attr('title', '');
//find the fields that has the class AJAXValidate
//and reset there title attribute to ''
$(".AJAXValidate").removeClass('AJAXValidate');
//remove the class
$(div).children().each
(
//for each divs in the second document
function(i)
{
//HERE is the problem
//If I log $(div).children() I can see what is inside
//But I do the log below $(this) is undefined.
//Here is my question: Why is it undefined?
console.log($(this));
$('#' + $(this).attr('name')).attr('title', $(this).html());
$('#' + $(this).attr('name')).addClass('AJAXValidate');
}
);
if($('#'+section+' .AJAXValidate').length > 0)
{
$('#'+section+' input[type="submit"]').attr('disabled', true);
}
else
{
$('#'+section+' input[type=submit]').attr('disabled', false);
}
});
}
And than the server send back message that might contains multiple divs
like this:
<div name='txtFNoneExp'>This is a test. </div>
...
If you checked out the code you'll see that my code work fine exepte that
the $(this) in the .each(); is undefined.
A call this function else where in my page and it work just fine!
Thanks!
Here is a function that take a divs id and an array of fields inside that
div.
Exemple:
section="div1",
fields=JSON.stringify({txtFNoneExp:$('#txtFNoneExp').val(),
txtFNoneDate:$('#txtFNoneDate').val()})
The function send those over to the server VIA AJAX:
function AJAXValidation(section, fields)
{
var request = $.ajax(
{
url: "ProcessJRT.php",
type: "POST",
contentType:"application/x-www-form-urlencoded;charset=UTF-8",
data:
{
validate:section,
array:fields
}
});
request.done(
function(message)
{
var div = document.createElement('div');
//create a separate document to append message
$(div).html(message);
//Append message
$('#' + section + " .AJAXValidate").attr('title', '');
//find the fields that has the class AJAXValidate
//and reset there title attribute to ''
$(".AJAXValidate").removeClass('AJAXValidate');
//remove the class
$(div).children().each
(
//for each divs in the second document
function(i)
{
//HERE is the problem
//If I log $(div).children() I can see what is inside
//But I do the log below $(this) is undefined.
//Here is my question: Why is it undefined?
console.log($(this));
$('#' + $(this).attr('name')).attr('title', $(this).html());
$('#' + $(this).attr('name')).addClass('AJAXValidate');
}
);
if($('#'+section+' .AJAXValidate').length > 0)
{
$('#'+section+' input[type="submit"]').attr('disabled', true);
}
else
{
$('#'+section+' input[type=submit]').attr('disabled', false);
}
});
}
And than the server send back message that might contains multiple divs
like this:
<div name='txtFNoneExp'>This is a test. </div>
...
If you checked out the code you'll see that my code work fine exepte that
the $(this) in the .each(); is undefined.
A call this function else where in my page and it work just fine!
Thanks!
How can I include custom jquery slider for related products Magento 1.7.0.2
How can I include custom jquery slider for related products Magento 1.7.0.2
I am trying to build a custom jquery slider in the Product page meaning
the view.phtml in Magento 1.7.0.2
The code below is working and It fetches me the Related Products
<?php $related_prods = $_product->getRelatedProductIds(); ?>
<?php foreach($related_prods as $related): ?>
<?php $_rel = Mage::getModel('catalog/product')->load($related); ?>
<?php echo $_rel->getName(); ?>
<img src="<?php echo $_rel->getImageUrl(); ?>"/>
<?php endforeach; ?>
I would like to include this code with a horizontal jquery slider but I
haven't found something yet.
Does anyone has a horizontal jquery slider to include the php code above?
I am trying to build a custom jquery slider in the Product page meaning
the view.phtml in Magento 1.7.0.2
The code below is working and It fetches me the Related Products
<?php $related_prods = $_product->getRelatedProductIds(); ?>
<?php foreach($related_prods as $related): ?>
<?php $_rel = Mage::getModel('catalog/product')->load($related); ?>
<?php echo $_rel->getName(); ?>
<img src="<?php echo $_rel->getImageUrl(); ?>"/>
<?php endforeach; ?>
I would like to include this code with a horizontal jquery slider but I
haven't found something yet.
Does anyone has a horizontal jquery slider to include the php code above?
tsql put values into single row
tsql put values into single row
this is my issue:
given the result of a select statement that is inserted into a cursor, how
can I put these values into just one row?
for example given a b c how can I achieve a,b,c ?
this is my issue:
given the result of a select statement that is inserted into a cursor, how
can I put these values into just one row?
for example given a b c how can I achieve a,b,c ?
Tuesday, 17 September 2013
How to get content of an element in the html returned by jquery post
How to get content of an element in the html returned by jquery post
I have a jQuery post request which return a tabular data in html format
This is the jQuery post
jQuery('#chem_search').submit(function(e){
e.preventDefault();
var itemcode=jQuery('[name="itemcode"]').val();
jQuery.post("chemical_search_query.php", {"itemcode":itemcode},
function(data) {
jQuery('#type2').html(data);
});
});
the data returned by the ajax request is like this
echo "<div id='dar'><table class='s_report'><tr><th>Item
Code</th><th>Description</th><th>Unit</th><th>Op. Stock</th><th>Recd.
Qty</th><th>Total Receipts</th><th>Used Qty</th><th>Available
Stock</th></tr>";
$sr_no=0;
while($row=mysql_fetch_array($result))
{
$dateform=explode('-',$row['recd_date']);
$dateform2=explode('-',$row['analysed_date']);
$dateform3=explode('-',$row['report_send']);
echo "<td><div id='itemcode'>" . $row['item_code'].
"</div></td>";
echo "<td>" . $row['description'] . "</td>";
echo "<td>" . $row['uom'] . "</td>";
echo "<td>" . $row['open_stock'] . "</td>";
echo "<td>" . $row['recd_total'] . "</td>";
echo "<td>" .
$sum=$row['open_stock']+$row['recd_total'] . "</td>";
echo "<td><div id='iss'>" . $row['issue_qty'] .
"</div></td>";
echo "<td>" . $available=$sum-$row['issue_qty'] .
"</td>";
echo "</tr>";
}
echo "</table></div>";}
I want to get content of the div "itemcode" when I click on the div "iss".
I know how to get content of the div which is clicked. But that is not the
requirement. Any option?
I have a jQuery post request which return a tabular data in html format
This is the jQuery post
jQuery('#chem_search').submit(function(e){
e.preventDefault();
var itemcode=jQuery('[name="itemcode"]').val();
jQuery.post("chemical_search_query.php", {"itemcode":itemcode},
function(data) {
jQuery('#type2').html(data);
});
});
the data returned by the ajax request is like this
echo "<div id='dar'><table class='s_report'><tr><th>Item
Code</th><th>Description</th><th>Unit</th><th>Op. Stock</th><th>Recd.
Qty</th><th>Total Receipts</th><th>Used Qty</th><th>Available
Stock</th></tr>";
$sr_no=0;
while($row=mysql_fetch_array($result))
{
$dateform=explode('-',$row['recd_date']);
$dateform2=explode('-',$row['analysed_date']);
$dateform3=explode('-',$row['report_send']);
echo "<td><div id='itemcode'>" . $row['item_code'].
"</div></td>";
echo "<td>" . $row['description'] . "</td>";
echo "<td>" . $row['uom'] . "</td>";
echo "<td>" . $row['open_stock'] . "</td>";
echo "<td>" . $row['recd_total'] . "</td>";
echo "<td>" .
$sum=$row['open_stock']+$row['recd_total'] . "</td>";
echo "<td><div id='iss'>" . $row['issue_qty'] .
"</div></td>";
echo "<td>" . $available=$sum-$row['issue_qty'] .
"</td>";
echo "</tr>";
}
echo "</table></div>";}
I want to get content of the div "itemcode" when I click on the div "iss".
I know how to get content of the div which is clicked. But that is not the
requirement. Any option?
How can I prevent (not react to) a segmentation fault?
How can I prevent (not react to) a segmentation fault?
I am not trying to handle a segmentation fault. I understand how exception
handling works, more or less. I would rather not have the fault in the
first place. What I want to do is call a function or perform an operation
that returns a value telling me whether or not that particular memory
location/block is accessible, without actually accessing it and getting
the fault.
That is, I would like a C function to probe an address in Linux and/or Mac
OS X before actually accessing it. Something like:
result = probe_memory(address,length)
where result is
0 = writable
1 = read-only
-1 = nonexistent
or something along those lines.
Is there anything like that in Linux and/or Mac OS X?
I am not trying to handle a segmentation fault. I understand how exception
handling works, more or less. I would rather not have the fault in the
first place. What I want to do is call a function or perform an operation
that returns a value telling me whether or not that particular memory
location/block is accessible, without actually accessing it and getting
the fault.
That is, I would like a C function to probe an address in Linux and/or Mac
OS X before actually accessing it. Something like:
result = probe_memory(address,length)
where result is
0 = writable
1 = read-only
-1 = nonexistent
or something along those lines.
Is there anything like that in Linux and/or Mac OS X?
Cannot get django template tag to return unicode
Cannot get django template tag to return unicode
I'm writing an app that will track a series of matches between 2 players.
I am using Django's User model and extending it with my own UserProfile.
I store usernames in User as their steamID (ex: 76561197965801299) and
then look up their steam username on login, and update UserProfile.
Instead of looking at 76561197965801299, I want to look at a username, and
on one page, I want to decorate this username with more goodies, so I
wrote a template tag.
Problem:
I cannot seem to print unicode data from my template tag.
Actual Error:
'ascii' codec can't encode character u'\u260e' in position 16: ordinal not
in range(128)
Normally Django doesn't bother me with unicode issues (for example: I can
see this unicode object in the admin pages no problem) but I've never
tried applying a template tag, so there is obviously something I'm doing
wrong here.
template/ladder/match_game_listing.html
{{ match.challengee|steam_name }}
The match.challengee in this case is 76561197971597000.
ladder/templatetags/ladder_filters.py
from django import template
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.utils.html import mark_safe
from cafe.models import UserProfile
register = template.Library()
@register.filter()
def steam_name(name):
try:
user_obj = User.objects.get(username=name)
user_prof = UserProfile.objects.get(user_id=user_obj.id)
url = user_prof.url
handle = unicode(user_prof.handle)
avatar = user_prof.avatar
steam_string = "<a href='{0}' alt='{1}\'s profile'><img src='{2}'
alt='{1}\'s avatar' >{1}</a>".format(url, handle, avatar)
return mark_safe(steam_string)
# Non-steam entities can exist, ignore
except ObjectDoesNotExist:
return name
When I go to view this in the browser, I get the aforementioned error:
UnicodeEncodeError at /ladder/dota2/ 'ascii' codec can't encode character
u'\u260e' in position 16: ordinal not in range(128)
With a helpful hint of:
Unicode error hint
The string that could not be encoded/decoded was: oose ¢Ï
I've tried browsing the Django docs numerous times, and I have tried
playing with force_text() to no avail, but as I'm a little unclear on why
this isn't working, I might just be missing the relevant section. This
template tag works in cases where the name does not have unicode.
I'm writing an app that will track a series of matches between 2 players.
I am using Django's User model and extending it with my own UserProfile.
I store usernames in User as their steamID (ex: 76561197965801299) and
then look up their steam username on login, and update UserProfile.
Instead of looking at 76561197965801299, I want to look at a username, and
on one page, I want to decorate this username with more goodies, so I
wrote a template tag.
Problem:
I cannot seem to print unicode data from my template tag.
Actual Error:
'ascii' codec can't encode character u'\u260e' in position 16: ordinal not
in range(128)
Normally Django doesn't bother me with unicode issues (for example: I can
see this unicode object in the admin pages no problem) but I've never
tried applying a template tag, so there is obviously something I'm doing
wrong here.
template/ladder/match_game_listing.html
{{ match.challengee|steam_name }}
The match.challengee in this case is 76561197971597000.
ladder/templatetags/ladder_filters.py
from django import template
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.utils.html import mark_safe
from cafe.models import UserProfile
register = template.Library()
@register.filter()
def steam_name(name):
try:
user_obj = User.objects.get(username=name)
user_prof = UserProfile.objects.get(user_id=user_obj.id)
url = user_prof.url
handle = unicode(user_prof.handle)
avatar = user_prof.avatar
steam_string = "<a href='{0}' alt='{1}\'s profile'><img src='{2}'
alt='{1}\'s avatar' >{1}</a>".format(url, handle, avatar)
return mark_safe(steam_string)
# Non-steam entities can exist, ignore
except ObjectDoesNotExist:
return name
When I go to view this in the browser, I get the aforementioned error:
UnicodeEncodeError at /ladder/dota2/ 'ascii' codec can't encode character
u'\u260e' in position 16: ordinal not in range(128)
With a helpful hint of:
Unicode error hint
The string that could not be encoded/decoded was: oose ¢Ï
I've tried browsing the Django docs numerous times, and I have tried
playing with force_text() to no avail, but as I'm a little unclear on why
this isn't working, I might just be missing the relevant section. This
template tag works in cases where the name does not have unicode.
replace value in multi dimensional array with another value in PHP
replace value in multi dimensional array with another value in PHP
In PHP, I have an array as follows:
array(35) {
[0] => array(11) {
'dept_number' → str•4 '2310'
'dept_descr' → str•10 'Some Stuff'
}
[1] => array(11) {
'dept_number' → str•4 '1010'
'dept_descr' → str•11 'Other Stuff'
}
...and so on
I have another array as follows:
array(22) {
[2310] => str•6 'Bakery'
[1010] => str•4 'Beer'
...and so on
I want to replace the dept_descr in the first array with the description
in the second array, where the dept_number in the first array matches the
key in the second array. so, the result would be:
array(35) {
[0] => array(11) {
'dept_number' → str•4 '2310'
'dept_descr' → str•6 'Bakery'
}
[1] => array(11) {
'dept_number' → str•4 '1010'
'dept_descr' → str•4 'Beer'
}
How is this done?
In PHP, I have an array as follows:
array(35) {
[0] => array(11) {
'dept_number' → str•4 '2310'
'dept_descr' → str•10 'Some Stuff'
}
[1] => array(11) {
'dept_number' → str•4 '1010'
'dept_descr' → str•11 'Other Stuff'
}
...and so on
I have another array as follows:
array(22) {
[2310] => str•6 'Bakery'
[1010] => str•4 'Beer'
...and so on
I want to replace the dept_descr in the first array with the description
in the second array, where the dept_number in the first array matches the
key in the second array. so, the result would be:
array(35) {
[0] => array(11) {
'dept_number' → str•4 '2310'
'dept_descr' → str•6 'Bakery'
}
[1] => array(11) {
'dept_number' → str•4 '1010'
'dept_descr' → str•4 'Beer'
}
How is this done?
Elements of an arraylist as replacement in a files line
Elements of an arraylist as replacement in a files line
I have this part of the code which reads a file linebyline. This original
line that is about to be edited is: j(ac) "test" /Aaa,Bbb/
I have an arraylist with elements [Ccc,Ddd,Eee] and I want these elements
to be replaces in the line above between / and /. The replcement between /
and / works fine. However I cant put the arraylist straight to the
.replace cause [] will also appear. So I am tryin to add the elements of
the list. However I cant get the desired result which is: j(ac) "test"
/Ccc,Ddd,Eee/
I keep getting only the first element: j(ac) "test" /Ccc/
How could I fix this?
List<String> strlist = new ArrayList<String>() ;
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("j(ac)")) {
String skat ;
skat = null ;
for(String s : strtogams) {
for (int index = 0; index < strlist.size(); index++) {
s = strlist.get(index);
skat=s;
}
}
String next = line.replaceAll("/.*?/", "/"+skat+"/");
System.out.print(next);
}
I have this part of the code which reads a file linebyline. This original
line that is about to be edited is: j(ac) "test" /Aaa,Bbb/
I have an arraylist with elements [Ccc,Ddd,Eee] and I want these elements
to be replaces in the line above between / and /. The replcement between /
and / works fine. However I cant put the arraylist straight to the
.replace cause [] will also appear. So I am tryin to add the elements of
the list. However I cant get the desired result which is: j(ac) "test"
/Ccc,Ddd,Eee/
I keep getting only the first element: j(ac) "test" /Ccc/
How could I fix this?
List<String> strlist = new ArrayList<String>() ;
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.contains("j(ac)")) {
String skat ;
skat = null ;
for(String s : strtogams) {
for (int index = 0; index < strlist.size(); index++) {
s = strlist.get(index);
skat=s;
}
}
String next = line.replaceAll("/.*?/", "/"+skat+"/");
System.out.print(next);
}
li element accepting borders in chrome browser
li element accepting borders in chrome browser
I have made a site. It all looks fine in mozila but it has some issues in
Chrome.
The problem is with the right navigation (sidebar) which gets thick opaque
bottom borders.
Please take a look at it:
www.ms-models.com
Thanks in advance
I have made a site. It all looks fine in mozila but it has some issues in
Chrome.
The problem is with the right navigation (sidebar) which gets thick opaque
bottom borders.
Please take a look at it:
www.ms-models.com
Thanks in advance
Sunday, 15 September 2013
Spring Validation with Groups in Domain Objects with Builder Pattern
Spring Validation with Groups in Domain Objects with Builder Pattern
I am writing some help code to add builders to my domain model using the
Builder Pattern. I have the basic portion of the code built, but I want to
added another build method that will validate the newly built object. I
envision this new method would accept a class to match up with the groups
in my bean validation. Therefore, when I get the object back from the
builder I know it is a valid abject for the state I want. I have two
questions concerning this approach.
First, does this sound like a good approach? I have not seen anything on
the net about doing this, but I think it would be a good idea to have in a
builder.
Next question, What is a good way to get a validator into the builder?
Should I try to auotwire it in or something else?
I am writing some help code to add builders to my domain model using the
Builder Pattern. I have the basic portion of the code built, but I want to
added another build method that will validate the newly built object. I
envision this new method would accept a class to match up with the groups
in my bean validation. Therefore, when I get the object back from the
builder I know it is a valid abject for the state I want. I have two
questions concerning this approach.
First, does this sound like a good approach? I have not seen anything on
the net about doing this, but I think it would be a good idea to have in a
builder.
Next question, What is a good way to get a validator into the builder?
Should I try to auotwire it in or something else?
Is there a "right" way to make the setupController hook fire consistently?
Is there a "right" way to make the setupController hook fire consistently?
First, I'm sorry, but I can't show any actual code at the moment.
I have a page with a search bar. Upon entering text and clicking enter, a
transition occurs to the same page with a query in the URL. Due to the way
the model and setupController hooks fire, I have set up my code as
follows:
model: Updates the search text field with the text that was passed, and
changes the controller's model to the current JavaScript timestamp as a
hack to force the call to setupController.
setupController: obtains the text from the search field, and should then
update the model with the proper search results (NYI)
What I'm doing in the model hook seems downright hacky, but I'm not quite
sure how else to go about this in a way that remains consistent with both
somebody manually adjusting the URL and a proper transitionTo.
I'd appreciate it if somebody could tell me if there's a "right" way to
ensure that setupController is called regardless of whether or not Ember
thinks that the model has changed (which seems to be the culprit that's
currently necessitating the hack.)
First, I'm sorry, but I can't show any actual code at the moment.
I have a page with a search bar. Upon entering text and clicking enter, a
transition occurs to the same page with a query in the URL. Due to the way
the model and setupController hooks fire, I have set up my code as
follows:
model: Updates the search text field with the text that was passed, and
changes the controller's model to the current JavaScript timestamp as a
hack to force the call to setupController.
setupController: obtains the text from the search field, and should then
update the model with the proper search results (NYI)
What I'm doing in the model hook seems downright hacky, but I'm not quite
sure how else to go about this in a way that remains consistent with both
somebody manually adjusting the URL and a proper transitionTo.
I'd appreciate it if somebody could tell me if there's a "right" way to
ensure that setupController is called regardless of whether or not Ember
thinks that the model has changed (which seems to be the culprit that's
currently necessitating the hack.)
Python Tkinter: Changing other button's text from event handler of one button
Python Tkinter: Changing other button's text from event handler of one button
I have the following problem when using tkinter to create a very simple
window containing a matrix of buttons: When one of the buttons is clicked,
the event handler changes the text of that button using the configure
method on the button widget. This works. But I also want to change the
text in one of the other buttons, which does not work. The method I use is
that on creating the button, I store the object returned by the Button
method before I use the grid geometry manager to place it. This object
looks like ".123456789L" when printed and seems to be a pointer to the
widget. I also use configure on this to change the button text. But
somehow it seems to be wrong, because it works sometimes, and most of the
times not. There's unfortunately no error message, just nothing happens
when calling configure. I checked and it seems to be the correct pointer
to the widget. Do I have to use a special way to affect a widget other
that the one that called the event handler? These are the relevant parts
of the code:
# CREATING THE BUTTONS:
buttons={} # global
for i in range(3):
for j in range(3):
button = Tkinter.Button(self,text='foo')
buttons[button]=(i,j)
button.grid(column=j,row=i)
button.bind( "<Button-1>", self.OnButtonClick )
# CHANGING BUTTONS:
def find_button(i,j):
"""Return the pointer to the other button to be changed when a button has
been clicked."""
for button,key in buttons.items():
if key==(i,j): return button
def OnButtonClick(self,event):
print "You clicked the button",buttons[event.widget]
i,j=buttons[event.widget]
old_button=find_button(i,j) # This is simplified, I don't actually pass
i,j, but other values. But I checked this and it returns the reference to
the correct button. But this simplified version works the same way, just
assume a different button that the one pressed would be returned.
old_button.configure(text = 'blabla') # THIS DOES NOT WORK
event.widget.configure(text = 'something') # THIS WORKS
I have the following problem when using tkinter to create a very simple
window containing a matrix of buttons: When one of the buttons is clicked,
the event handler changes the text of that button using the configure
method on the button widget. This works. But I also want to change the
text in one of the other buttons, which does not work. The method I use is
that on creating the button, I store the object returned by the Button
method before I use the grid geometry manager to place it. This object
looks like ".123456789L" when printed and seems to be a pointer to the
widget. I also use configure on this to change the button text. But
somehow it seems to be wrong, because it works sometimes, and most of the
times not. There's unfortunately no error message, just nothing happens
when calling configure. I checked and it seems to be the correct pointer
to the widget. Do I have to use a special way to affect a widget other
that the one that called the event handler? These are the relevant parts
of the code:
# CREATING THE BUTTONS:
buttons={} # global
for i in range(3):
for j in range(3):
button = Tkinter.Button(self,text='foo')
buttons[button]=(i,j)
button.grid(column=j,row=i)
button.bind( "<Button-1>", self.OnButtonClick )
# CHANGING BUTTONS:
def find_button(i,j):
"""Return the pointer to the other button to be changed when a button has
been clicked."""
for button,key in buttons.items():
if key==(i,j): return button
def OnButtonClick(self,event):
print "You clicked the button",buttons[event.widget]
i,j=buttons[event.widget]
old_button=find_button(i,j) # This is simplified, I don't actually pass
i,j, but other values. But I checked this and it returns the reference to
the correct button. But this simplified version works the same way, just
assume a different button that the one pressed would be returned.
old_button.configure(text = 'blabla') # THIS DOES NOT WORK
event.widget.configure(text = 'something') # THIS WORKS
insert/delete into std::map found/at by constants
insert/delete into std::map found/at by constants
I'm using json-spirit's mObject to create jagged multidimensional maps for
my family's real-time personal finance websocket server.
I've found that the [] operator doesn't accept consts, but I can't find
how to insert using find(const) or at(const).
With this code
string accountList[] = {"mine", "wife's", "kid's"};
BOOST_FOREACH( string account, accountList )
{
accounts[account] = mObject(); // no error
accounts.insert(std::make_pair(account,mObject())); // no error
accounts[account]["cash"] = mValue(0); //error
accounts.at(account).insert(std::make_pair("cash",mValue(0))); //
still error
}
The first usage of the [] operator strangely doesn't give error, thus I
assume it works. The second line inside the FOREACH also works, but I get
errors for the last two.
error: no match for 'operator[]' in 'accounts.std::map<_Key, _Tp, _Compare,
_Alloc>::operator[]<std::basic_string<char>,
json_spirit::Value_impl<json_spirit::Config_map<std::basic_string<char> > >,
std::less<std::basic_string<char> >, std::allocator<std::pair<const
std::basic_string<char>,
json_spirit::Value_impl<json_spirit::Config_map<std::basic_string<char> >
> > > >((*
(const key_type*)(& account)))["cash"]'
and
error: 'std::map<std::basic_string<char>,
json_spirit::Value_impl<json_spirit::Config_map<std::basic_string<char> > >,
std::less<std::basic_string<char> >, std::allocator<std::pair<const
std::basic_string<char>,
json_spirit::Value_impl<json_spirit::Config_map<std::basic_string<char> >
> > >
>::mapped_type' has no member named 'insert'
According to the json-spirit docs, mObject is a typedef std::map<
std::string, mValue > mObject;, and I'm pretty sure that mValue is some
sort of boost::any since it gave the same errors as when I tried to
reinvent the wheel.
How can I insert and (since I'm having so much trouble) delete into
mObjects with const strings as key argument?
I'm using json-spirit's mObject to create jagged multidimensional maps for
my family's real-time personal finance websocket server.
I've found that the [] operator doesn't accept consts, but I can't find
how to insert using find(const) or at(const).
With this code
string accountList[] = {"mine", "wife's", "kid's"};
BOOST_FOREACH( string account, accountList )
{
accounts[account] = mObject(); // no error
accounts.insert(std::make_pair(account,mObject())); // no error
accounts[account]["cash"] = mValue(0); //error
accounts.at(account).insert(std::make_pair("cash",mValue(0))); //
still error
}
The first usage of the [] operator strangely doesn't give error, thus I
assume it works. The second line inside the FOREACH also works, but I get
errors for the last two.
error: no match for 'operator[]' in 'accounts.std::map<_Key, _Tp, _Compare,
_Alloc>::operator[]<std::basic_string<char>,
json_spirit::Value_impl<json_spirit::Config_map<std::basic_string<char> > >,
std::less<std::basic_string<char> >, std::allocator<std::pair<const
std::basic_string<char>,
json_spirit::Value_impl<json_spirit::Config_map<std::basic_string<char> >
> > > >((*
(const key_type*)(& account)))["cash"]'
and
error: 'std::map<std::basic_string<char>,
json_spirit::Value_impl<json_spirit::Config_map<std::basic_string<char> > >,
std::less<std::basic_string<char> >, std::allocator<std::pair<const
std::basic_string<char>,
json_spirit::Value_impl<json_spirit::Config_map<std::basic_string<char> >
> > >
>::mapped_type' has no member named 'insert'
According to the json-spirit docs, mObject is a typedef std::map<
std::string, mValue > mObject;, and I'm pretty sure that mValue is some
sort of boost::any since it gave the same errors as when I tried to
reinvent the wheel.
How can I insert and (since I'm having so much trouble) delete into
mObjects with const strings as key argument?
Can any one give example of Artificial Neural network implementing in netbeans ? for TCP network packets
Can any one give example of Artificial Neural network implementing in
netbeans ? for TCP network packets
Please give an example on how to implement Artificial Neural Network in
Netbeans using java? Problem is how to use ANN for training. How training
actually takes place ? A live example would be very helpful.
netbeans ? for TCP network packets
Please give an example on how to implement Artificial Neural Network in
Netbeans using java? Problem is how to use ANN for training. How training
actually takes place ? A live example would be very helpful.
Field NULL in SQL
Field NULL in SQL
I have a table in DB:
REGULAR(num(bigint) not allow null, title(nvarchar(10)),
content(nvarchar(500)), path(nvarchar(50)) allow null)
with some data:
1.REGULAR1(1|title1|content1|path1)
2.REGULAR2(2|title2|content2|)--> path is not inputed (null)
I excute some query in SQL DB server 2008:
1. select PATH from REGULAR where num='2'; -> result is PATH:NULL
But
2. select count(*) from REGULAR where PATH = NULL; --> result is COUNT:0
(it must be 1 which has num=2)
Therefore, when I excute a queries from Webform it works wrong
string sql= select * from REGULAR;
Datatable regular= excute(sql)....
for(int i=0;i<regular.Rows.Count; i++)
{
if(regular.Rows[i]["path"]!=null)
{
Textbox1.Text= "a";//do something else...
}
else
Textbox1.Text+="b";//...
}
and the result is: Textbox.Text= "ab"---> it much be ="a". Is there any
mistake???
I have a table in DB:
REGULAR(num(bigint) not allow null, title(nvarchar(10)),
content(nvarchar(500)), path(nvarchar(50)) allow null)
with some data:
1.REGULAR1(1|title1|content1|path1)
2.REGULAR2(2|title2|content2|)--> path is not inputed (null)
I excute some query in SQL DB server 2008:
1. select PATH from REGULAR where num='2'; -> result is PATH:NULL
But
2. select count(*) from REGULAR where PATH = NULL; --> result is COUNT:0
(it must be 1 which has num=2)
Therefore, when I excute a queries from Webform it works wrong
string sql= select * from REGULAR;
Datatable regular= excute(sql)....
for(int i=0;i<regular.Rows.Count; i++)
{
if(regular.Rows[i]["path"]!=null)
{
Textbox1.Text= "a";//do something else...
}
else
Textbox1.Text+="b";//...
}
and the result is: Textbox.Text= "ab"---> it much be ="a". Is there any
mistake???
C++ namespace FW ; Matrix multiplication
C++ namespace FW ; Matrix multiplication
I'm trying to implement some basic matrix multiplication, for translation.
In my opinion the multiplication should work, but I get this error.
binary '*=' : no operator found which takes a right-hand operand of type
'FW::Vec4f' (or there is no acceptable conversion)
Here is my code, using std and FW namepsace
Mat4f World;
float x, y, z;
World.setCol(0, Vec4f(1, 0, 0, x));
World.setCol(1, Vec4f(0, 1, 0, y));
World.setCol(2, Vec4f(0, 0, 1, z));
World.setCol(3, Vec4f(0, 0, 0, 1));
World *= Vec4f(translation_, 1, 1, 1);
I'm trying to implement some basic matrix multiplication, for translation.
In my opinion the multiplication should work, but I get this error.
binary '*=' : no operator found which takes a right-hand operand of type
'FW::Vec4f' (or there is no acceptable conversion)
Here is my code, using std and FW namepsace
Mat4f World;
float x, y, z;
World.setCol(0, Vec4f(1, 0, 0, x));
World.setCol(1, Vec4f(0, 1, 0, y));
World.setCol(2, Vec4f(0, 0, 1, z));
World.setCol(3, Vec4f(0, 0, 0, 1));
World *= Vec4f(translation_, 1, 1, 1);
Saturday, 14 September 2013
shell_exec probably not working
shell_exec probably not working
i understand this might be a little silly to ask but i can't seem to get
shell_exec to work in my php code.
In the code bellow $cmdstring holds the command string but it is not being
executed for some reason. I tried to echo it and copy paste it in the
commandline and that worked fine. So it seems like it has something to do
with shell_exec.
I tried searching the net but I couldn't find any suitable answer.
move_uploaded_file($_FILES["file"]["tmp_name"],"C:xampp\htdocs\docman\docs\\"
. $_FILES["file"]["name"]);
$cmdstring='C:\xampp\htdocs\docman\docs\pdftotext
'.$_FILES['file']['name'].' '.$modifedfilename.'.txt';
shell_exec($cmdstring);
mysql_query($thequery) or die("DAMN");
echo "Upload Successful";
i understand this might be a little silly to ask but i can't seem to get
shell_exec to work in my php code.
In the code bellow $cmdstring holds the command string but it is not being
executed for some reason. I tried to echo it and copy paste it in the
commandline and that worked fine. So it seems like it has something to do
with shell_exec.
I tried searching the net but I couldn't find any suitable answer.
move_uploaded_file($_FILES["file"]["tmp_name"],"C:xampp\htdocs\docman\docs\\"
. $_FILES["file"]["name"]);
$cmdstring='C:\xampp\htdocs\docman\docs\pdftotext
'.$_FILES['file']['name'].' '.$modifedfilename.'.txt';
shell_exec($cmdstring);
mysql_query($thequery) or die("DAMN");
echo "Upload Successful";
MySQL update date where date is 0000-00-00
MySQL update date where date is 0000-00-00
I imported some data from excel onto my database. Due to some formatting
errors, many of the ship dates are "0000-00-00". I want to change that to
NULL. I used the following query but it doesn't work. Can someone show me
the correct syntax?
UPDATE inventory SET shipdate = NULL WHERE shipdate IS '0000-00-00'
I imported some data from excel onto my database. Due to some formatting
errors, many of the ship dates are "0000-00-00". I want to change that to
NULL. I used the following query but it doesn't work. Can someone show me
the correct syntax?
UPDATE inventory SET shipdate = NULL WHERE shipdate IS '0000-00-00'
Visual Studio heart overlay in solution explorer. What does it mean?
Visual Studio heart overlay in solution explorer. What does it mean?
In solution explorer you sometime see heart overlay in the class
definition nodes. What does it signify?
In solution explorer you sometime see heart overlay in the class
definition nodes. What does it signify?
how can i make a clickable image open up a youtube video inside of a shadowbox in the center of a webpage? [on hold]
how can i make a clickable image open up a youtube video inside of a
shadowbox in the center of a webpage? [on hold]
hi im learning wordpress on a website http://lingeriesshop.net and i just
implemented a new right sidebar with a spinning clickable video image.
when the image is clicked id like it to open a video onscreen center
inside of a shadowbox like my videos on my video page do. you can see the
shadow box effect im wanting to implement if you visit this url
http://lingeriesshop.net/videos/ and click on a video. does anyone know a
way i could do this?
shadowbox in the center of a webpage? [on hold]
hi im learning wordpress on a website http://lingeriesshop.net and i just
implemented a new right sidebar with a spinning clickable video image.
when the image is clicked id like it to open a video onscreen center
inside of a shadowbox like my videos on my video page do. you can see the
shadow box effect im wanting to implement if you visit this url
http://lingeriesshop.net/videos/ and click on a video. does anyone know a
way i could do this?
Pure CSS menu drop down Not working iOS
Pure CSS menu drop down Not working iOS
I have a pure css menu drop down, works great in everything but not iOS
(iPhone or iPad) http://jsfiddle.net/kibblewhite/n7Fbt/embedded/result/
HTML:
<ul class="navigation">
<li class="sub">
<span class="navigation-entry-title" alt="Home"
title="Home">Home</span>
<ul class="navigation-dropdown">
<li><a href="#">Home Page</a></li>
<li><a href="#">First Time Student</a></li>
<li><a href="#">What is Swing Dancing?</a></li>
</ul>
</li>
<li class="sub">
<span class="navigation-entry-title" alt="Classes"
title="Classes">Classes</span>
<ul class="navigation-dropdown">
<li><a href="#">Courses</a></li>
<li><a href="#">Our Agenda & Time Table</a></li>
<li><a href="#">Workshops</a></li>
<li><a href="#">Curriculum</a></li>
<li><a href="#">Venues</a></li>
</ul>
</li>
<li class="sub">
<span class="navigation-entry-title" alt="Events">Events</span>
<ul class="navigation-dropdown">
<li><a href="#">Socials</a></li>
<li><a href="#">Performances</a></li>
<li><a href="#">Competitions</a></li>
<li><a href="#">Stepping Out</a></li>
<li><a href="#">Camps</a></li>
</ul>
</li>
<li class="sub">
<span class="navigation-entry-title" alt="">Team</span>
<ul class="navigation-dropdown">
<li><a href="#">Teachers</a></li>
<li><a href="#">Join Our Troupe</a></li>
<li><a href="#">Join our Team</a></li>
</ul>
</li>
<li class="sub">
<span class="navigation-entry-title" alt="">Hire Us</span>
<ul class="navigation-dropdown">
<li><a href="#">Planning an event?</a></li>
<li><a href="#">Privates</a></li>
<li><a href="#">Wedding Dances</a></li>
<li><a href="#">Schools and Youth Projects</a></li>
</ul>
</li>
<li class="sub">
<span class="navigation-entry-title" alt="">Media</span>
<ul class="navigation-dropdown">
<li><a href="#">Resource</a></li>
<li><a href="#">Press Release</a></li>
<li><a href="#">Photo Galleries</a></li>
<li><a href="#">Videos</a></li>
<li><a href="#">Announcements</a></li>
</ul>
</li>
</ul>
CSS:
body {
background-color: DimGrey;
}
ul.navigation {
margin: 0;
list-style: none;
}
ul.navigation > li.sub {
float: left;
position: relative;
padding: 3px 10px 5px 10px;
margin: 0;
font-family: 'Lato', sans-serif;
}
ul.navigation > li.sub > span {
color: ivory;
text-decoration: none;
}
ul.navigation > li.sub > span.navigation-entry-title {
text-transform: uppercase;
}
/** the symbol before the navigation entry */
ul.navigation > li.sub > span.navigation-entry-title:before {
content: "\00BB";
letter-spacing: 3px;
}
ul.navigation > li.sub > ul.navigation-dropdown {
position: absolute;
list-style: none;
top: -1000em;
opacity: 0;
transition: opacity .38s ease-in-out;
-moz-transition: opacity .38s ease-in-out;
-webkit-transition: opacity .38s ease-in-out;
box-shadow: 0 2px 6px grey;
-moz-box-shadow: 0 2px 6px grey;
-webkit-box-shadow: 0 2px 6px grey;
padding: 0;
min-width: 180px;
}
ul.navigation > li.sub > ul.navigation-dropdown > li {
background-color: white;
white-space: nowrap;
padding: 8px 32px 8px 18px;
border-top: 1px dotted #999;
font-size: small;
}
ul.navigation > li.sub > ul.navigation-dropdown > li > a {
text-decoration: none;
color: #999;
}
ul.navigation > li.sub > ul.navigation-dropdown > li > a:hover {
color: black;
}
/** what to do whilst hovering over the menu entry */
ul.navigation > li.sub:hover {
background: #34152C;
cursor: pointer;
}
ul.navigation > li.sub:hover > ul.navigation-dropdown {
left: 0;
top: 26px;
opacity: 0.94;
display: block;
}
The two issues I'd like to address is:
The menu fails to appear when you click/hover/focus on the menu item
If I surround the span menu items with tags, which I'm trying to avoid at
all costs, but then the menu drop down fails to close when I click
anywhere else on the screen anyways, so it fails in so many ways.
Any help would be greatly welcomed.
I have a pure css menu drop down, works great in everything but not iOS
(iPhone or iPad) http://jsfiddle.net/kibblewhite/n7Fbt/embedded/result/
HTML:
<ul class="navigation">
<li class="sub">
<span class="navigation-entry-title" alt="Home"
title="Home">Home</span>
<ul class="navigation-dropdown">
<li><a href="#">Home Page</a></li>
<li><a href="#">First Time Student</a></li>
<li><a href="#">What is Swing Dancing?</a></li>
</ul>
</li>
<li class="sub">
<span class="navigation-entry-title" alt="Classes"
title="Classes">Classes</span>
<ul class="navigation-dropdown">
<li><a href="#">Courses</a></li>
<li><a href="#">Our Agenda & Time Table</a></li>
<li><a href="#">Workshops</a></li>
<li><a href="#">Curriculum</a></li>
<li><a href="#">Venues</a></li>
</ul>
</li>
<li class="sub">
<span class="navigation-entry-title" alt="Events">Events</span>
<ul class="navigation-dropdown">
<li><a href="#">Socials</a></li>
<li><a href="#">Performances</a></li>
<li><a href="#">Competitions</a></li>
<li><a href="#">Stepping Out</a></li>
<li><a href="#">Camps</a></li>
</ul>
</li>
<li class="sub">
<span class="navigation-entry-title" alt="">Team</span>
<ul class="navigation-dropdown">
<li><a href="#">Teachers</a></li>
<li><a href="#">Join Our Troupe</a></li>
<li><a href="#">Join our Team</a></li>
</ul>
</li>
<li class="sub">
<span class="navigation-entry-title" alt="">Hire Us</span>
<ul class="navigation-dropdown">
<li><a href="#">Planning an event?</a></li>
<li><a href="#">Privates</a></li>
<li><a href="#">Wedding Dances</a></li>
<li><a href="#">Schools and Youth Projects</a></li>
</ul>
</li>
<li class="sub">
<span class="navigation-entry-title" alt="">Media</span>
<ul class="navigation-dropdown">
<li><a href="#">Resource</a></li>
<li><a href="#">Press Release</a></li>
<li><a href="#">Photo Galleries</a></li>
<li><a href="#">Videos</a></li>
<li><a href="#">Announcements</a></li>
</ul>
</li>
</ul>
CSS:
body {
background-color: DimGrey;
}
ul.navigation {
margin: 0;
list-style: none;
}
ul.navigation > li.sub {
float: left;
position: relative;
padding: 3px 10px 5px 10px;
margin: 0;
font-family: 'Lato', sans-serif;
}
ul.navigation > li.sub > span {
color: ivory;
text-decoration: none;
}
ul.navigation > li.sub > span.navigation-entry-title {
text-transform: uppercase;
}
/** the symbol before the navigation entry */
ul.navigation > li.sub > span.navigation-entry-title:before {
content: "\00BB";
letter-spacing: 3px;
}
ul.navigation > li.sub > ul.navigation-dropdown {
position: absolute;
list-style: none;
top: -1000em;
opacity: 0;
transition: opacity .38s ease-in-out;
-moz-transition: opacity .38s ease-in-out;
-webkit-transition: opacity .38s ease-in-out;
box-shadow: 0 2px 6px grey;
-moz-box-shadow: 0 2px 6px grey;
-webkit-box-shadow: 0 2px 6px grey;
padding: 0;
min-width: 180px;
}
ul.navigation > li.sub > ul.navigation-dropdown > li {
background-color: white;
white-space: nowrap;
padding: 8px 32px 8px 18px;
border-top: 1px dotted #999;
font-size: small;
}
ul.navigation > li.sub > ul.navigation-dropdown > li > a {
text-decoration: none;
color: #999;
}
ul.navigation > li.sub > ul.navigation-dropdown > li > a:hover {
color: black;
}
/** what to do whilst hovering over the menu entry */
ul.navigation > li.sub:hover {
background: #34152C;
cursor: pointer;
}
ul.navigation > li.sub:hover > ul.navigation-dropdown {
left: 0;
top: 26px;
opacity: 0.94;
display: block;
}
The two issues I'd like to address is:
The menu fails to appear when you click/hover/focus on the menu item
If I surround the span menu items with tags, which I'm trying to avoid at
all costs, but then the menu drop down fails to close when I click
anywhere else on the screen anyways, so it fails in so many ways.
Any help would be greatly welcomed.
can't add plugin org.apache.cordova.geolocation.GeoBroker
can't add plugin org.apache.cordova.geolocation.GeoBroker
I am having some problems with PhoneGap 3.0 Everything was working as
should on PhoneGap 2.9
Now I upgraded to 3.0 And created a new PhoneGap Project.
$> phonegap create new_project
added to config.xml :
<feature name="http://api.phonegap.com/1.0/geolocation"/>
and for index.html I used the full example from
http://docs.phonegap.com/en/edge/cordova_geolocation_geolocation.md.html#geolocation.getCurrentPosition_full_example
then
$> phonegap build android
I imported the project to Eclipse and checked the following :
AndroidManifest.xml has
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
xml/config.xml has
<feature name="Geolocation">
<param name="android-package"
value="org.apache.cordova.geolocation.GeoBroker" />
</feature>
I also used this cmd :
$> phonegap local plugin add
https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git
and that created the package src/
org.apache.cordova.geolocation
now when I run my app. I got the Following errors :
I/System.out(15155): Error adding plugin
org.apache.cordova.geolocation.GeoBroker.
D/PluginManager(15155): exec() call to unknown plugin: Geolocation
and the Javascript function onError() alert with code:null & message:
Any suggestions ?
Thank you in Advance
I am having some problems with PhoneGap 3.0 Everything was working as
should on PhoneGap 2.9
Now I upgraded to 3.0 And created a new PhoneGap Project.
$> phonegap create new_project
added to config.xml :
<feature name="http://api.phonegap.com/1.0/geolocation"/>
and for index.html I used the full example from
http://docs.phonegap.com/en/edge/cordova_geolocation_geolocation.md.html#geolocation.getCurrentPosition_full_example
then
$> phonegap build android
I imported the project to Eclipse and checked the following :
AndroidManifest.xml has
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
xml/config.xml has
<feature name="Geolocation">
<param name="android-package"
value="org.apache.cordova.geolocation.GeoBroker" />
</feature>
I also used this cmd :
$> phonegap local plugin add
https://git-wip-us.apache.org/repos/asf/cordova-plugin-geolocation.git
and that created the package src/
org.apache.cordova.geolocation
now when I run my app. I got the Following errors :
I/System.out(15155): Error adding plugin
org.apache.cordova.geolocation.GeoBroker.
D/PluginManager(15155): exec() call to unknown plugin: Geolocation
and the Javascript function onError() alert with code:null & message:
Any suggestions ?
Thank you in Advance
Iphone_ local notification_how to handle multiple nodification
Iphone_ local notification_how to handle multiple nodification
In my app, i placed 4 textfield with time , based on this time , local
notification should appear. its my logic. how to handle this multiple
local notifications
In my app, i placed 4 textfield with time , based on this time , local
notification should appear. its my logic. how to handle this multiple
local notifications
Can we use the Google Chart API in Android?
Can we use the Google Chart API in Android?
I looked through the Google Chart API and found it very nice. I need to
make pie charts for my Android application, and I would like to use the
Google Chart API to do the same. Is it possible? If yes, can someone
please link me to a tutorial for it? Thanks a lot!
I looked through the Google Chart API and found it very nice. I need to
make pie charts for my Android application, and I would like to use the
Google Chart API to do the same. Is it possible? If yes, can someone
please link me to a tutorial for it? Thanks a lot!
Friday, 13 September 2013
Making an inline css to be more powerful than an external !important?
Making an inline css to be more powerful than an external !important?
I have a slider script and a template external stylesheet, both I MUST
use. I was instructed to just use a custom.css to override the template
external stylesheet.
My problem is, the slider css in the template has an !important. The
slider script calculates the width and height of the images and inserts it
through inline css. I want the inline css to take more power in the
cascade rather than the !important in the template stylesheet.
For example:
In html doc, after it load the slider script:
<img src="slide1.jpg" style="width: 980.2545515px;" />
In template stylesheet:
img {
width: 500px !important;
}
I tried using jquery such as:
$("img").css("width","500px");
However, it doesn't override anything. Note that I need the automatically
generated width to override anything. But I can't seem to find a way to
override the width: 500px !important - width: auto/width: inherit doesn't
work neither.
Any solutions?
I have a slider script and a template external stylesheet, both I MUST
use. I was instructed to just use a custom.css to override the template
external stylesheet.
My problem is, the slider css in the template has an !important. The
slider script calculates the width and height of the images and inserts it
through inline css. I want the inline css to take more power in the
cascade rather than the !important in the template stylesheet.
For example:
In html doc, after it load the slider script:
<img src="slide1.jpg" style="width: 980.2545515px;" />
In template stylesheet:
img {
width: 500px !important;
}
I tried using jquery such as:
$("img").css("width","500px");
However, it doesn't override anything. Note that I need the automatically
generated width to override anything. But I can't seem to find a way to
override the width: 500px !important - width: auto/width: inherit doesn't
work neither.
Any solutions?
How do I add a line from a file into an array? [on hold]
How do I add a line from a file into an array? [on hold]
I have a file that looks like this:
17 12 15
7 54 9873 1867 4425 878 365 783
4
20
I am trying to get each line into it's own array so it would be something
like this:
array1[] = {17, 12, 15}
array2[] = {7, 54, 9873, 1867, 4425, 878, 365, 783}
array3[] = {4}
array4[] = {20}
This is what my code looks like so far:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FunTime {
public static void main(String[] args) throws IOException{
try (BufferedReader br = new BufferedReader(new
FileReader("funtime.txt"))){
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I can read the file and it prints it out line by line but I don't know how
to add each line into an array. Any ideas?
I have a file that looks like this:
17 12 15
7 54 9873 1867 4425 878 365 783
4
20
I am trying to get each line into it's own array so it would be something
like this:
array1[] = {17, 12, 15}
array2[] = {7, 54, 9873, 1867, 4425, 878, 365, 783}
array3[] = {4}
array4[] = {20}
This is what my code looks like so far:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FunTime {
public static void main(String[] args) throws IOException{
try (BufferedReader br = new BufferedReader(new
FileReader("funtime.txt"))){
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I can read the file and it prints it out line by line but I don't know how
to add each line into an array. Any ideas?
unhandled exception error won't allow me to insert data
unhandled exception error won't allow me to insert data
So if i run this code i'm thrown a multi-part identifier errorregarding
the binding of the textbox "clid"
Can somebody please help to resolve this issue?
Using cnnentry As New SqlConnection("Data Source=NB-1492\sqlipt;Initial
Catalog=Bookings;Integrated Security=True;Pooling=False")
Dim entrclientid As String
Dim clid As New TextBox
clid = FormView1.FindControl("txtclientid")
entrclientid = Convert.ToString(clid)
Dim sqlentry1 As String = "INSERT INTO
BOOKING_DETAILS(CLIENT_ID) VALUES("
Dim sqlentry2 As String = entrclientid
Dim sqlentry3 As String = ")"
Dim sqlentry4 As String = sqlentry1 & sqlentry2 & sqlentry3
Dim cmdclientid As New SqlCommand(sqlentry4, cnnentry)
cnnentry.Open()
string1 = cmdclientid.ExecuteNonQuery()
cnnentry.Close()
End Using
Thanks in advance
P.S. please excuse the naming conventions i wrote this extremely quickly
So if i run this code i'm thrown a multi-part identifier errorregarding
the binding of the textbox "clid"
Can somebody please help to resolve this issue?
Using cnnentry As New SqlConnection("Data Source=NB-1492\sqlipt;Initial
Catalog=Bookings;Integrated Security=True;Pooling=False")
Dim entrclientid As String
Dim clid As New TextBox
clid = FormView1.FindControl("txtclientid")
entrclientid = Convert.ToString(clid)
Dim sqlentry1 As String = "INSERT INTO
BOOKING_DETAILS(CLIENT_ID) VALUES("
Dim sqlentry2 As String = entrclientid
Dim sqlentry3 As String = ")"
Dim sqlentry4 As String = sqlentry1 & sqlentry2 & sqlentry3
Dim cmdclientid As New SqlCommand(sqlentry4, cnnentry)
cnnentry.Open()
string1 = cmdclientid.ExecuteNonQuery()
cnnentry.Close()
End Using
Thanks in advance
P.S. please excuse the naming conventions i wrote this extremely quickly
Unicode of upper and lowercase letters
Unicode of upper and lowercase letters
I need to write a program that reads in the unicode (an integer between 97
and 122) of a lower]case character (in other words, ask the user to enter
the unicode of a lower]case character) and display the upper]case
character of it, but I can't figure out how to do this. Help please??
I need to write a program that reads in the unicode (an integer between 97
and 122) of a lower]case character (in other words, ask the user to enter
the unicode of a lower]case character) and display the upper]case
character of it, but I can't figure out how to do this. Help please??
Perform pre and post processing with sqlite3
Perform pre and post processing with sqlite3
How can I perform post processing on my SQL3 database via python? The
following code doesn't work, but what I am trying to do is first create a
new database if not exists already, then insert some data, and finally
execute the query and close the connection. But I what to do so
separately, so as to add additional functionality later on, such as delete
/ updater / etc... Any ideas?
class TitlesDB:
# initiate global variables
conn = None
c = None
# perform pre - processing
def __init__(self, name):
import os
os.chdir('/../../')
import sqlite3
conn = sqlite3.connect(name)
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS titles (title VARCHAR(100)
UNIQUE)')
# insert a bunch of new titles
def InsertTitles(self, list):
c.executemany('INSERT OR IGNORE INTO titles VALUES (?)', list)
# perform post - processing
def __fina__(self):
conn.commit()
conn.close()
How can I perform post processing on my SQL3 database via python? The
following code doesn't work, but what I am trying to do is first create a
new database if not exists already, then insert some data, and finally
execute the query and close the connection. But I what to do so
separately, so as to add additional functionality later on, such as delete
/ updater / etc... Any ideas?
class TitlesDB:
# initiate global variables
conn = None
c = None
# perform pre - processing
def __init__(self, name):
import os
os.chdir('/../../')
import sqlite3
conn = sqlite3.connect(name)
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS titles (title VARCHAR(100)
UNIQUE)')
# insert a bunch of new titles
def InsertTitles(self, list):
c.executemany('INSERT OR IGNORE INTO titles VALUES (?)', list)
# perform post - processing
def __fina__(self):
conn.commit()
conn.close()
Thursday, 12 September 2013
Most "pythonic" way to do this?
Most "pythonic" way to do this?
what's the most "pythonic" way to calculate if a list of list has each
element greater than its neigbbour? eg
a = [[3.1, 3.13], [3.14, 3.12], [3.12, 3.1]]
I want to see if the first element in each of the list (inside the bigger
list) is greater than the 2nd element. So for first item, its false
because 3.1 < 3.13. 2nd and 3rd item is true.
I can most certainly use a for loop, but would like to see alternative
approaches. thanks.
what's the most "pythonic" way to calculate if a list of list has each
element greater than its neigbbour? eg
a = [[3.1, 3.13], [3.14, 3.12], [3.12, 3.1]]
I want to see if the first element in each of the list (inside the bigger
list) is greater than the 2nd element. So for first item, its false
because 3.1 < 3.13. 2nd and 3rd item is true.
I can most certainly use a for loop, but would like to see alternative
approaches. thanks.
How to make installer using installshield
How to make installer using installshield
I developed windows service in visual c++ using VS2012. Usually I install
it using sc create .... command for testing purpose. Now i want to create
installer for my service using install shield limited. How can I do that?
can anyone show me the steps to do that.
Thanks, Khurram.
I developed windows service in visual c++ using VS2012. Usually I install
it using sc create .... command for testing purpose. Now i want to create
installer for my service using install shield limited. How can I do that?
can anyone show me the steps to do that.
Thanks, Khurram.
Why doesn't jQuery dialog open event fire when .dialog("open") is called?
Why doesn't jQuery dialog open event fire when .dialog("open") is called?
I define a #scan-date-select dialog in the code below. When I define this
dialog, I attach an "open" event handler that is supposed to create a
datepicker widget that should appear inside the dialog. The dialog opens
correctly, but this open event never gets called. I need to know why the
open event handler is failing to get triggered. I have spent two days
trying to figure out what is wrong. I really hope someone here can help.
This is the HTML:
<div class="footer_all_pro clearfix">
<ul class="Printing-options clearfix">
<li>Shipping Labels:</li>
<li class="print-usps-label shipper-logo"><a
href="#"><img class="print-label-logo"
src="/dev/skin/images/logo_endicia.png"></a></li>
<li class="print-label shipper-logo"><a
href="#"><img class="print-label-logo"
src="/dev/skin/images/logo_ups.png"></a></li>
<li class="print-fed-label shipper-logo"><a
href="#"><img class="print-label-logo"
src="/dev/skin/images/logo_fedex.png"></a></li>
<li class="print-invoice"><a href="#">Packing
Slip</a></li>
<li class="print-pick"><a href="#">Pick List</a></li>
<li class="print-scan"><a href="#">SCAN Report</a></li>
<li class="del-scr"><span><img
src="/dev/skin/images/print-pick.png"></span><a
href="#" style="margin-top: -20px;">Delete</a></li>
<li class="del-arc"><span><img
src="/dev/skin/images/print-pick.png"></span><a href="#"
style="margin-top: -20px;">Archive</a></li>
<li class="send_email"><span><img
src="/dev/skin/images/print-pick.png"></span><a href="#"
style="margin-top: -20px;">Send Email</a></li>
<!-- <li class="del-all-inv"><span><img
src="/dev/skin/images/print-pick.png" /></span><a href="#"
style="margin-top: -20px;">Delete All</a></li>-->
</ul>
</div>
Here is the jQuery:
$( ".print-scan a" ).click(function(e) {
var $dialog = $("<div></div>")
.dialog({
title: "Confirm SCAN Report",
modal: false,
resizable: false,
scrollable: true,
width: 300,
height: 250,
position: { my: "center", at: "center", of: "article#dialog" },
buttons: { "No": function() { $( this ).dialog( "destroy" ); return false; },
"Yes": function() {
$(this).dialog("destroy");
$("<div id=\"scan-date-select\"></div>")
.dialog({
title: "Select SCAN Date",
modal: true,
resizable: false,
position: { my: "center", at: "center", of:
"article#dialog" },
open: function(event, ui) {
var $rptDate = $("#scan-date-select
.ui-dialog-content") //$(this)
.datepicker({ autoSize: true })
.datepicker("show");
console.log($(this));
console.log($rptDate);
//return false;
},
buttons: { Cancel: function() {
$(this).dialog("destroy"); return false; },
"Create Report": function() {
var selectedDate =
$rptDate.datepicker("getDate");
if(selectedDate == null) {
return false;
}
$(".request-print-label")
.attr("action",envPath +
"/partner/uspsscan")
.append('<input type="hidden"
name="rpt-date"
value="'+selectedDate+'" />')
.submit();
$(this).dialog("destroy");
return false;
}
}
})
.html("<div style=\"padding: 15px\">Please select a
transaction date for the SCAN Report</div>")
.dialog("open");
}
}
})
.html("<div id=\"confirm-scan\" style=\"padding: 15px\">CAUTION: Once
shipping labels are included on the SCAN Report, you will be unable to
issue refunds for these labels. Proceed anyway?</div>")
.dialog("open");
});
I define a #scan-date-select dialog in the code below. When I define this
dialog, I attach an "open" event handler that is supposed to create a
datepicker widget that should appear inside the dialog. The dialog opens
correctly, but this open event never gets called. I need to know why the
open event handler is failing to get triggered. I have spent two days
trying to figure out what is wrong. I really hope someone here can help.
This is the HTML:
<div class="footer_all_pro clearfix">
<ul class="Printing-options clearfix">
<li>Shipping Labels:</li>
<li class="print-usps-label shipper-logo"><a
href="#"><img class="print-label-logo"
src="/dev/skin/images/logo_endicia.png"></a></li>
<li class="print-label shipper-logo"><a
href="#"><img class="print-label-logo"
src="/dev/skin/images/logo_ups.png"></a></li>
<li class="print-fed-label shipper-logo"><a
href="#"><img class="print-label-logo"
src="/dev/skin/images/logo_fedex.png"></a></li>
<li class="print-invoice"><a href="#">Packing
Slip</a></li>
<li class="print-pick"><a href="#">Pick List</a></li>
<li class="print-scan"><a href="#">SCAN Report</a></li>
<li class="del-scr"><span><img
src="/dev/skin/images/print-pick.png"></span><a
href="#" style="margin-top: -20px;">Delete</a></li>
<li class="del-arc"><span><img
src="/dev/skin/images/print-pick.png"></span><a href="#"
style="margin-top: -20px;">Archive</a></li>
<li class="send_email"><span><img
src="/dev/skin/images/print-pick.png"></span><a href="#"
style="margin-top: -20px;">Send Email</a></li>
<!-- <li class="del-all-inv"><span><img
src="/dev/skin/images/print-pick.png" /></span><a href="#"
style="margin-top: -20px;">Delete All</a></li>-->
</ul>
</div>
Here is the jQuery:
$( ".print-scan a" ).click(function(e) {
var $dialog = $("<div></div>")
.dialog({
title: "Confirm SCAN Report",
modal: false,
resizable: false,
scrollable: true,
width: 300,
height: 250,
position: { my: "center", at: "center", of: "article#dialog" },
buttons: { "No": function() { $( this ).dialog( "destroy" ); return false; },
"Yes": function() {
$(this).dialog("destroy");
$("<div id=\"scan-date-select\"></div>")
.dialog({
title: "Select SCAN Date",
modal: true,
resizable: false,
position: { my: "center", at: "center", of:
"article#dialog" },
open: function(event, ui) {
var $rptDate = $("#scan-date-select
.ui-dialog-content") //$(this)
.datepicker({ autoSize: true })
.datepicker("show");
console.log($(this));
console.log($rptDate);
//return false;
},
buttons: { Cancel: function() {
$(this).dialog("destroy"); return false; },
"Create Report": function() {
var selectedDate =
$rptDate.datepicker("getDate");
if(selectedDate == null) {
return false;
}
$(".request-print-label")
.attr("action",envPath +
"/partner/uspsscan")
.append('<input type="hidden"
name="rpt-date"
value="'+selectedDate+'" />')
.submit();
$(this).dialog("destroy");
return false;
}
}
})
.html("<div style=\"padding: 15px\">Please select a
transaction date for the SCAN Report</div>")
.dialog("open");
}
}
})
.html("<div id=\"confirm-scan\" style=\"padding: 15px\">CAUTION: Once
shipping labels are included on the SCAN Report, you will be unable to
issue refunds for these labels. Proceed anyway?</div>")
.dialog("open");
});
Subscribe to:
Posts (Atom)