Get the names of all the entities in the entity container
How to retrieve the name of all the entity objects in the container. I
wish to bind the list of tables to a combox. So I want the name of all the
classes in the edmx.
Thursday, 3 October 2013
Wednesday, 2 October 2013
spring java and customize configuration file
spring java and customize configuration file
i would like to include a xml file for my web app configuration. where
should i include this config file and how can i access it?
this is my proj tree directory:
web proj/
|
|---Java Resource/
|
|---build/
|
|---WebContent/
| |
| |---css/
| |---images/
| |---js/
| |---META-INF/
| |---themes/
| |---WEB-INF/
| | |
| | |---jsp/
| | |---lib/
| | |---web-servlet.xml
| | |---spring-security.xml
| | |---tiles.xml
| | |---web.xml
| |---index.jsp
|---build.properties
|---build.xml
many thanks.
i would like to include a xml file for my web app configuration. where
should i include this config file and how can i access it?
this is my proj tree directory:
web proj/
|
|---Java Resource/
|
|---build/
|
|---WebContent/
| |
| |---css/
| |---images/
| |---js/
| |---META-INF/
| |---themes/
| |---WEB-INF/
| | |
| | |---jsp/
| | |---lib/
| | |---web-servlet.xml
| | |---spring-security.xml
| | |---tiles.xml
| | |---web.xml
| |---index.jsp
|---build.properties
|---build.xml
many thanks.
Best way to iterate 1 to 10 times and add value and to numpy array in python
Best way to iterate 1 to 10 times and add value and to numpy array in python
I know this is a simple question for someone, but I'm lost here.
Say if I want my result to be 10 random numbers in an array value:
np.random.randint(0,2) # returns 0,1
I want to iterate 10 times:
for i=1 to 10 :
np.random.randint(0,2) addto myarray
I want a numpy array of0,1,1,0... 10 times
Thank you.
I know this is a simple question for someone, but I'm lost here.
Say if I want my result to be 10 random numbers in an array value:
np.random.randint(0,2) # returns 0,1
I want to iterate 10 times:
for i=1 to 10 :
np.random.randint(0,2) addto myarray
I want a numpy array of0,1,1,0... 10 times
Thank you.
extract string after the first special character
extract string after the first special character
I have this string below:
foob/site?article=foo-title&id=12
how can I get the foo-title from the above string using regex? A short
solution would be appreciated.
Note: the foo-title could be any title.
I have this string below:
foob/site?article=foo-title&id=12
how can I get the foo-title from the above string using regex? A short
solution would be appreciated.
Note: the foo-title could be any title.
Modal Diolog position using variable
Modal Diolog position using variable
i have modal dialog. I want to position it according to variable that i
get. I just concerned on Y-position and for X-position i just put 'middle'
and it's worked.
Is it possible for me to put variable in my modal window position just
like my last line?
My idea is where ever user click, the modal dialog will appear upper the
clicked position
here is how i get the y-position (onclcick)
var curr = e.pageY - $(window).scrollTop();
$('#spnCursor').val(curr);
This code to get the variable value
$(function() {
var cursor = $('#spnCursor').val();
var msgposition = cursor - 300;
$( "#dialog-form" ).dialog({
position: ['middle','msgposition'],
Thanks.
i have modal dialog. I want to position it according to variable that i
get. I just concerned on Y-position and for X-position i just put 'middle'
and it's worked.
Is it possible for me to put variable in my modal window position just
like my last line?
My idea is where ever user click, the modal dialog will appear upper the
clicked position
here is how i get the y-position (onclcick)
var curr = e.pageY - $(window).scrollTop();
$('#spnCursor').val(curr);
This code to get the variable value
$(function() {
var cursor = $('#spnCursor').val();
var msgposition = cursor - 300;
$( "#dialog-form" ).dialog({
position: ['middle','msgposition'],
Thanks.
Tuesday, 1 October 2013
Write python object to multi-column csv file
Write python object to multi-column csv file
I am using Google Geocode API to append more detailed geographical
information to a list of addresses. That is to say, in a spreadsheet, I
want to append columns of sub-district (an administrative unit in India),
city and village specifically to each observation (address).
I've already imported the address into python in an ugly way and used
Google API together with some codes to convert this page
(http://maps.googleapis.com/maps/api/geocode/json?address=RAVI+NAGAR,+NAIDU+THOTA,+VISAKHAPATNAM+&sensor=true
) into the following printout:
Ravi Nagar [u'neighborhood', u'political']
Naidu Thota [u'sublocality', u'political']
Vizag [u'locality', u'political']
Vishakhapatnam [u'administrative_area_level_2', u'political']
Andhra Pradesh [u'administrative_area_level_1', u'political']
India [u'country', u'political']
530029 [u'postal_code']
as search result for address string:
"RAVI+NAGAR,+NAIDU+THOTA,+VISAKHAPATNAM+",Visakhapatnam,ANDHRA+PRADESH.
My question is, how to get these back to the previous csv file? I mean, I
don't want to miss the previous rows of the csv file and I want to append
new columns to the table. (Given the above result, I would like to have
columns for "postal_code", "administrative_area_level_1",
"administrative_area_level_2", "locality", "sublocality" and
"neighborhood" respectively. What I can think of is to construction a
function with identifier but I don't know that method according to my
shallow knowledge of Python.
One more minor point to ask: does it matter for u to show up in the
printouts? How to remove it? I mean remove the u in the "result"
dictionary (for this, you can click the link I've provided)?
Thank you for your help!
Linfeng
I am using Google Geocode API to append more detailed geographical
information to a list of addresses. That is to say, in a spreadsheet, I
want to append columns of sub-district (an administrative unit in India),
city and village specifically to each observation (address).
I've already imported the address into python in an ugly way and used
Google API together with some codes to convert this page
(http://maps.googleapis.com/maps/api/geocode/json?address=RAVI+NAGAR,+NAIDU+THOTA,+VISAKHAPATNAM+&sensor=true
) into the following printout:
Ravi Nagar [u'neighborhood', u'political']
Naidu Thota [u'sublocality', u'political']
Vizag [u'locality', u'political']
Vishakhapatnam [u'administrative_area_level_2', u'political']
Andhra Pradesh [u'administrative_area_level_1', u'political']
India [u'country', u'political']
530029 [u'postal_code']
as search result for address string:
"RAVI+NAGAR,+NAIDU+THOTA,+VISAKHAPATNAM+",Visakhapatnam,ANDHRA+PRADESH.
My question is, how to get these back to the previous csv file? I mean, I
don't want to miss the previous rows of the csv file and I want to append
new columns to the table. (Given the above result, I would like to have
columns for "postal_code", "administrative_area_level_1",
"administrative_area_level_2", "locality", "sublocality" and
"neighborhood" respectively. What I can think of is to construction a
function with identifier but I don't know that method according to my
shallow knowledge of Python.
One more minor point to ask: does it matter for u to show up in the
printouts? How to remove it? I mean remove the u in the "result"
dictionary (for this, you can click the link I've provided)?
Thank you for your help!
Linfeng
Struts2: Displaying text/huge file in textarea or frame
Struts2: Displaying text/huge file in textarea or frame
I have a huge content of data which is stored in a data-structure
(TreeMap) in the backend and I need to display that in my UI which should
be based on struts2.
Any idea on how to display the content of the Map in the struts2 front end
screen?
In backend I will be using a for loop to iterate through each record of
the map and need to display it line by line in the front end. I don't
think that I can use textarea for this. Whether there is any feature
available in struts2 to print it line by line in the front end by reading
it from backend. I am totally new to struts and It will be great if I
could get any suggestions. Please let me know in case if any clarification
is needed.
I have a huge content of data which is stored in a data-structure
(TreeMap) in the backend and I need to display that in my UI which should
be based on struts2.
Any idea on how to display the content of the Map in the struts2 front end
screen?
In backend I will be using a for loop to iterate through each record of
the map and need to display it line by line in the front end. I don't
think that I can use textarea for this. Whether there is any feature
available in struts2 to print it line by line in the front end by reading
it from backend. I am totally new to struts and It will be great if I
could get any suggestions. Please let me know in case if any clarification
is needed.
Is there a way to detect if a website uses a a known DDoS protection service (Prolexic for example)?
Is there a way to detect if a website uses a a known DDoS protection
service (Prolexic for example)?
Is there a way to check if a website uses a a known DDoS protection
service (Prolexic for example)?
My first guess was to look at the IP address the website resolves (and see
if it matches the protection service provider) to, but I am not sure that
proves anything.
service (Prolexic for example)?
Is there a way to check if a website uses a a known DDoS protection
service (Prolexic for example)?
My first guess was to look at the IP address the website resolves (and see
if it matches the protection service provider) to, but I am not sure that
proves anything.
SQL Azure Automated Backups doesn't work
SQL Azure Automated Backups doesn't work
I configured automated export of my SQL azure db, but backups are not
created. Also, I'am resieved this mail.
Automated SQL Export failed for pgmkixvn6d:aplicensingdb at 25.09.2013
23:06:45. The temporary database copy was made, but this copy could not be
exported to the .bacpac file in storage.
NOTES: We recommend checking that the storage account is available, and
that you can perform a manual export to that account. We will attempt to
export again at the next scheduled time
I tryed to export db manualy in this storage accaunt — it was created
without problems.
I configured automated export of my SQL azure db, but backups are not
created. Also, I'am resieved this mail.
Automated SQL Export failed for pgmkixvn6d:aplicensingdb at 25.09.2013
23:06:45. The temporary database copy was made, but this copy could not be
exported to the .bacpac file in storage.
NOTES: We recommend checking that the storage account is available, and
that you can perform a manual export to that account. We will attempt to
export again at the next scheduled time
I tryed to export db manualy in this storage accaunt — it was created
without problems.
Monday, 30 September 2013
Using a big brace over multiple lines - multiple lines left of it tex.stackexchange.com
Using a big brace over multiple lines - multiple lines left of it –
tex.stackexchange.com
I am super helpless, I wanna do the following: Mathmode, 2 lines on the
left, a brace over both (using array) and than I wanna have 3 lines on the
right. A small example: \begin{align*} \left. ...
tex.stackexchange.com
I am super helpless, I wanna do the following: Mathmode, 2 lines on the
left, a brace over both (using array) and than I wanna have 3 lines on the
right. A small example: \begin{align*} \left. ...
Interesing, hard limit with sum, involving $\pi$
Interesing, hard limit with sum, involving $\pi$
Yesterday I was boring so I decided to derive formula for area of circle
with integrals. Very good exercise, I think, because I forgot many, many
things about integrals. So I started with: $$\int_{-r}^{r}
\sqrt{r^2-x^2}dx$$ but I didn't have any clue how to count indefinite
integral $\int\sqrt{r^2-x^2}dx$ (is it even possible? today I only found
method for counting definite integral above with trigonometric
substitution, but this does not apply in general), so I decided to use
Riemann's theorem, since I only need to count definite integral. And
everything was going well, till something extremely interesting happend.
The last step I need to do is to find this limit: $$\lim_{n \to
+\infty}\frac{1}{n}\sum_{k=1}^{n}\sqrt{\frac{k}{n}\cdot\frac{n-k}{n}}$$
Surprisingly it is equal to $\frac{\pi}{8}$, and it is mindblowing ;-) but
I only know that because I know formula for area of circle which I'm
trying to derive. But without knowing it, is it possible to calculate this
limit with relatively simple methods? I really, really want to to this in
order to award my attempts. Can anybody help?
Yesterday I was boring so I decided to derive formula for area of circle
with integrals. Very good exercise, I think, because I forgot many, many
things about integrals. So I started with: $$\int_{-r}^{r}
\sqrt{r^2-x^2}dx$$ but I didn't have any clue how to count indefinite
integral $\int\sqrt{r^2-x^2}dx$ (is it even possible? today I only found
method for counting definite integral above with trigonometric
substitution, but this does not apply in general), so I decided to use
Riemann's theorem, since I only need to count definite integral. And
everything was going well, till something extremely interesting happend.
The last step I need to do is to find this limit: $$\lim_{n \to
+\infty}\frac{1}{n}\sum_{k=1}^{n}\sqrt{\frac{k}{n}\cdot\frac{n-k}{n}}$$
Surprisingly it is equal to $\frac{\pi}{8}$, and it is mindblowing ;-) but
I only know that because I know formula for area of circle which I'm
trying to derive. But without knowing it, is it possible to calculate this
limit with relatively simple methods? I really, really want to to this in
order to award my attempts. Can anybody help?
Oracle forms migrated from 10g to 11g
Oracle forms migrated from 10g to 11g
Once exported from oracle 10g to 11g, It is saying some java beans are
missing in the form. Is there something we need to change the FORM beans
path in new version.If not, Where are we mentioning the path for java
beans in reports.
Once exported from oracle 10g to 11g, It is saying some java beans are
missing in the form. Is there something we need to change the FORM beans
path in new version.If not, Where are we mentioning the path for java
beans in reports.
What is the opposite of Regexp.escape?
What is the opposite of Regexp.escape?
What is the opposite of Regexp.escape ?
> Regexp.escape('A & B')
=> "A\\ &\\ B"
> # do something --
=> "A & B"
How can I get the original value?
What is the opposite of Regexp.escape ?
> Regexp.escape('A & B')
=> "A\\ &\\ B"
> # do something --
=> "A & B"
How can I get the original value?
Sunday, 29 September 2013
How can I start Emacs with predefined window?
How can I start Emacs with predefined window?
Is there a way to make my Emacs start with predefined frame as my attached
screenshot? I am not familiar enough how to do it in my .emacs script...
It is as simple as doing :
split-window-horizontally (create two window side by side)
split-window-vertically (split the first window in the left into two part).
And in the last window, I want it to upload a calendar. I make this
arrangement mostly because my monitor have a broken LCD in the left part
of it. So my code must be in the right side of the screen :)
Is there a way to make my Emacs start with predefined frame as my attached
screenshot? I am not familiar enough how to do it in my .emacs script...
It is as simple as doing :
split-window-horizontally (create two window side by side)
split-window-vertically (split the first window in the left into two part).
And in the last window, I want it to upload a calendar. I make this
arrangement mostly because my monitor have a broken LCD in the left part
of it. So my code must be in the right side of the screen :)
Is it possible to update an F# entity in RavenDB without abandoning immutability?
Is it possible to update an F# entity in RavenDB without abandoning
immutability?
I have become a great fan of the powerful type system in F# and how it
allows you to create some very tight restraints on your domain models (for
those interested, see this). I have also become a great fan of RavenDB and
how it makes database work very simple in most of the cases I run into.
However, there seems to be issues getting the two to play nicely together
- at least if you insist on immutable types.
As long as you don't ever have to update your entities, all you need to do
is make the id property mutable. While I'm certainly not happy that this
is necessary, I can live with it. However, it seems that change tracking
is handled in such a way that you must mutate the original object
retrieved from the database and it is not possible to attach a new object
to the database to represent an updated version of an existing entity. It
does seem to be possible to do what I want using the patching API, but the
documentation clearly warns against this type of general usage.
Am I missing a part of the RavenDB API that will let me do this without
too much fuss or must I abandon the idea of immutable domain models (or
perhaps make a feature request for it)?
immutability?
I have become a great fan of the powerful type system in F# and how it
allows you to create some very tight restraints on your domain models (for
those interested, see this). I have also become a great fan of RavenDB and
how it makes database work very simple in most of the cases I run into.
However, there seems to be issues getting the two to play nicely together
- at least if you insist on immutable types.
As long as you don't ever have to update your entities, all you need to do
is make the id property mutable. While I'm certainly not happy that this
is necessary, I can live with it. However, it seems that change tracking
is handled in such a way that you must mutate the original object
retrieved from the database and it is not possible to attach a new object
to the database to represent an updated version of an existing entity. It
does seem to be possible to do what I want using the patching API, but the
documentation clearly warns against this type of general usage.
Am I missing a part of the RavenDB API that will let me do this without
too much fuss or must I abandon the idea of immutable domain models (or
perhaps make a feature request for it)?
Algorithm Complexity: Parameter Nature Changing the Result?
Algorithm Complexity: Parameter Nature Changing the Result?
Say, there is such the algorithm:
for (int i = 1; i < k; i++) {
for (int j = 0; j < (n-k)/(k-1); j=j+2) {
someFunction();
}
}
as you can see there is one nested loop and the function. Let the
function's complexity is O(g_i * (log g_i)), where g_i = (n-k)/(k-1) - j.
1) Am I right that if k is a part of n (k = n/b, where b is a constant),
the overall complexity of the algorithm is O(n), even if b is some huge
constant? [someFunction()'s complexity becomes O(1) at each iteration and
multiplying this value to (n-k)/(2*(k-1)) again gives O(1) because of the
k's nature, and the outer loop gives the O(n)]
2) Am I right that if k is a constant (event a huge one), the overall
complexity is O(n^2 * log n'), where n' is [actually don't know, how to
evaluate this] ? [the only inner loop is important in a complexity
evaluation]
Say, there is such the algorithm:
for (int i = 1; i < k; i++) {
for (int j = 0; j < (n-k)/(k-1); j=j+2) {
someFunction();
}
}
as you can see there is one nested loop and the function. Let the
function's complexity is O(g_i * (log g_i)), where g_i = (n-k)/(k-1) - j.
1) Am I right that if k is a part of n (k = n/b, where b is a constant),
the overall complexity of the algorithm is O(n), even if b is some huge
constant? [someFunction()'s complexity becomes O(1) at each iteration and
multiplying this value to (n-k)/(2*(k-1)) again gives O(1) because of the
k's nature, and the outer loop gives the O(n)]
2) Am I right that if k is a constant (event a huge one), the overall
complexity is O(n^2 * log n'), where n' is [actually don't know, how to
evaluate this] ? [the only inner loop is important in a complexity
evaluation]
Understanding disposable objects
Understanding disposable objects
I've looked in SO about a question like this one, and even that I've found
quite a few, any of those threw any light into this matter for me.
Let's assume I have this code:
public class SuperObject : IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) { }
}
Do I need the protected virtual void Dispose(bool) on SuperObject? Since
there is really nothing to dispose there.
public interface ICustom : IDisposable { }
public class Custom : ICustom
{
public SuperObject Super { get; protected set; }
public Custom()
{
Super = new SuperObject();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (!disposing) return;
if (Super != null)
Super.Dispose();
}
}
public class Foo
{
public Foo()
{
using (var c = new Custom())
{
//do magic with c
}
}
}
Now what happens if I want/need/try to use Custom on a class like
System.Web.Mvc.Controller which already implements and has implemented
IDisposable?
public class Moo : Controller
{
Custom c;
public Moo()
{
c = new Custom();
}
// Use c throughout this class
}
How to properly dispose c in Moo?
I've looked in SO about a question like this one, and even that I've found
quite a few, any of those threw any light into this matter for me.
Let's assume I have this code:
public class SuperObject : IDisposable
{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) { }
}
Do I need the protected virtual void Dispose(bool) on SuperObject? Since
there is really nothing to dispose there.
public interface ICustom : IDisposable { }
public class Custom : ICustom
{
public SuperObject Super { get; protected set; }
public Custom()
{
Super = new SuperObject();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (!disposing) return;
if (Super != null)
Super.Dispose();
}
}
public class Foo
{
public Foo()
{
using (var c = new Custom())
{
//do magic with c
}
}
}
Now what happens if I want/need/try to use Custom on a class like
System.Web.Mvc.Controller which already implements and has implemented
IDisposable?
public class Moo : Controller
{
Custom c;
public Moo()
{
c = new Custom();
}
// Use c throughout this class
}
How to properly dispose c in Moo?
Saturday, 28 September 2013
DIV won't show up in PHP echo
DIV won't show up in PHP echo
I am updating my website again, and this time I´m about to use a
Javascript Popup box with my register script.
This is the one I want to use: LINK
Here is the part of my code:
IF ($q3)
{
IF ($admin_default_activate == 0)
{
echo "<span style=\"color:green\">Your account is created, but
requires an Administrator to activate it.</span>";
}
ELSE
{ ?>
<div id="modal">
<div id="heading">
Your account is created and activated!
</div>
<div id="boxcontent">
<p><b>Account Details:</b><br><b>Email:</b>
test@website.se<br /><b>Password:</b>
password<br><br><b>Settings:</b><br><b>POP3:</b>
mail.website.se (Port 110)<br><b>IMAP:</b>
mail.website.se (Port 143)<br><b>SMTP:</b>
mail.website.se (Port 25/587)</p>
<a href="#" class="button red close"><img
src="popup/images/cross.png">Stäng</a>
</div>
</div>
<?php
}
}
ELSE
{
//echo "<span style=\"color:red\">Database error, could not create
email account!. Contact the Administrator</span>";
}
The Javascript code is inside the tag, but it still dont work.
The original button code is:
<a href="#" id="button">Click me</a>
And the one I use now is:
<input type="submit" id="button" name="submit" value="Create">
I dont know if that makes any differens..
Some help would be very good! =)
// Hampe
PS: Sorry for my bad English, I´m from Sweden
I am updating my website again, and this time I´m about to use a
Javascript Popup box with my register script.
This is the one I want to use: LINK
Here is the part of my code:
IF ($q3)
{
IF ($admin_default_activate == 0)
{
echo "<span style=\"color:green\">Your account is created, but
requires an Administrator to activate it.</span>";
}
ELSE
{ ?>
<div id="modal">
<div id="heading">
Your account is created and activated!
</div>
<div id="boxcontent">
<p><b>Account Details:</b><br><b>Email:</b>
test@website.se<br /><b>Password:</b>
password<br><br><b>Settings:</b><br><b>POP3:</b>
mail.website.se (Port 110)<br><b>IMAP:</b>
mail.website.se (Port 143)<br><b>SMTP:</b>
mail.website.se (Port 25/587)</p>
<a href="#" class="button red close"><img
src="popup/images/cross.png">Stäng</a>
</div>
</div>
<?php
}
}
ELSE
{
//echo "<span style=\"color:red\">Database error, could not create
email account!. Contact the Administrator</span>";
}
The Javascript code is inside the tag, but it still dont work.
The original button code is:
<a href="#" id="button">Click me</a>
And the one I use now is:
<input type="submit" id="button" name="submit" value="Create">
I dont know if that makes any differens..
Some help would be very good! =)
// Hampe
PS: Sorry for my bad English, I´m from Sweden
Convert string to desired format using python
Convert string to desired format using python
I want to substitute the following:
default by <http://www.mycompany.com/>
db: by <http://www.mydbcompany.com/>
I have data of the following format:
<a> <b> <c>.
<d> db:connect <e>.
db:start <f> <g>.
<h> <i> "hello".
Now I want to transform this data into the following form:
<http://www.mycompany.com/a> <http://www.mycompany.com/b>
<http://www.mycompany.com/c>.
<http://www.mycompany.com/d> <http://www.mydbcompany.com/connect>
<http://www.mycompany.com/e>.
<http://www.mydbcompany.com/start> <http://www.mycompany.com/f>
<http://www.mycompany.com/g>.
<http://www.mycompany.com/h> <http://www.mycompany.com/i> "hello".
Now the way I am trying to achieve the desired format is to separate to
break each line by using:
line1=re.split('(?<=)\s+(?=<)',line)
and then for line1[0], line1[1], line1[2] I try to
substitute < by <http://www.mycompany.com/
However, my problem is that this approach does not work for db: and
quotes. Is there some way by which I may achieve the desired output in
python
I want to substitute the following:
default by <http://www.mycompany.com/>
db: by <http://www.mydbcompany.com/>
I have data of the following format:
<a> <b> <c>.
<d> db:connect <e>.
db:start <f> <g>.
<h> <i> "hello".
Now I want to transform this data into the following form:
<http://www.mycompany.com/a> <http://www.mycompany.com/b>
<http://www.mycompany.com/c>.
<http://www.mycompany.com/d> <http://www.mydbcompany.com/connect>
<http://www.mycompany.com/e>.
<http://www.mydbcompany.com/start> <http://www.mycompany.com/f>
<http://www.mycompany.com/g>.
<http://www.mycompany.com/h> <http://www.mycompany.com/i> "hello".
Now the way I am trying to achieve the desired format is to separate to
break each line by using:
line1=re.split('(?<=)\s+(?=<)',line)
and then for line1[0], line1[1], line1[2] I try to
substitute < by <http://www.mycompany.com/
However, my problem is that this approach does not work for db: and
quotes. Is there some way by which I may achieve the desired output in
python
Adding date field to java
Adding date field to java
I am creating a program. Now, i want the users to enter their date of
birth in a field. I have no idea on how to do this. I am using net beans .
There doesn't seem to have any other field type. I have been searching
over the internet for some time. Also i will be storing this date of birth
to the my sql database. How can i achieve it?
Or is there a way to include some kind of calender into the program so
users can just click it. But this is just optional
thanks. I am beginner :) so please explain with code.
I am creating a program. Now, i want the users to enter their date of
birth in a field. I have no idea on how to do this. I am using net beans .
There doesn't seem to have any other field type. I have been searching
over the internet for some time. Also i will be storing this date of birth
to the my sql database. How can i achieve it?
Or is there a way to include some kind of calender into the program so
users can just click it. But this is just optional
thanks. I am beginner :) so please explain with code.
How to hide controls in flow player
How to hide controls in flow player
<param
name="flashVars"
value="config={'playlist':['screenshot.jpg',
{'url':'video.mp4','autoPlay':true}]}"
/>
which config key = value, should I put to hide the controls in flowplayer?
<param
name="flashVars"
value="config={'playlist':['screenshot.jpg',
{'url':'video.mp4','autoPlay':true}]}"
/>
which config key = value, should I put to hide the controls in flowplayer?
Friday, 27 September 2013
how to drawImage in context with scale and mask?
how to drawImage in context with scale and mask?
I'm making a magnifier view with scale and render a part of view in a
magnifier-shape mask, like following
- (UIImage *)magnifierInFrame:(CGRect)frame scale:(CGFloat)scaleFactor {
CGSize imageSize = frame.size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextScaleCTM(c, scaleFactor, scaleFactor);
CGContextConcatCTM(c,
CGAffineTransformMakeTranslation(-frame.origin.x,
-frame.origin.y));
[[UIImage imageNamed:@"magnifier_background"] drawInRect:frame];
CGContextClipToMask(c, frame, [UIImage
imageNamed:@"magnifier_content_mask"].CGImage);
[self.layer renderInContext:c];
UIImage *magnifierImage =
UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return magnifierImage;
}
because I scale the context, as a result, the magnifier_content_mask area
is scaled as well, but it should not scale magnifier_content_mask and
magnifier_background area, and only scale view content in frame, is there
any way to do it?
I'm making a magnifier view with scale and render a part of view in a
magnifier-shape mask, like following
- (UIImage *)magnifierInFrame:(CGRect)frame scale:(CGFloat)scaleFactor {
CGSize imageSize = frame.size;
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextScaleCTM(c, scaleFactor, scaleFactor);
CGContextConcatCTM(c,
CGAffineTransformMakeTranslation(-frame.origin.x,
-frame.origin.y));
[[UIImage imageNamed:@"magnifier_background"] drawInRect:frame];
CGContextClipToMask(c, frame, [UIImage
imageNamed:@"magnifier_content_mask"].CGImage);
[self.layer renderInContext:c];
UIImage *magnifierImage =
UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return magnifierImage;
}
because I scale the context, as a result, the magnifier_content_mask area
is scaled as well, but it should not scale magnifier_content_mask and
magnifier_background area, and only scale view content in frame, is there
any way to do it?
getline and passing input streams inside class functions, primary-expression error
getline and passing input streams inside class functions,
primary-expression error
I have a file called grades.txt with some lines of text and integers on it
that i want to read into an already defined class ive created called
Assignment.
int main()
{
ifstream input_file("grades.txt");
Assignment assignment;
input_file >> assignment;
return 0;
}
Above is my main function that will read input_file into the created class
assignment.
friend istream& operator >> (istream& is, Assignment& assignment)
{ // function to read in data to class variables
string line;
getline(*****, line);
// to be able to operate on strings
istringstream iss(line);
// set values read in from input file.
iss >> assignment.Assignment_type;
iss >> assignment.Date;
iss >> assignment.Max_score;
iss >> assignment.Actual_score;
// sometimes Assignment Name will have spaces, have to use getline()
getline(is, assignment.Assignment_name);
return is;
}
Heres the class function that will overload the >> operator to read into
each of the variables in assignment. the group of stars is what im having
problems with, i dont know what to pass to it. I've tried ifstream and
ofstream thinking it was that easy but they return the same error code
P01.cpp:34:21: error: expected primary-expression before ',' token
primary-expression error
I have a file called grades.txt with some lines of text and integers on it
that i want to read into an already defined class ive created called
Assignment.
int main()
{
ifstream input_file("grades.txt");
Assignment assignment;
input_file >> assignment;
return 0;
}
Above is my main function that will read input_file into the created class
assignment.
friend istream& operator >> (istream& is, Assignment& assignment)
{ // function to read in data to class variables
string line;
getline(*****, line);
// to be able to operate on strings
istringstream iss(line);
// set values read in from input file.
iss >> assignment.Assignment_type;
iss >> assignment.Date;
iss >> assignment.Max_score;
iss >> assignment.Actual_score;
// sometimes Assignment Name will have spaces, have to use getline()
getline(is, assignment.Assignment_name);
return is;
}
Heres the class function that will overload the >> operator to read into
each of the variables in assignment. the group of stars is what im having
problems with, i dont know what to pass to it. I've tried ifstream and
ofstream thinking it was that easy but they return the same error code
P01.cpp:34:21: error: expected primary-expression before ',' token
Why this [haskell] compilation error?
Why this [haskell] compilation error?
module Main
alicebob :: String -> String
alicebob "alice" = "Hi alice"
alicebob "bob" = "Hi bob"
alicebob _ = "Hi person whose name is neither alice nor bob."
greet :: IO ()
greet = do
putStrLn "hi. whats your name?"
name <- getLine
putStrLn (alicebob name)
Simple programming exercise to get some user input, and reply. Just
starting to learn haskell so please excuse the simple question. Getting an
error on line alicebob :: String -> String. How can I fix it?
module Main
alicebob :: String -> String
alicebob "alice" = "Hi alice"
alicebob "bob" = "Hi bob"
alicebob _ = "Hi person whose name is neither alice nor bob."
greet :: IO ()
greet = do
putStrLn "hi. whats your name?"
name <- getLine
putStrLn (alicebob name)
Simple programming exercise to get some user input, and reply. Just
starting to learn haskell so please excuse the simple question. Getting an
error on line alicebob :: String -> String. How can I fix it?
how to compare and call function in javascript
how to compare and call function in javascript
Hello im just studiing javascript and im making a form where it will ask
for a start address and a destination address. What i want to do but cant
figure out is how i can get javascript to compare the two value if my
input box and if it exist on the function it will show a messege, but if
it doesnt exist it will still loop till it finds the value and show the
messege or show an error if it really dont have anything.
base on this HTML form
<div id="panel">
<form>
<input type="text" placeholder="Start Address" id="start" >
<input type="text" placeholder="Destination Address" id="end">
<input type="button" value="Get Direction" id="SubmitBtn"
onclick="printme()" >
</form>
</div>
<div id="infopanel">
</div>
example : if start and end is equal to plane ride show "you must ride a
plane " or if start and end is equal to boat ride show " you must ride a
boat" or if start and end is equal to bus ride show " you must ride a bus"
else show you cant go there.
Hello im just studiing javascript and im making a form where it will ask
for a start address and a destination address. What i want to do but cant
figure out is how i can get javascript to compare the two value if my
input box and if it exist on the function it will show a messege, but if
it doesnt exist it will still loop till it finds the value and show the
messege or show an error if it really dont have anything.
base on this HTML form
<div id="panel">
<form>
<input type="text" placeholder="Start Address" id="start" >
<input type="text" placeholder="Destination Address" id="end">
<input type="button" value="Get Direction" id="SubmitBtn"
onclick="printme()" >
</form>
</div>
<div id="infopanel">
</div>
example : if start and end is equal to plane ride show "you must ride a
plane " or if start and end is equal to boat ride show " you must ride a
boat" or if start and end is equal to bus ride show " you must ride a bus"
else show you cant go there.
Python if statement checking for a £ pound sign in a string?
Python if statement checking for a £ pound sign in a string?
I have the following line which is causing me problems:
if "Total £" in studentfees:
returns:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa3 in position 4:
ordinal not in range(128)
How can I get around this?
Thanks in advance - Hyflex
I have the following line which is causing me problems:
if "Total £" in studentfees:
returns:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xa3 in position 4:
ordinal not in range(128)
How can I get around this?
Thanks in advance - Hyflex
How to get Phone number from Android Cursor?
How to get Phone number from Android Cursor?
Following this tutorial I'm trying to get the phone number of a person in
the contacts list. With this code I can get the email address:
if (cursor.moveToFirst()){
int emailIdx = cursor.getColumnIndex(Email.DATA);
String email = cursor.getString(emailIdx);
Log.wtf("Email address: ", email);
}
Following this reasoning I tried to get the Phone number like this:
if (cursor.moveToFirst()){
int phoneNrIdx = cursor.getColumnIndex(Phone.DATA);
String phoneNr = cursor.getString(phoneNrIdx);
Log.wtf("Phone number:", phoneNr);
}
Unfortunately this also returns the email address. Does anybody know how I
can get the phone number of this contact? All tips are welcome!
Following this tutorial I'm trying to get the phone number of a person in
the contacts list. With this code I can get the email address:
if (cursor.moveToFirst()){
int emailIdx = cursor.getColumnIndex(Email.DATA);
String email = cursor.getString(emailIdx);
Log.wtf("Email address: ", email);
}
Following this reasoning I tried to get the Phone number like this:
if (cursor.moveToFirst()){
int phoneNrIdx = cursor.getColumnIndex(Phone.DATA);
String phoneNr = cursor.getString(phoneNrIdx);
Log.wtf("Phone number:", phoneNr);
}
Unfortunately this also returns the email address. Does anybody know how I
can get the phone number of this contact? All tips are welcome!
Can (this) throws a NullPointerException?
Can (this) throws a NullPointerException?
I have an Activity with checkbox that triggers onCheckedChanged(), and I
initializing it by using.
CheckBox check = (CheckBox) findViewById(R.id.checkbox_accept);
check.setOnCheckedChangeListener(this);
here's the xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearlayout_welcome_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/nce_a1_default_icon_signup_background"
android:orientation="vertical" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:fillViewport="true"
android:isScrollContainer="true"
android:scrollbars="none" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="10dp" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:src="@drawable/nce_a1_default_icon_signup_start" />
<CheckBox
android:id="@+id/checkbox_accept"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:background="@drawable/checkmarkbox_bg"
android:button="@drawable/nce_a1_default_icon_checkmark_box_selector"
android:paddingBottom="5dp"
android:paddingLeft="25dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:text="@string/sign_up_yeah_sure_verify_me"
android:textColor="@color/black_opacity_90"
android:textSize="14sp" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/nce_a1_default_icon_delete_bar"
android:gravity="center"
android:orientation="horizontal"
android:padding="10dp" >
<Button
android:id="@+id/btn_learn_more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="@drawable/nce_a1_default_icon_button_dont_get_it_selector"
/>
<Button
android:id="@+id/btn_continue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:background="@drawable/nce_a1_default_icon_button_lets_go_selector"
android:enabled="false" >
</Button>
</LinearLayout>
</LinearLayout>
what weird is it works but there is a time that it caused
NullPointerException. Should I use (MainActivity.this) instead of (this)
only? Is there a difference between the two?
one thing I have the same id's in different layout. Should it be the
caused? but I think that is fine because I'm using a View.
I have an Activity with checkbox that triggers onCheckedChanged(), and I
initializing it by using.
CheckBox check = (CheckBox) findViewById(R.id.checkbox_accept);
check.setOnCheckedChangeListener(this);
here's the xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearlayout_welcome_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/nce_a1_default_icon_signup_background"
android:orientation="vertical" >
<ScrollView
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:fillViewport="true"
android:isScrollContainer="true"
android:scrollbars="none" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="10dp" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight="1"
android:src="@drawable/nce_a1_default_icon_signup_start" />
<CheckBox
android:id="@+id/checkbox_accept"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|bottom"
android:background="@drawable/checkmarkbox_bg"
android:button="@drawable/nce_a1_default_icon_checkmark_box_selector"
android:paddingBottom="5dp"
android:paddingLeft="25dp"
android:paddingRight="5dp"
android:paddingTop="5dp"
android:text="@string/sign_up_yeah_sure_verify_me"
android:textColor="@color/black_opacity_90"
android:textSize="14sp" />
</LinearLayout>
</ScrollView>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/nce_a1_default_icon_delete_bar"
android:gravity="center"
android:orientation="horizontal"
android:padding="10dp" >
<Button
android:id="@+id/btn_learn_more"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:background="@drawable/nce_a1_default_icon_button_dont_get_it_selector"
/>
<Button
android:id="@+id/btn_continue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:background="@drawable/nce_a1_default_icon_button_lets_go_selector"
android:enabled="false" >
</Button>
</LinearLayout>
</LinearLayout>
what weird is it works but there is a time that it caused
NullPointerException. Should I use (MainActivity.this) instead of (this)
only? Is there a difference between the two?
one thing I have the same id's in different layout. Should it be the
caused? but I think that is fine because I'm using a View.
Thursday, 26 September 2013
How to set the today's date in datepicker textbox in angularjs
How to set the today's date in datepicker textbox in angularjs
I have two datepicker textbox From date and To Date... I need default in
From date this month start date and To date today's day...
How to set default dates in Angularjs Datepicker textbox..?
I have two datepicker textbox From date and To Date... I need default in
From date this month start date and To date today's day...
How to set default dates in Angularjs Datepicker textbox..?
Wednesday, 25 September 2013
Error while calling Cross domain API
Error while calling Cross domain API
I am calling a cross domain webservice api from ajax in my js, but i am
getting an error as:-
"XMLHttpRequest cannot load http://url2.com/social/polling/get_poll.
Origin http://url1.com is not allowed by Access-Control-Allow-Origin"
i also tried to set Access-Control-Allow-Origin to * in header of request
, but then to no success, i am getting same error
Below is what i am actually doing:-
$.ajax({
type : "POST",
dataType : "jsonp",
data : {
pollId : pollId
},
/* header : {'Access-Control-Allow-Origin':'*'}, */
url : "http://url2.com/social/rs/polling/get_poll",
beforeSend : function(xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin',
'*');
},
success : function(response) {
var html;
var html = "<div ><h2>" + response.topic + "</h2>";
for ( var index = 0; index < response.options.length; index++) {
html = html
+ "<input type=\"checkbox\" name=\"option\" value=\""
+ response.options[index] + "\" />"
+ response.options[index] + "<br/>";
}
html = html
+ "<input type=\"button\" value=\"Submit\"
onclick=\"pollIT("
+ response.pollId + ", '" + response.topic
+ "'); \" /></div>";
$("#question").append("");
$("#question").append(html);
html = "";
},
error : function(e) {
console.log(e);
return false;
}
});
I have also tried setting header as header :
{'Access-Control-Allow-Origin':'*'}, but still unsuccessful. Please Help
me to get out of this
I am calling a cross domain webservice api from ajax in my js, but i am
getting an error as:-
"XMLHttpRequest cannot load http://url2.com/social/polling/get_poll.
Origin http://url1.com is not allowed by Access-Control-Allow-Origin"
i also tried to set Access-Control-Allow-Origin to * in header of request
, but then to no success, i am getting same error
Below is what i am actually doing:-
$.ajax({
type : "POST",
dataType : "jsonp",
data : {
pollId : pollId
},
/* header : {'Access-Control-Allow-Origin':'*'}, */
url : "http://url2.com/social/rs/polling/get_poll",
beforeSend : function(xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin',
'*');
},
success : function(response) {
var html;
var html = "<div ><h2>" + response.topic + "</h2>";
for ( var index = 0; index < response.options.length; index++) {
html = html
+ "<input type=\"checkbox\" name=\"option\" value=\""
+ response.options[index] + "\" />"
+ response.options[index] + "<br/>";
}
html = html
+ "<input type=\"button\" value=\"Submit\"
onclick=\"pollIT("
+ response.pollId + ", '" + response.topic
+ "'); \" /></div>";
$("#question").append("");
$("#question").append(html);
html = "";
},
error : function(e) {
console.log(e);
return false;
}
});
I have also tried setting header as header :
{'Access-Control-Allow-Origin':'*'}, but still unsuccessful. Please Help
me to get out of this
Thursday, 19 September 2013
Can't see components in JScrollPane
Can't see components in JScrollPane
I'm using a JScrollPane to hold a JTextArea for a large area of text. I
add the TextArea directly to the JFrame, it works fine. But I add it to
the scrollpane and add the scrollpane, I don't see the textarea. Here's my
SSCCE:
textPane.add(chatMonitor);
textPane.setAutoscrolls(true);
textPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textPane.setVisible(true);
add(textPane);
I'm using a JScrollPane to hold a JTextArea for a large area of text. I
add the TextArea directly to the JFrame, it works fine. But I add it to
the scrollpane and add the scrollpane, I don't see the textarea. Here's my
SSCCE:
textPane.add(chatMonitor);
textPane.setAutoscrolls(true);
textPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
textPane.setVisible(true);
add(textPane);
WCF Return different fault depending on RequestFormat
WCF Return different fault depending on RequestFormat
I have a WCF method:
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "exception")]
public List<Color> GenerateException()
I want to return a different fault based on the client (SOAP vs JSON)
because they don't seem to have visibility to the message if I don't.
So I check the content type and choose my type accordingly
String ct = WebOperationContext.Current.IncomingRequest.ContentType;
FaultException fe = new FaultException(errorMessage, new
FaultCode(errorCode));
WebFaultException<ErrorData> errorDataWebFault = new
WebFaultException<ErrorData> (errorData,
System.Net.HttpStatusCode.InternalServerError);
if (ct.Contains("text/xml"))
throw fe;
else//Can throw any of the WebFaultExceptions here
throw errorDataWebFault;
If I don't check, SOAP consumers can't see the message of
WebFaultExceptions, and JSON consumers cant see the message of the
FaultException.
Is there a better way to do this? Feels like there should be something
"built in".
I have a WCF method:
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "exception")]
public List<Color> GenerateException()
I want to return a different fault based on the client (SOAP vs JSON)
because they don't seem to have visibility to the message if I don't.
So I check the content type and choose my type accordingly
String ct = WebOperationContext.Current.IncomingRequest.ContentType;
FaultException fe = new FaultException(errorMessage, new
FaultCode(errorCode));
WebFaultException<ErrorData> errorDataWebFault = new
WebFaultException<ErrorData> (errorData,
System.Net.HttpStatusCode.InternalServerError);
if (ct.Contains("text/xml"))
throw fe;
else//Can throw any of the WebFaultExceptions here
throw errorDataWebFault;
If I don't check, SOAP consumers can't see the message of
WebFaultExceptions, and JSON consumers cant see the message of the
FaultException.
Is there a better way to do this? Feels like there should be something
"built in".
Change li class in javascript
Change li class in javascript
I want to change the class of the current li(list) which is selected
$('li.doBlokkeer').click(function(e) {
$(this).addClass('doDEBlokkeer').removeClass('doBlokkeer');
});
$('li.doDEBlokkeer').click(function(e) {
$(this).addClass('doBlokkeer').removeClass('doDEBlokkeer');
});
so if a current li is selected its class need to be changed (it needs to
have doDEBlokkeer). The above code works.. The problem is that this only
works once for each LI item..
when I click on li.doBlokkeer the class changes which is good, but when I
press the same current li again, it calls the same function li.doBlokkeer
instead of li.doDEBlokkeer function (despite the css class) . I tried so
much stuff but i really can't find any solution. can you guys help me out?
I have been searching for a solution for more then 14 hours, so frustrated
right now...
I want to change the class of the current li(list) which is selected
$('li.doBlokkeer').click(function(e) {
$(this).addClass('doDEBlokkeer').removeClass('doBlokkeer');
});
$('li.doDEBlokkeer').click(function(e) {
$(this).addClass('doBlokkeer').removeClass('doDEBlokkeer');
});
so if a current li is selected its class need to be changed (it needs to
have doDEBlokkeer). The above code works.. The problem is that this only
works once for each LI item..
when I click on li.doBlokkeer the class changes which is good, but when I
press the same current li again, it calls the same function li.doBlokkeer
instead of li.doDEBlokkeer function (despite the css class) . I tried so
much stuff but i really can't find any solution. can you guys help me out?
I have been searching for a solution for more then 14 hours, so frustrated
right now...
Xcode 5 / iOS7 error
Xcode 5 / iOS7 error
My App is nice and working fine in the app store. It even runs on iOS7
with no problems. However when I compile in Xcode 5 (for iOS7) its a
disaster. The status bar is missing, the view is all stretched out, it
doesn't pause where it should, and my third party advertiser's pop ups
don't show up. Anyone know what's going on, at least with the status bar
problem?
My App is nice and working fine in the app store. It even runs on iOS7
with no problems. However when I compile in Xcode 5 (for iOS7) its a
disaster. The status bar is missing, the view is all stretched out, it
doesn't pause where it should, and my third party advertiser's pop ups
don't show up. Anyone know what's going on, at least with the status bar
problem?
Error Message..!
Error Message..!
I have a project, i am trying to compile it on the Win32 and Win64
compilers using Visual Studio 2010. Primarily for the focus on Win 32.
With the build chain i can compile the project and generate the exe for
the Project both (debug and Release). However its quite starnage
behaviour. The Source contains the test cases may be around 150 or so.
when i am executing the Release, it goes upto 30 Test cases are executed
and stops with error message. However when i am executing the debug, in
four test cases the execution stops.
Error message with Debug :- "Microsoft Visual Studio C Runtime Library has
detected a fatal error in unittest_framework-win32-vc_100-x86-mt-d.exe."
CallStack Debug :-
msvcr100.dll!__crt_debugger_hook()
msvcr100.dll!__call_reportfault() + 0x25 bytes
msvcr100.dll!_abort() + 0x28 bytes
msvcr100.dll!__wassert() + 0x5ff bytes
> unittest_framework-win32-vc_100-x86-mt-d.exe!daddy::TOutputPin<val_cfg::CValCfgOutputBAP,daddy::TDefaultIntervention<val_cfg::CValCfgOutputBAP>
>::reserve(bool f_defaultConstruct_b, const val_cfg::CValCfgOutputBAP
* const f_placementChunkAddress_p) Line 83 + 0x27 bytes C++
unittest_framework-win32-vc_100-x86-mt-d.exe!val_cfg::CBAP::work_Rx(const
val_cfg::CValCfgOutPins & f_ValCfgOutPins) Line 56 + 0xf bytes C++
unittest_framework-win32-vc_100-x86-mt-d.exe!val_cfg::CReceiver::work_Motor_14(const
autobus::CAutobusBaseRx & f_RxMessage, const val_cfg::CValCfgOutPins &
f_ValCfgOutPins) Line 2563 C++
unittest_framework-win32-vc_100-x86-mt-d.exe!val_cfg::CReceiver::work(const
val_cfg::CValCfgOutPins & f_ValCfgOutPins) Line 67 C++
Error Message with Release :- "Unhandled exception at 0x771a15de
(ntdll.dll) in unittest_framework-win32-vc_100-x86-mt.exe: 0xC0000005:
Access violation reading location 0x00000005."
Callstack Release :-
unittest_framework-win32-vc_100-x86-mt.exe!CppUnit::TestComposite::run()
+ 0x1a bytes C++
unittest_framework-win32-vc_100-x86-mt.exe!CppUnit::TestRunner::WrappingSuite::run()
+ 0x27 bytes C++
unittest_framework-win32-vc_100-x86-mt.exe!CppUnit::TestResult::runTest()
+ 0x1a bytes C++
unittest_framework-win32-vc_100-x86-mt.exe!CppUnit::TestRunner::run()
+ 0x54 bytes C++
unittest_framework-win32-vc_100-x86-mt.exe!unittest_framework::testRoutine()
+ 0xdc bytes C++
unittest_framework-win32-vc_100-x86-mt.exe!_main() + 0x8a bytes C++
> unittest_framework-win32-vc_100-x86-mt.exe!__tmainCRTStartup() Line
555 + 0x17 bytes C
kernel32.dll!@BaseThreadInitThunk@12() + 0x12 bytes
ntdll.dll!___RtlUserThreadStart@8() + 0x27 bytes
ntdll.dll!__RtlUserThreadStart@8() + 0x1b bytes
First of all i am trying to figure out why it behaves differnetly. Project
Configuration: Win Console, Win32, Congi type:- Makefile.
I have a project, i am trying to compile it on the Win32 and Win64
compilers using Visual Studio 2010. Primarily for the focus on Win 32.
With the build chain i can compile the project and generate the exe for
the Project both (debug and Release). However its quite starnage
behaviour. The Source contains the test cases may be around 150 or so.
when i am executing the Release, it goes upto 30 Test cases are executed
and stops with error message. However when i am executing the debug, in
four test cases the execution stops.
Error message with Debug :- "Microsoft Visual Studio C Runtime Library has
detected a fatal error in unittest_framework-win32-vc_100-x86-mt-d.exe."
CallStack Debug :-
msvcr100.dll!__crt_debugger_hook()
msvcr100.dll!__call_reportfault() + 0x25 bytes
msvcr100.dll!_abort() + 0x28 bytes
msvcr100.dll!__wassert() + 0x5ff bytes
> unittest_framework-win32-vc_100-x86-mt-d.exe!daddy::TOutputPin<val_cfg::CValCfgOutputBAP,daddy::TDefaultIntervention<val_cfg::CValCfgOutputBAP>
>::reserve(bool f_defaultConstruct_b, const val_cfg::CValCfgOutputBAP
* const f_placementChunkAddress_p) Line 83 + 0x27 bytes C++
unittest_framework-win32-vc_100-x86-mt-d.exe!val_cfg::CBAP::work_Rx(const
val_cfg::CValCfgOutPins & f_ValCfgOutPins) Line 56 + 0xf bytes C++
unittest_framework-win32-vc_100-x86-mt-d.exe!val_cfg::CReceiver::work_Motor_14(const
autobus::CAutobusBaseRx & f_RxMessage, const val_cfg::CValCfgOutPins &
f_ValCfgOutPins) Line 2563 C++
unittest_framework-win32-vc_100-x86-mt-d.exe!val_cfg::CReceiver::work(const
val_cfg::CValCfgOutPins & f_ValCfgOutPins) Line 67 C++
Error Message with Release :- "Unhandled exception at 0x771a15de
(ntdll.dll) in unittest_framework-win32-vc_100-x86-mt.exe: 0xC0000005:
Access violation reading location 0x00000005."
Callstack Release :-
unittest_framework-win32-vc_100-x86-mt.exe!CppUnit::TestComposite::run()
+ 0x1a bytes C++
unittest_framework-win32-vc_100-x86-mt.exe!CppUnit::TestRunner::WrappingSuite::run()
+ 0x27 bytes C++
unittest_framework-win32-vc_100-x86-mt.exe!CppUnit::TestResult::runTest()
+ 0x1a bytes C++
unittest_framework-win32-vc_100-x86-mt.exe!CppUnit::TestRunner::run()
+ 0x54 bytes C++
unittest_framework-win32-vc_100-x86-mt.exe!unittest_framework::testRoutine()
+ 0xdc bytes C++
unittest_framework-win32-vc_100-x86-mt.exe!_main() + 0x8a bytes C++
> unittest_framework-win32-vc_100-x86-mt.exe!__tmainCRTStartup() Line
555 + 0x17 bytes C
kernel32.dll!@BaseThreadInitThunk@12() + 0x12 bytes
ntdll.dll!___RtlUserThreadStart@8() + 0x27 bytes
ntdll.dll!__RtlUserThreadStart@8() + 0x1b bytes
First of all i am trying to figure out why it behaves differnetly. Project
Configuration: Win Console, Win32, Congi type:- Makefile.
String.split a text
String.split a text
My program reads a line from a file. This line contains comma-seperated
text like:
123,test,444,"don't split, this",more test,1
I would like the result of a split to be this:
123
test
444
"don't split, this"
more test
1
If I use the String.split(","), I would get this:
123
test
444
"don't split
this"
more test
1
In other words: The comma in the substring "don't split, this" is not a
seperator. How to deal with this?
Thanks in advance.. Jakob
My program reads a line from a file. This line contains comma-seperated
text like:
123,test,444,"don't split, this",more test,1
I would like the result of a split to be this:
123
test
444
"don't split, this"
more test
1
If I use the String.split(","), I would get this:
123
test
444
"don't split
this"
more test
1
In other words: The comma in the substring "don't split, this" is not a
seperator. How to deal with this?
Thanks in advance.. Jakob
IOS, Android native app with webview
IOS, Android native app with webview
To build a webview for Android i know, and can do it, but how to create on
IOS, W8. I see, there is a many online generations services, but they
charges a very extra money, for only to use a webview. Is there a any
service that could to generate webview native app for free with they ads
or watermarks, no metter.
To build a webview for Android i know, and can do it, but how to create on
IOS, W8. I see, there is a many online generations services, but they
charges a very extra money, for only to use a webview. Is there a any
service that could to generate webview native app for free with they ads
or watermarks, no metter.
Wednesday, 18 September 2013
Input string was not in a correct format, error coming
Input string was not in a correct format, error coming
I m getting error:
input string was not in corect format
in the line:
int amount = Convert.ToInt32(txtAmount.Text);
I m getting error:
input string was not in corect format
in the line:
int amount = Convert.ToInt32(txtAmount.Text);
connect sql server using java script directly without server side language.
connect sql server using java script directly without server side language.
now I trying to connect sql server using java script directly without
server side language . for web interface is HTML5 , but it don't work at
all ! I also test it with 2 different connection string: 1.ODBC Connection
string 2.Oledb Connection string any recommend please ?
now I trying to connect sql server using java script directly without
server side language . for web interface is HTML5 , but it don't work at
all ! I also test it with 2 different connection string: 1.ODBC Connection
string 2.Oledb Connection string any recommend please ?
How to find functions, classes and IDs on HTML/CSS/Javascript/PHP
How to find functions, classes and IDs on HTML/CSS/Javascript/PHP
Intro: I am fixing a website that wasn't coded by me (first time) and I
would like to know the best way to find functions, classes and IDs
associations within all files of the website.
Main problem: The main problem is that I lose too much time trying do
discover what function does what and what elements are affected. For
example I look at a certain element with a certain ID or class and I have
to manually search all files to check associations.
Extra info: I currently use sublimetext and, some times, dreamweaver but I
am willing to use other programs if needed to be more efficient. The
website is mainly HTML, CSS and Javascript.
Intro: I am fixing a website that wasn't coded by me (first time) and I
would like to know the best way to find functions, classes and IDs
associations within all files of the website.
Main problem: The main problem is that I lose too much time trying do
discover what function does what and what elements are affected. For
example I look at a certain element with a certain ID or class and I have
to manually search all files to check associations.
Extra info: I currently use sublimetext and, some times, dreamweaver but I
am willing to use other programs if needed to be more efficient. The
website is mainly HTML, CSS and Javascript.
Logging in node.js to a file, without another module
Logging in node.js to a file, without another module
I'm running a node application as a daemon. When debugging the daemon, I
need to see the output, so I'd like to redirect stdout and stderr to a
file.
I'd expect I can just reassign stdout and stderr like in Python or C:
fs = require('fs');
process.stdout = fs.openSync('/var/log/foo', 'w');
process.stderr = process.stdout;
console.log('hello');
When I run the script directly, "hello" is printed to the console! Of
course when I run in the background, I see output neither on the console
(of course) or in /var/log/foo.
I don't want or need sophisticated logging. I just need to see the builtin
messages that node already provides.
I'm running a node application as a daemon. When debugging the daemon, I
need to see the output, so I'd like to redirect stdout and stderr to a
file.
I'd expect I can just reassign stdout and stderr like in Python or C:
fs = require('fs');
process.stdout = fs.openSync('/var/log/foo', 'w');
process.stderr = process.stdout;
console.log('hello');
When I run the script directly, "hello" is printed to the console! Of
course when I run in the background, I see output neither on the console
(of course) or in /var/log/foo.
I don't want or need sophisticated logging. I just need to see the builtin
messages that node already provides.
Capybara can find but not fill_in
Capybara can find but not fill_in
I am having some very strange behaviour with Capybara. It stubbornly
refuses to fill in the fields of my login form.
<fieldset>
<div class="clearfix">
<label for="user_email">E-Mail Adresse</label>
<div class="input">
<input id="user_email" name="user[email]" size="30" type="email"
value="">
</div>
</div>
<div class="clearfix">
<label for="user_password">Passwort</label>
<div class="input">
<input id="user_password" name="user[password]" size="30"
type="password" value="">
</div>
</div>
<div class="clearfix">
<div class="input">
<input name="user[remember_me]" type="hidden" value="0"><input
id="user_remember_me" name="user[remember_me]" type="checkbox"
value="1"> <label for="user_remember_me">angemeldet
bleiben</label>
</div>
</div>
</fieldset>
And here is where the fun begins:
within("#login_form"){ find("#user_email")}
=> #<Capybara::Element tag="input"
path="/html/body/div[2]/div[@id='content']/div/div[1]/form[@id='login_form']/fieldset/div[1]/div/input[@id='user_email']">
within("#login_form"){ fill_in("#user_email", with: "foo@example.com")}
Capybara::ElementNotFound: Unable to find field "#user_email"
I don't quite understand how it is possible to be able to find, and yet
not find, an element. Another pair of eyes on this would be appreciated.
I am having some very strange behaviour with Capybara. It stubbornly
refuses to fill in the fields of my login form.
<fieldset>
<div class="clearfix">
<label for="user_email">E-Mail Adresse</label>
<div class="input">
<input id="user_email" name="user[email]" size="30" type="email"
value="">
</div>
</div>
<div class="clearfix">
<label for="user_password">Passwort</label>
<div class="input">
<input id="user_password" name="user[password]" size="30"
type="password" value="">
</div>
</div>
<div class="clearfix">
<div class="input">
<input name="user[remember_me]" type="hidden" value="0"><input
id="user_remember_me" name="user[remember_me]" type="checkbox"
value="1"> <label for="user_remember_me">angemeldet
bleiben</label>
</div>
</div>
</fieldset>
And here is where the fun begins:
within("#login_form"){ find("#user_email")}
=> #<Capybara::Element tag="input"
path="/html/body/div[2]/div[@id='content']/div/div[1]/form[@id='login_form']/fieldset/div[1]/div/input[@id='user_email']">
within("#login_form"){ fill_in("#user_email", with: "foo@example.com")}
Capybara::ElementNotFound: Unable to find field "#user_email"
I don't quite understand how it is possible to be able to find, and yet
not find, an element. Another pair of eyes on this would be appreciated.
Access and SQL date comparison
Access and SQL date comparison
I have an Access 2010 front and sql2008 back. I am using a date parameter
on a form and a view for the report. It doesn't give me any data. It's not
understanding the access date paramter. I have tried converting the date
in sql, but still no data.
I have an Access 2010 front and sql2008 back. I am using a date parameter
on a form and a view for the report. It doesn't give me any data. It's not
understanding the access date paramter. I have tried converting the date
in sql, but still no data.
Can we use ueventobserver in android application
Can we use ueventobserver in android application
Can we use ueventobserver in an android application to watch the events
from a specific device? can we able to get the sysfs path of the specific
device?
Can we use ueventobserver in an android application to watch the events
from a specific device? can we able to get the sysfs path of the specific
device?
Recognizing email fields without using regular expressions
Recognizing email fields without using regular expressions
We have a tokenizer which tokenizes a text file .The logic followed is
quite weird but necessary in our context.
An email such as xyz.zyx@gmail.com
will result in the following tokens : xyz . zyx @ gmail
I would like to know how can we recognize the field as email if we are
allowed to use only these tokens. No regex is allowed. We are allowed only
to use the tokens and their surrounding tokens to figure out if the field
is an email field
We have a tokenizer which tokenizes a text file .The logic followed is
quite weird but necessary in our context.
An email such as xyz.zyx@gmail.com
will result in the following tokens : xyz . zyx @ gmail
I would like to know how can we recognize the field as email if we are
allowed to use only these tokens. No regex is allowed. We are allowed only
to use the tokens and their surrounding tokens to figure out if the field
is an email field
Tuesday, 17 September 2013
Hyperlink not opening in Iframe, instead opens in new tab
Hyperlink not opening in Iframe, instead opens in new tab
I have some hyperlinks on a left panel sidebar. On clicking any of them,
the respective page should open in an iframe present on the right. Now,
this is working fine for most of the links. But for some links and
unfortunately, the links i need to use, it opens correctly in the iframe
only for the first time of page load. After that, it keeps opening in a
new tab.
The console says "Unsafe JavaScript attempt to access frame with URL1 from
frame with URL2. Domains, protocols and ports don't match." But this
appears even in the cases when the links open up correctly in the iframe.
I am completely puzzled as to why this is happening. Help me out.
<a href= "some url" target="iframe_P"> </a>
<iframe src="random url" name="iframe_P" scrolling="auto"></iframe>
Also I have tried using id = "iframe_P". Doesn't work either.
I have some hyperlinks on a left panel sidebar. On clicking any of them,
the respective page should open in an iframe present on the right. Now,
this is working fine for most of the links. But for some links and
unfortunately, the links i need to use, it opens correctly in the iframe
only for the first time of page load. After that, it keeps opening in a
new tab.
The console says "Unsafe JavaScript attempt to access frame with URL1 from
frame with URL2. Domains, protocols and ports don't match." But this
appears even in the cases when the links open up correctly in the iframe.
I am completely puzzled as to why this is happening. Help me out.
<a href= "some url" target="iframe_P"> </a>
<iframe src="random url" name="iframe_P" scrolling="auto"></iframe>
Also I have tried using id = "iframe_P". Doesn't work either.
Saving images from website to folder using curl php
Saving images from website to folder using curl php
I am able to save images from a website using curl like so:
//$fullpath = "/images/".basename($img);
$fullpath = basename($img);
$ch = curl_init($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$rawData = curl_exec($ch);
curl_close($ch);
if(file_exists($fullpath)) {
unlink($fullpath);
}
$fp = fopen($fullpath, 'w+');
fwrite($fp, $rawData);
fclose($fp);
However, this will only save the image on the same folder in which I have
the php file that executes the save function is in. I'd like to save the
images to a specific folder. I've tried using $fullpath =
"/images/".basename($img); (the commented out first line of my function)
but this results to an error:
failed to open stream: No such file or directory
So my question is, how can I save the file on a specific folder in my
project? Another question I have is, how can I change the filename of the
image I save on the my folder? For example, I'd like to add the prefix
siteimg_ to the image's filename. How do I implement this?
I am able to save images from a website using curl like so:
//$fullpath = "/images/".basename($img);
$fullpath = basename($img);
$ch = curl_init($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$rawData = curl_exec($ch);
curl_close($ch);
if(file_exists($fullpath)) {
unlink($fullpath);
}
$fp = fopen($fullpath, 'w+');
fwrite($fp, $rawData);
fclose($fp);
However, this will only save the image on the same folder in which I have
the php file that executes the save function is in. I'd like to save the
images to a specific folder. I've tried using $fullpath =
"/images/".basename($img); (the commented out first line of my function)
but this results to an error:
failed to open stream: No such file or directory
So my question is, how can I save the file on a specific folder in my
project? Another question I have is, how can I change the filename of the
image I save on the my folder? For example, I'd like to add the prefix
siteimg_ to the image's filename. How do I implement this?
How to let the user input as many lines of input as they want until they input the "stop" word in Python?
How to let the user input as many lines of input as they want until they
input the "stop" word in Python?
Say that I'm asking the user to input lines from a book or whatever. I
don't know how many lines they will decide to input though. How would you
let them input as many lines as they want until they input a secret word,
"blueblue" for example. That's the code i've got so far.
while (blueblue == false):
line1 = input()
Help would be much appreciated.
input the "stop" word in Python?
Say that I'm asking the user to input lines from a book or whatever. I
don't know how many lines they will decide to input though. How would you
let them input as many lines as they want until they input a secret word,
"blueblue" for example. That's the code i've got so far.
while (blueblue == false):
line1 = input()
Help would be much appreciated.
Why does resque 1.25 not trigger before_fork or after_fork?
Why does resque 1.25 not trigger before_fork or after_fork?
I am using resque 1.25.0 but for some reason my before_fork does not get
called? Resque.before_first_hook gets called but before_fork does not.
Resque.before_first_fork do
puts 'running Resque.before_first_fork'
end
Resque.before_fork do |job|
puts 'running Resque.before_fork.'
end
I am using resque 1.25.0 but for some reason my before_fork does not get
called? Resque.before_first_hook gets called but before_fork does not.
Resque.before_first_fork do
puts 'running Resque.before_first_fork'
end
Resque.before_fork do |job|
puts 'running Resque.before_fork.'
end
How to group by and include zero sums
How to group by and include zero sums
I'm trying to write a query that returns sums of transactions within every
category the user has created in my application. My current query works
fine but it does not display a category if no transactions have been made
under that category yet. I want my query to display every category even if
the sum of everything is 0.
I looked up how to do it and was suggested to use a LEFT/RIGHT OUTER JOIN
but it doesn't do what I want.
I am accessing a Microsoft Access 2007 Database via Windows C#
Application. This is my current query:
SELECT Categories.CategoryName ,
SUM( Transactions.TransactionCredit ) as CreditSum ,
SUM( Transactions.TransactionDebit ) as DebitSum ,
SUM( Transactions.TransactionCredit ) -
SUM( Transactions.TransactionDebit ) as Difference ,
SUM( Transactions.TransactionDebit ) /
( SELECT SUM(TransactionDebit)
FROM Transactions
WHERE AccountID = {currentAccountId}
) as 'Percent of Total Debit'
FROM Categories
LEFT JOIN Transactions on Categories.CategoryName = Transactions.CategoryName
WHERE Transactions.AccountID = {currentAccountId}
AND TransactionDate >= {startDate}
AND TransactionDate <= {endDate}
GROUP BY Categories.CategoryName
I'm trying to write a query that returns sums of transactions within every
category the user has created in my application. My current query works
fine but it does not display a category if no transactions have been made
under that category yet. I want my query to display every category even if
the sum of everything is 0.
I looked up how to do it and was suggested to use a LEFT/RIGHT OUTER JOIN
but it doesn't do what I want.
I am accessing a Microsoft Access 2007 Database via Windows C#
Application. This is my current query:
SELECT Categories.CategoryName ,
SUM( Transactions.TransactionCredit ) as CreditSum ,
SUM( Transactions.TransactionDebit ) as DebitSum ,
SUM( Transactions.TransactionCredit ) -
SUM( Transactions.TransactionDebit ) as Difference ,
SUM( Transactions.TransactionDebit ) /
( SELECT SUM(TransactionDebit)
FROM Transactions
WHERE AccountID = {currentAccountId}
) as 'Percent of Total Debit'
FROM Categories
LEFT JOIN Transactions on Categories.CategoryName = Transactions.CategoryName
WHERE Transactions.AccountID = {currentAccountId}
AND TransactionDate >= {startDate}
AND TransactionDate <= {endDate}
GROUP BY Categories.CategoryName
Sunday, 15 September 2013
Relational Database Design for News, Events and Photographs
Relational Database Design for News, Events and Photographs
I have large amounts of historical data dating to 1965, to include
photographic collections, PDF files, various Microsoft documents, notes,
and journals. Material is being categorized and cross-referenced. I want
to develop a dynamic relational interactive database (proper term?) to
place these materials online for purposes of conducting ongoing research.
An example: Photographs (large collections) and various files might relate
to an event that took place in, say, 1980. I would then be able to access
all information related to that event, and also be able to filter that
relevant only to my search. Concerning allowing input by others, this
would be an option built-in for later consideration. My idea is to make
information readily available for anyone to research. Exactly how this can
best be accomplished is the problem I now face. I had considered FileMaker
Pro Advanced, but it seems there would be problems with system slowdown
when accessing large photographic files, and such files are a major
consideration for this project. So, I'm looking for software/database
suggestions. Perhaps a system already available that will allow changes
and used as a platform from which I can develop my project, one expected
to be long-term. I do not have expertise in php or MySQL, however, some of
this could be learned but I would need to cut the 'learning curve' due to
time limitations. I now use BlueHost for another website, and they have
both MySQL and PHP available. I don't know if this would be the way to go.
Your suggestions would certainty help to point me in the right approach.
Thanks.
I have large amounts of historical data dating to 1965, to include
photographic collections, PDF files, various Microsoft documents, notes,
and journals. Material is being categorized and cross-referenced. I want
to develop a dynamic relational interactive database (proper term?) to
place these materials online for purposes of conducting ongoing research.
An example: Photographs (large collections) and various files might relate
to an event that took place in, say, 1980. I would then be able to access
all information related to that event, and also be able to filter that
relevant only to my search. Concerning allowing input by others, this
would be an option built-in for later consideration. My idea is to make
information readily available for anyone to research. Exactly how this can
best be accomplished is the problem I now face. I had considered FileMaker
Pro Advanced, but it seems there would be problems with system slowdown
when accessing large photographic files, and such files are a major
consideration for this project. So, I'm looking for software/database
suggestions. Perhaps a system already available that will allow changes
and used as a platform from which I can develop my project, one expected
to be long-term. I do not have expertise in php or MySQL, however, some of
this could be learned but I would need to cut the 'learning curve' due to
time limitations. I now use BlueHost for another website, and they have
both MySQL and PHP available. I don't know if this would be the way to go.
Your suggestions would certainty help to point me in the right approach.
Thanks.
python read() and write() in large blocks / memory management
python read() and write() in large blocks / memory management
I'm writing some python code that splices together large files at various
points. I've done something similar in C where I allocated a 1MB char
array and used that as the read/write buffer. And it was very simple: read
1MB into the char array then write it out.
But with python I'm assuming it is different, each time I call read() with
size = 1M, it will allocate a 1M long character string. And hopefully when
the buffer goes out of scope it will we freed in the next gc pass.
Would python handle the allocation this way? If so, is the constant
allocation/deallocation cycle be computationally expensive?
Can I tell python to use the same block of memory just like in C? Or is
the python vm smart enough to do it itself?
I guess what I'm essentially aiming for is kinda like an implementation of
dd in python.
I'm writing some python code that splices together large files at various
points. I've done something similar in C where I allocated a 1MB char
array and used that as the read/write buffer. And it was very simple: read
1MB into the char array then write it out.
But with python I'm assuming it is different, each time I call read() with
size = 1M, it will allocate a 1M long character string. And hopefully when
the buffer goes out of scope it will we freed in the next gc pass.
Would python handle the allocation this way? If so, is the constant
allocation/deallocation cycle be computationally expensive?
Can I tell python to use the same block of memory just like in C? Or is
the python vm smart enough to do it itself?
I guess what I'm essentially aiming for is kinda like an implementation of
dd in python.
How to close window using [x] in corner without it freezing?
How to close window using [x] in corner without it freezing?
I want to click the [x] in the corner of the window and for it to shut the
whole application. Instead it is freezing up and not responding. Thanks
for any help.
import sys
#import and init pygame
import pygame
pygame.init()
#create the screen
window = pygame.display.set_mode((640, 480))
#draw a line - see http://www.pygame.org/docs/ref/draw.html for more
pygame.draw.line(window, (255, 255, 255), (0, 0), (30, 50))
#draw it to the screen
pygame.display.flip()
#input handling (somewhat boilerplate code):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
else:
print event
I'm used to java and so was wondering if there was a dispose and close
type action for the frame.
I want to click the [x] in the corner of the window and for it to shut the
whole application. Instead it is freezing up and not responding. Thanks
for any help.
import sys
#import and init pygame
import pygame
pygame.init()
#create the screen
window = pygame.display.set_mode((640, 480))
#draw a line - see http://www.pygame.org/docs/ref/draw.html for more
pygame.draw.line(window, (255, 255, 255), (0, 0), (30, 50))
#draw it to the screen
pygame.display.flip()
#input handling (somewhat boilerplate code):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
else:
print event
I'm used to java and so was wondering if there was a dispose and close
type action for the frame.
Convert string to smalldatetime before a database insert
Convert string to smalldatetime before a database insert
I have everything inserting fine until I try to insert a string
"09/21/3013" into the ArrivalDate column which is a smalldatetime. How do
I convert this so I can insert into the database? Thanks in advance!
Here's the code:
private void ExecuteInsert(string BookingName, string BookedBy)
{
string connString =
System.Configuration.ConfigurationManager.ConnectionStrings["CateringAuthorizationEntities"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string sql = "INSERT INTO tbBooking (BookingName, BookedBy,
ArrivalDate) VALUES "
+ " (@BookingName, @BookedBy, @ArrivalDate)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
//param[0] = new SqlParameter("@id", SqlDbType.Int, 20);
param[0] = new SqlParameter("@BookingName",
System.Data.SqlDbType.VarChar, 50);
param[1] = new SqlParameter("@BookedBy",
System.Data.SqlDbType.VarChar, 50);
param[2] = new SqlParameter("@ArrivalDate",
System.Data.SqlDbType.SmallDateTime);
param[0].Value = BookingName;
param[1].Value = BookedBy;
param[2].Value = ArrivalDate;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void BtnCatering_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//call the method to execute insert to the database
ExecuteInsert(BookingName.Text, BookedBy.Text);
Response.Write("Record was successfully added!");
}
}
I have everything inserting fine until I try to insert a string
"09/21/3013" into the ArrivalDate column which is a smalldatetime. How do
I convert this so I can insert into the database? Thanks in advance!
Here's the code:
private void ExecuteInsert(string BookingName, string BookedBy)
{
string connString =
System.Configuration.ConfigurationManager.ConnectionStrings["CateringAuthorizationEntities"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string sql = "INSERT INTO tbBooking (BookingName, BookedBy,
ArrivalDate) VALUES "
+ " (@BookingName, @BookedBy, @ArrivalDate)";
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] param = new SqlParameter[3];
//param[0] = new SqlParameter("@id", SqlDbType.Int, 20);
param[0] = new SqlParameter("@BookingName",
System.Data.SqlDbType.VarChar, 50);
param[1] = new SqlParameter("@BookedBy",
System.Data.SqlDbType.VarChar, 50);
param[2] = new SqlParameter("@ArrivalDate",
System.Data.SqlDbType.SmallDateTime);
param[0].Value = BookingName;
param[1].Value = BookedBy;
param[2].Value = ArrivalDate;
for (int i = 0; i < param.Length; i++)
{
cmd.Parameters.Add(param[i]);
}
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
}
protected void BtnCatering_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//call the method to execute insert to the database
ExecuteInsert(BookingName.Text, BookedBy.Text);
Response.Write("Record was successfully added!");
}
}
Is it possible to use an Integer to call methods and arrays dynamically?
Is it possible to use an Integer to call methods and arrays dynamically?
For example:
3 methods exist
"map1method,
map2method,
map3mehtod"
and I want to call the right one depending on what the integer 'activemap'
has currently stored in it.
I could do an If statement
"If (activemap == 1)
map1method;
elseif (activemap ==2)
..."
But is there a possible way of using the integer more efficiently?
Like a "map(activemap)method"
Also could I also call a specific array in a batch of them in the same
fashion.
This is all in java by the way.
For example:
3 methods exist
"map1method,
map2method,
map3mehtod"
and I want to call the right one depending on what the integer 'activemap'
has currently stored in it.
I could do an If statement
"If (activemap == 1)
map1method;
elseif (activemap ==2)
..."
But is there a possible way of using the integer more efficiently?
Like a "map(activemap)method"
Also could I also call a specific array in a batch of them in the same
fashion.
This is all in java by the way.
How to determine in Java script the height of a div is in Percentage or pixels
How to determine in Java script the height of a div is in Percentage or
pixels
Is there a way in javascript to determine wether the height of the Div is
in %
<div id="dvPercentage" style="height: 80%">
How do I get that the height of the div was given in Percentage.
pixels
Is there a way in javascript to determine wether the height of the Div is
in %
<div id="dvPercentage" style="height: 80%">
How do I get that the height of the div was given in Percentage.
How to echo html elements, inline
How to echo html elements, inline
every second item needs to be on right side of the page, but inline with
first item, so it would create 2x2 type grid of both echoed items.
I added some CSS like this .container{float:left; width:50%;} but it
didn't work.
if ($file6 % 2 == 1)
{
echo '<div id="container">
<div id="thumbnail">
<a href="/images/tirgus/'. $file .'"
title="'.cleanString($file).'" class="thickbox"><img
src="/images/tirgus/thumbs/'.$row['id'].'.jpeg" width="141"
height="74" alt="image" /></a>
</div>
<br>
<div id="info1"><sub>' .cleanString($file2).'</sub></div>
<br>
<div id="info2"><sub>Telefons: ' .cleanString($file3).
'</sub><br><sub>email: '.cleanString($file4).'</sub></div><br>
<div id="info3"><sub>Iepostoja:</sub> ' .cleanString($file5).
'</div><br>
</div><widgets><customization><css> <link rel="stylesheet"
href="template_faili/gallery.css"></css></customization></widgets>';
}
else if ($file6 % 2 == 0) {
echo '<div id="container2">
<div id="thumbnail2">
<a href="/images/tirgus/'. $file .'"
title="'.cleanString($file).'" class="thickbox"><img
src="/images/tirgus/thumbs/'.$row['id'].'.jpeg" width="141"
height="74" alt="image" /></a>
</div>
<br>
<div id="info1"><sub>' .cleanString($file2).'</sub></div>
<br>
<div id="info2"><sub>Telefons: ' .cleanString($file3).
'</sub><br><sub>email: '.cleanString($file4).'</sub></div><br>
<div id="info3"><sub>Iepostoja:</sub> ' .cleanString($file5).
'</div><br>
</div><widgets><customization><css> <link rel="stylesheet"
href="template_faili/gallery.css"></css></customization></widgets>';
}
}
every second item needs to be on right side of the page, but inline with
first item, so it would create 2x2 type grid of both echoed items.
I added some CSS like this .container{float:left; width:50%;} but it
didn't work.
if ($file6 % 2 == 1)
{
echo '<div id="container">
<div id="thumbnail">
<a href="/images/tirgus/'. $file .'"
title="'.cleanString($file).'" class="thickbox"><img
src="/images/tirgus/thumbs/'.$row['id'].'.jpeg" width="141"
height="74" alt="image" /></a>
</div>
<br>
<div id="info1"><sub>' .cleanString($file2).'</sub></div>
<br>
<div id="info2"><sub>Telefons: ' .cleanString($file3).
'</sub><br><sub>email: '.cleanString($file4).'</sub></div><br>
<div id="info3"><sub>Iepostoja:</sub> ' .cleanString($file5).
'</div><br>
</div><widgets><customization><css> <link rel="stylesheet"
href="template_faili/gallery.css"></css></customization></widgets>';
}
else if ($file6 % 2 == 0) {
echo '<div id="container2">
<div id="thumbnail2">
<a href="/images/tirgus/'. $file .'"
title="'.cleanString($file).'" class="thickbox"><img
src="/images/tirgus/thumbs/'.$row['id'].'.jpeg" width="141"
height="74" alt="image" /></a>
</div>
<br>
<div id="info1"><sub>' .cleanString($file2).'</sub></div>
<br>
<div id="info2"><sub>Telefons: ' .cleanString($file3).
'</sub><br><sub>email: '.cleanString($file4).'</sub></div><br>
<div id="info3"><sub>Iepostoja:</sub> ' .cleanString($file5).
'</div><br>
</div><widgets><customization><css> <link rel="stylesheet"
href="template_faili/gallery.css"></css></customization></widgets>';
}
}
Saturday, 14 September 2013
gcc error: expected expression before 'else'
gcc error: expected expression before 'else'
I'm wondering why such code generates following error while compiling:
1.c:11: error: expected expression before 'else'
code:
#include <stdio.h>
#define xprintk(...) while(0);
int main (void)
{
if (1)
xprintk("aaa\n");
else
xprintk("bbb\n");
return 0;
}
I'm wondering why such code generates following error while compiling:
1.c:11: error: expected expression before 'else'
code:
#include <stdio.h>
#define xprintk(...) while(0);
int main (void)
{
if (1)
xprintk("aaa\n");
else
xprintk("bbb\n");
return 0;
}
Create box 3d border (triangle) with CSS
Create box 3d border (triangle) with CSS
I want the create a box with border radius 2px. but top right corner is
will be like 3d Like on the picture here: http://i.imgur.com/5nSB0Pa.png
I want the create a box with border radius 2px. but top right corner is
will be like 3d Like on the picture here: http://i.imgur.com/5nSB0Pa.png
Is b^n = È(c^n) for all b=?iso-8859-1?Q?=2Cc_=3E_1=3F?=
Is b^n = È(c^n) for all b,c > 1?
I have been trying to find a solution where 0 < k_1*c^n <= b^n <= k_2*c^n,
but so far I've had no luck. From my understanding of the Wikipedia
article on time complexity all functions on the form a^n should have the
same asymptotic growth. Is this false?
I have been trying to find a solution where 0 < k_1*c^n <= b^n <= k_2*c^n,
but so far I've had no luck. From my understanding of the Wikipedia
article on time complexity all functions on the form a^n should have the
same asymptotic growth. Is this false?
Error when using SUM on a text value
Error when using SUM on a text value
When I run
SELECT SUM(CASE column1 WHEN 'sometext' THEN 1 ELSE 0 END)
FROM table1
I get the following error: "The data types text and varchar are
incompatible in the equal to operator." The column is datatype text so i
tried the following but got the same error. Any ideas?
SELECT SUM(CASE column1 WHEN CAST('sometext' AS VARCHAR (40)) THEN 1 ELSE
0 END)
FROM table1
When I run
SELECT SUM(CASE column1 WHEN 'sometext' THEN 1 ELSE 0 END)
FROM table1
I get the following error: "The data types text and varchar are
incompatible in the equal to operator." The column is datatype text so i
tried the following but got the same error. Any ideas?
SELECT SUM(CASE column1 WHEN CAST('sometext' AS VARCHAR (40)) THEN 1 ELSE
0 END)
FROM table1
sparse hstack and weird dtype conversion error
sparse hstack and weird dtype conversion error
In working with some text data, I'm trying to join an np array(from a
pandas series) to a csr matrix.
I've done the below.
#create a compatible sparse matrix from my np.array.
#sparse.csr_matrix(X['link'].values) returns array size (1,7395)
#transpose that array for (7395,1)
X = sparse.csr_matrix(X['link'].values.transpose)
#bodies is a sparse.csr_matrix with shape (7395, 20000)
bodies = sparse.hstack((bodies,X))
However, this line gives the error "no supported conversion for types:
(dtype('0'),) ". I'm not sure what this means? How do I get around it?
Thanks.
In working with some text data, I'm trying to join an np array(from a
pandas series) to a csr matrix.
I've done the below.
#create a compatible sparse matrix from my np.array.
#sparse.csr_matrix(X['link'].values) returns array size (1,7395)
#transpose that array for (7395,1)
X = sparse.csr_matrix(X['link'].values.transpose)
#bodies is a sparse.csr_matrix with shape (7395, 20000)
bodies = sparse.hstack((bodies,X))
However, this line gives the error "no supported conversion for types:
(dtype('0'),) ". I'm not sure what this means? How do I get around it?
Thanks.
MediaStore.Images.Media.getBitmap gets images only from local SD?
MediaStore.Images.Media.getBitmap gets images only from local SD?
I'm building an android app that can get images from the photos gallery.
here is my code, but it succeed on getting images from local SD only.
how can I adjust it to get ones from external SD?
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String action = intent.getAction();
Uri uri = null;
// if this is from the share menu
if (Intent.ACTION_SEND.equals(action)) {
if (extras.containsKey(Intent.EXTRA_STREAM))
{
try
{
// Get resource path from intent callee
uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
I have this uri:
content://media/external/images/media/27031
but my code fails here with no information (it just crashes), no log cat,
not console error.
try {
if (uri !=null)
{
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(this.getContentResolver(),
uri);
imageView.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
Log.e(this.getClass().getName(), e.toString());
}
at any rate, why dont I see any exception thrown? just a crash?
and why does the uri differ from the path I see after clicking photo ->
properties?
I'm building an android app that can get images from the photos gallery.
here is my code, but it succeed on getting images from local SD only.
how can I adjust it to get ones from external SD?
Intent intent = getIntent();
Bundle extras = intent.getExtras();
String action = intent.getAction();
Uri uri = null;
// if this is from the share menu
if (Intent.ACTION_SEND.equals(action)) {
if (extras.containsKey(Intent.EXTRA_STREAM))
{
try
{
// Get resource path from intent callee
uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
I have this uri:
content://media/external/images/media/27031
but my code fails here with no information (it just crashes), no log cat,
not console error.
try {
if (uri !=null)
{
Bitmap bitmap =
MediaStore.Images.Media.getBitmap(this.getContentResolver(),
uri);
imageView.setImageBitmap(bitmap);
}
} catch (IOException e) {
e.printStackTrace();
Log.e(this.getClass().getName(), e.toString());
}
at any rate, why dont I see any exception thrown? just a crash?
and why does the uri differ from the path I see after clicking photo ->
properties?
How to retrieve more than 100 results using Twitter4j
How to retrieve more than 100 results using Twitter4j
I'm using the Twitter4j library to retrieve tweets, but I'm not getting
nearly enough for my purposes. Currently, I'm getting that maximum of 100
from one page. How do I implement maxId and sinceId into the below code in
Processing in order to retrieve more than the 100 results from the Twitter
search API? I'm totally new to Processing (and programming in general), so
any bit of direction on this would be awesome! Thanks!
void setup() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("xxxx");
cb.setOAuthConsumerSecret("xxxx");
cb.setOAuthAccessToken("xxxx");
cb.setOAuthAccessTokenSecret("xxxx");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
Query query = new Query("#peace");
query.setCount(100);
try {
QueryResult result = twitter.search(query);
ArrayList tweets = (ArrayList) result.getTweets();
for (int i = 0; i < tweets.size(); i++) {
Status t = (Status) tweets.get(i);
GeoLocation loc = t.getGeoLocation();
if (loc!=null) {
tweets.get(i++);
String user = t.getUser().getScreenName();
String msg = t.getText();
Double lat = t.getGeoLocation().getLatitude();
Double lon = t.getGeoLocation().getLongitude();
println("USER: " + user + " wrote: " + msg + " located at " + lat
+ ", " + lon);
}
}
}
catch (TwitterException te) {
println("Couldn't connect: " + te);
};
}
void draw() {
}
I'm using the Twitter4j library to retrieve tweets, but I'm not getting
nearly enough for my purposes. Currently, I'm getting that maximum of 100
from one page. How do I implement maxId and sinceId into the below code in
Processing in order to retrieve more than the 100 results from the Twitter
search API? I'm totally new to Processing (and programming in general), so
any bit of direction on this would be awesome! Thanks!
void setup() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("xxxx");
cb.setOAuthConsumerSecret("xxxx");
cb.setOAuthAccessToken("xxxx");
cb.setOAuthAccessTokenSecret("xxxx");
Twitter twitter = new TwitterFactory(cb.build()).getInstance();
Query query = new Query("#peace");
query.setCount(100);
try {
QueryResult result = twitter.search(query);
ArrayList tweets = (ArrayList) result.getTweets();
for (int i = 0; i < tweets.size(); i++) {
Status t = (Status) tweets.get(i);
GeoLocation loc = t.getGeoLocation();
if (loc!=null) {
tweets.get(i++);
String user = t.getUser().getScreenName();
String msg = t.getText();
Double lat = t.getGeoLocation().getLatitude();
Double lon = t.getGeoLocation().getLongitude();
println("USER: " + user + " wrote: " + msg + " located at " + lat
+ ", " + lon);
}
}
}
catch (TwitterException te) {
println("Couldn't connect: " + te);
};
}
void draw() {
}
Friday, 13 September 2013
html, make page appear ready (no tab spinning wheel) while just waiting for images
html, make page appear ready (no tab spinning wheel) while just waiting
for images
I have a page that loads images from various sources. Occasionally these
images fail to load; perhaps the link has gone dead or whatever. That's
fine.
What bothers me is that the browser might take 6 seconds or even longer
(I've seen 20 seconds) before it decides that the image has failed to
load. During this time the spinning loading wheel in the Chrome tab keeps
going and going, making it seem like my page isn't ready.
I've switched my javascript loading from onload to $(document).ready() so
at least my page isn't inactive while it waits for the images to load. But
it might appear as though it is.
But is there some way to make my page appear "ready" (no spinning wheel)
when all it's doing is waiting for the image? Maybe another way to load
images? I currently use the img element with src. Or a way to make it give
up sooner? Does it really need 6 seconds to decide that an image link is
dead?
Not sure if this has a solution. It's a problem that I have seen on a lot
of websites, not just mine, but it drives me nuts. I'll often click the
stop-loading-x just to make it stop! I'd at least like for my own website
to not be like that.
for images
I have a page that loads images from various sources. Occasionally these
images fail to load; perhaps the link has gone dead or whatever. That's
fine.
What bothers me is that the browser might take 6 seconds or even longer
(I've seen 20 seconds) before it decides that the image has failed to
load. During this time the spinning loading wheel in the Chrome tab keeps
going and going, making it seem like my page isn't ready.
I've switched my javascript loading from onload to $(document).ready() so
at least my page isn't inactive while it waits for the images to load. But
it might appear as though it is.
But is there some way to make my page appear "ready" (no spinning wheel)
when all it's doing is waiting for the image? Maybe another way to load
images? I currently use the img element with src. Or a way to make it give
up sooner? Does it really need 6 seconds to decide that an image link is
dead?
Not sure if this has a solution. It's a problem that I have seen on a lot
of websites, not just mine, but it drives me nuts. I'll often click the
stop-loading-x just to make it stop! I'd at least like for my own website
to not be like that.
How do I make a batch file launch a certain part of another batch file
How do I make a batch file launch a certain part of another batch file
I'm making a .bat game and I'm putting in save files but I'm not sure how
to, what I want it to do basically is run a batch file, "Warrior", then go
to a certain part of the code-:Fight_1. I've looked everywhere but can't
find anything. I don't need all the code, I know how to start batch files
and that and I know the call command I just don't know how to call a
certain part of a batch file. Any help appreciated, thanks!
I'm making a .bat game and I'm putting in save files but I'm not sure how
to, what I want it to do basically is run a batch file, "Warrior", then go
to a certain part of the code-:Fight_1. I've looked everywhere but can't
find anything. I don't need all the code, I know how to start batch files
and that and I know the call command I just don't know how to call a
certain part of a batch file. Any help appreciated, thanks!
Silent creation of Virtual Machine via VBoxManage (virtualbox) succeeds while configuration still needs to be done manually
Silent creation of Virtual Machine via VBoxManage (virtualbox) succeeds
while configuration still needs to be done manually
Description
silent create virtual machine via VBoxManage.exe
Expected Result
VM silent created and configured
Actual Result
VM creation incomplete as configuration still needs to be done manually
while configuration still needs to be done manually
Description
silent create virtual machine via VBoxManage.exe
Expected Result
VM silent created and configured
Actual Result
VM creation incomplete as configuration still needs to be done manually
Sending/Recieving messages using MPI GPU
Sending/Recieving messages using MPI GPU
I have the simplest of MPI-GPU code. Trying to exchange messages of size 4
on two MPI processes using direct GPU-GPU communication. The code is below
#include <cstdlib>
#include <cstdio>
#include "cuda.h"
#include "cuda_runtime.h"
#include "mpi.h"
#define MESSAGE_SIZE 4
int main(int argc, char **argv)
{
MPI_Init(&argc,&argv);
int nprocs,proc_id;
MPI_Comm_rank(MPI_COMM_WORLD,&proc_id);
MPI_Comm_rank(MPI_COMM_WORLD,&nprocs);
double * send_message = new double[MESSAGE_SIZE];
double * recv_message = new double[MESSAGE_SIZE];
for( int i = 0 ; i < MESSAGE_SIZE ; i++ ){
send_message[i] = (double)rand()*(proc_id+1) / (double)(RAND_MAX - 1);
}
fprintf(stdout,"Proc:%d,SendMessage:%lf,%lf,%lf,%lf\n",proc_id,send_message[0],send_message[1],send_message[2],send_message[3]);
double* send_message_gpu;
double* recv_message_gpu;
cudaMalloc(&send_message_gpu,sizeof(double)*MESSAGE_SIZE);
cudaMemcpy(send_message_gpu,send_message,sizeof(double)*MESSAGE_SIZE,cudaMemcpyHostToDevice);
cudaMalloc(&recv_message_gpu,sizeof(double)*MESSAGE_SIZE);
MPI_Request mpi_send_request;
MPI_Status mpi_send_status,mpi_recv_status;
MPI_Isend(send_message_gpu,MESSAGE_SIZE,MPI_DOUBLE,nprocs-proc_id-1,0,MPI_COMM_WORLD,&mpi_send_request);
MPI_Recv(recv_message_gpu,MESSAGE_SIZE,MPI_DOUBLE,nprocs-proc_id-1,0,MPI_COMM_WORLD,&mpi_recv_status);
MPI_Wait(&mpi_send_request,&mpi_send_status);
cudaDeviceSynchronize();
cudaMemcpy(recv_message,recv_message_gpu,sizeof(double)*MESSAGE_SIZE,cudaMemcpyDeviceToHost);
fprintf(stdout,"Proc:%d,RecvMessage:%lf,%lf,%lf,%lf\n",proc_id,recv_message[0],recv_message[1],recv_message[2],recv_message[3]);
cudaFree(recv_message_gpu);
cudaFree(send_message_gpu);
delete[] send_message;
delete[] recv_message;
return 0;
}
But when i run srun -n 2 ./trial.x (compiled using nvcc cuda5.5 and
mvapich2-1.9), I get the following output
Proc:0,SendMessage:0.840188,0.394383,0.783099,0.798440
Proc:0,RecvMessage:0.000000,0.000000,0.000000,0.000000
Proc:1,SendMessage:1.680375,0.788766,1.566198,1.596880
Proc:1,RecvMessage:0.000000,0.000000,0.000000,0.000000
The message is not recieved. What am I doing wrong here?
I have the simplest of MPI-GPU code. Trying to exchange messages of size 4
on two MPI processes using direct GPU-GPU communication. The code is below
#include <cstdlib>
#include <cstdio>
#include "cuda.h"
#include "cuda_runtime.h"
#include "mpi.h"
#define MESSAGE_SIZE 4
int main(int argc, char **argv)
{
MPI_Init(&argc,&argv);
int nprocs,proc_id;
MPI_Comm_rank(MPI_COMM_WORLD,&proc_id);
MPI_Comm_rank(MPI_COMM_WORLD,&nprocs);
double * send_message = new double[MESSAGE_SIZE];
double * recv_message = new double[MESSAGE_SIZE];
for( int i = 0 ; i < MESSAGE_SIZE ; i++ ){
send_message[i] = (double)rand()*(proc_id+1) / (double)(RAND_MAX - 1);
}
fprintf(stdout,"Proc:%d,SendMessage:%lf,%lf,%lf,%lf\n",proc_id,send_message[0],send_message[1],send_message[2],send_message[3]);
double* send_message_gpu;
double* recv_message_gpu;
cudaMalloc(&send_message_gpu,sizeof(double)*MESSAGE_SIZE);
cudaMemcpy(send_message_gpu,send_message,sizeof(double)*MESSAGE_SIZE,cudaMemcpyHostToDevice);
cudaMalloc(&recv_message_gpu,sizeof(double)*MESSAGE_SIZE);
MPI_Request mpi_send_request;
MPI_Status mpi_send_status,mpi_recv_status;
MPI_Isend(send_message_gpu,MESSAGE_SIZE,MPI_DOUBLE,nprocs-proc_id-1,0,MPI_COMM_WORLD,&mpi_send_request);
MPI_Recv(recv_message_gpu,MESSAGE_SIZE,MPI_DOUBLE,nprocs-proc_id-1,0,MPI_COMM_WORLD,&mpi_recv_status);
MPI_Wait(&mpi_send_request,&mpi_send_status);
cudaDeviceSynchronize();
cudaMemcpy(recv_message,recv_message_gpu,sizeof(double)*MESSAGE_SIZE,cudaMemcpyDeviceToHost);
fprintf(stdout,"Proc:%d,RecvMessage:%lf,%lf,%lf,%lf\n",proc_id,recv_message[0],recv_message[1],recv_message[2],recv_message[3]);
cudaFree(recv_message_gpu);
cudaFree(send_message_gpu);
delete[] send_message;
delete[] recv_message;
return 0;
}
But when i run srun -n 2 ./trial.x (compiled using nvcc cuda5.5 and
mvapich2-1.9), I get the following output
Proc:0,SendMessage:0.840188,0.394383,0.783099,0.798440
Proc:0,RecvMessage:0.000000,0.000000,0.000000,0.000000
Proc:1,SendMessage:1.680375,0.788766,1.566198,1.596880
Proc:1,RecvMessage:0.000000,0.000000,0.000000,0.000000
The message is not recieved. What am I doing wrong here?
Android 2D Game With OpenGL
Android 2D Game With OpenGL
Recently I worked on a 2D Game using SurfaceView and I learned a lot about
game loops and everything. But now I want to make the same game using
OpenGL. I read that the GLSurfaceView is the class that would be relative
to what SurfaceView was. But I'm not sure about other things as:
Using SurfaceView, I used the Bitmap class to load a image resource that
would be lets say a character. And that bitmap would be a property of my
Character class. And for the gameloop I used a different Thread
I'm new to OpenGL so I'd like to know how to load image resources (do I
load them using the Bitmap class?), or what to use instead of a Thread for
the game loop?
Recently I worked on a 2D Game using SurfaceView and I learned a lot about
game loops and everything. But now I want to make the same game using
OpenGL. I read that the GLSurfaceView is the class that would be relative
to what SurfaceView was. But I'm not sure about other things as:
Using SurfaceView, I used the Bitmap class to load a image resource that
would be lets say a character. And that bitmap would be a property of my
Character class. And for the gameloop I used a different Thread
I'm new to OpenGL so I'd like to know how to load image resources (do I
load them using the Bitmap class?), or what to use instead of a Thread for
the game loop?
How to use dojox tools in DoJo?
How to use dojox tools in DoJo?
I am now learning Dojo. So I want to build my first demo by how to use
gauges in Dojo. I downloaded the zip package and build an asp.net web
project. then all the resources from Dojo package are imported to this
project.
Because I saw the demo from DoJo website:
http://demos.dojotoolkit.org/demos/gauges/demo.html, So I want to copy
this demo in my local computer with existing DoJo resources. HTML code
below:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="DojoDaemon.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dojo Circular Gauge Test Daemon</title>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<script src="Scripts/dojo-release-1.9.1/dojo/dojo.js"
type="text/javascript" data-dojo-config="async:true"></script>
<script
src="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/CircularLinearGauge.js"
type="text/javascript" data-dojo-config="async:true"></script>
<script
src="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/HorizontalLinearGauge.js"
type="text/javascript" data-dojo-config="async:true"></script>
<script
src="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/SemiCircularLinearGauge.js"
type="text/javascript" data-dojo-config="async:true"></script>
</head>
<body>
<form runat="server" id="form1">
<h2 align="center" style="color:white;">Predefined Glossy Gauges</h2>
<table style="height:100%; width:100%">
<tr>
<td align="center">
<div id="CircularGauge" background="{color:'rgba(0,0,0,0)'}"
useTooltip="false"
data-dojo-type="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/CircularLinearGauge"
style="width:200px;height:200px" value="20"></div>
</td>
<td align='center'>
<div id="CircularGauge2" background="{color:'rgba(0,0,0,0)'}"
useTooltip="false"
data-dojo-type="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/SemiCircularLinearGauge"
value="10" style="width:250px;height:200px"></div>
</td>
</tr>
<tr>
<td valign="middle" align="center" colspan="2">
<div id="HGauge3" style="margin:30px 0px 0px
0px;width:400px;height:60px" useTooltip="false"
background="{color:'rgba(0,0,0,0)'}"
data-dojo-type="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/HorizontalLinearGauge"
value="20"></div>
</td>
</tr>
</table>
</form>
</body>
</html>
Above is the code I use, I have searched a lot of examples, but got
nothing because no one article give me the detailed steps to teach me how
to use the resources in dojox folder. resources I found like :
http://dojotoolkit.org/api/dojox/dgauges/CircularGauge
http://dmandrioli.github.io/dgauges/dojox/dgauges/CircularGauge.html Would
anyone help me if familar with this? thank you ver much.
I am now learning Dojo. So I want to build my first demo by how to use
gauges in Dojo. I downloaded the zip package and build an asp.net web
project. then all the resources from Dojo package are imported to this
project.
Because I saw the demo from DoJo website:
http://demos.dojotoolkit.org/demos/gauges/demo.html, So I want to copy
this demo in my local computer with existing DoJo resources. HTML code
below:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="DojoDaemon.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Dojo Circular Gauge Test Daemon</title>
<link href="Styles/Site.css" rel="stylesheet" type="text/css" />
<script src="Scripts/dojo-release-1.9.1/dojo/dojo.js"
type="text/javascript" data-dojo-config="async:true"></script>
<script
src="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/CircularLinearGauge.js"
type="text/javascript" data-dojo-config="async:true"></script>
<script
src="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/HorizontalLinearGauge.js"
type="text/javascript" data-dojo-config="async:true"></script>
<script
src="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/SemiCircularLinearGauge.js"
type="text/javascript" data-dojo-config="async:true"></script>
</head>
<body>
<form runat="server" id="form1">
<h2 align="center" style="color:white;">Predefined Glossy Gauges</h2>
<table style="height:100%; width:100%">
<tr>
<td align="center">
<div id="CircularGauge" background="{color:'rgba(0,0,0,0)'}"
useTooltip="false"
data-dojo-type="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/CircularLinearGauge"
style="width:200px;height:200px" value="20"></div>
</td>
<td align='center'>
<div id="CircularGauge2" background="{color:'rgba(0,0,0,0)'}"
useTooltip="false"
data-dojo-type="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/SemiCircularLinearGauge"
value="10" style="width:250px;height:200px"></div>
</td>
</tr>
<tr>
<td valign="middle" align="center" colspan="2">
<div id="HGauge3" style="margin:30px 0px 0px
0px;width:400px;height:60px" useTooltip="false"
background="{color:'rgba(0,0,0,0)'}"
data-dojo-type="Scripts/dojo-release-1.9.1/dojox/dgauges/components/black/HorizontalLinearGauge"
value="20"></div>
</td>
</tr>
</table>
</form>
</body>
</html>
Above is the code I use, I have searched a lot of examples, but got
nothing because no one article give me the detailed steps to teach me how
to use the resources in dojox folder. resources I found like :
http://dojotoolkit.org/api/dojox/dgauges/CircularGauge
http://dmandrioli.github.io/dgauges/dojox/dgauges/CircularGauge.html Would
anyone help me if familar with this? thank you ver much.
Thursday, 12 September 2013
Need help in printing of a file in different format in C?
Need help in printing of a file in different format in C?
I am working on a project where I have to capture statistics of uuid
occurrences for ALIVE/SEARCH/BYEBYE (it can be all 3, combinations of 2
each, or one alone) in a dynamically populated file in run time.
I am able to print all 3 combinations, but not in combination of 1 or 2 e.g.
If my input.txt is like this :
uuid:22314754-a597-490b-8a93-02cfae01036b ALIVE 16
uuid:22314754-a597-490b-8a93-02cfae01036b BYEBYE 8
uuid:22314754-a597-490b-8a93-02cfae01036b SEARCH 8
uuid:50e65653-7525-485d-83bf-d293558c4264 ALIVE 32
uuid:50e65653-7525-485d-83bf-d293558c4264 BYEBYE 8
uuid:50e65653-7525-485d-83bf-d293558c4264 SEARCH 132
uuid:55076f6e-6b79-4d65-6497-180373763bc1 ALIVE 113
uuid:55076f6e-6b79-4d65-6497-180373763bc1 BYEBYE 112
uuid:55076f6e-6b79-4d65-6497-180373763bc1 SEARCH 111
uuid:T0100203354 ALIVE 1
uuid:T0100203354 BYEBYE 2
uuid:T0100203354 SEARCH 3
My code :
#include<stdio.h>
#include<string.h>
struct uid
{
char uid_val[100];
char state[100];
int temp_count;
int alive_count;
int search_count;
int bye_count;
} UID[100];
int main()
{
char str[100];
int i = 0;
int line = 0;
char temp_val[100] = "waseem";
FILE *fp1 = fopen("input.txt","r");
FILE *fp2=fopen("output.txt","w");
printf("init value is %s \n",temp_val);
while(!feof(fp1))
{
fscanf(fp1,"%s %s
%d",UID[i].uid_val,UID[i].state,&UID[i].temp_count);
int ret = 0;
ret=strcmp(UID[i].uid_val,temp_val);
if (ret!=0)
{
printf("new UID_val is %s\n",UID[i].uid_val);
// i++;
}
else
{
}
temp_val[0] = '\0';
strcpy(temp_val,UID[i].uid_val);
// printf("value is %s and %s and ret is
%d\n",temp_val,UID[i].uid_val,ret);
if(strcmp(UID[i].state,"ALIVE")==0)
{
UID[i].alive_count = UID[i].temp_count;
}
else if(strcmp(UID[i].state,"BYEBYE")==0)
{
UID[i].search_count = UID[i].temp_count;
}
else
{
UID[i].bye_count = UID[i].temp_count;
}
//printf("UID is %s State is %s Count is
%d\n",UID[i].uid_val,UID[i].state,UID[i].alive_count);
line++;
if(line%3 == 0)
{
i++;
}
}
//printf("value of is %d and lines is %d\n",i,line);
int n = 0;
//fp2=fopen("output.txt","w");
if (fp2==NULL)
{
printf("cant output to file\n");
}
else
{
fprintf(fp2,"Device ID\t\t\t\t\tALIVE\tBYEBYE\tSEARCH\n");
for(n = 0;n < i;n++)
{
fprintf(fp2,"%s\t%d\t%d\t%d\n",UID[n].uid_val,UID[n].alive_count,UID[n].search_count,UID[n].bye_count);
}
}
// for(n = 0;n < i;n++)
{
// printf("%s %d %d
%d\n",UID[n].uid_val,UID[n].alive_count,UID[n].search_count,UID[n].bye_count);
// }
fclose(fp1);
fclose (fp2);
return 0;
}
}
Gives the following output :(output.txt)
Device ID ALIVE BYEBYE SEARCH
uuid:22314754-a597-490b-8a93-02cfae01036b 16 8 8
uuid:50e65653-7525-485d-83bf-d293558c4264 32 8 132
uuid:55076f6e-6b79-4d65-6497-180373763bc1 113 112 111
uuid:T0100203354 1 2 3
I want to generalize the code such that uuid occurrence does not have to
be all 3 (ALIVE/SEARCH/BYEBYE), the occurrences can be any combination and
code should work. e.g my code crashes when input.txt contains the
following:
uuid:22314754-a597-490b-8a93-02cfae01036b BYEBYE 8
uuid:22314754-a597-490b-8a93-02cfae01036b SEARCH 8
uuid:50e65653-7525-485d-83bf-d293558c4264 ALIVE 32
uuid:50e65653-7525-485d-83bf-d293558c4264 BYEBYE 8
uuid:55076f6e-6b79-4d65-6497-180373763bc1 ALIVE 113
uuid:55076f6e-6b79-4d65-6497-180373763bc1 BYEBYE 112
uuid:55076f6e-6b79-4d65-6497-180373763bc1 SEARCH 111
uuid:T0100203354 BYEBYE 2
I am using ubuntu for gcc/g+ compiler.
I am working on a project where I have to capture statistics of uuid
occurrences for ALIVE/SEARCH/BYEBYE (it can be all 3, combinations of 2
each, or one alone) in a dynamically populated file in run time.
I am able to print all 3 combinations, but not in combination of 1 or 2 e.g.
If my input.txt is like this :
uuid:22314754-a597-490b-8a93-02cfae01036b ALIVE 16
uuid:22314754-a597-490b-8a93-02cfae01036b BYEBYE 8
uuid:22314754-a597-490b-8a93-02cfae01036b SEARCH 8
uuid:50e65653-7525-485d-83bf-d293558c4264 ALIVE 32
uuid:50e65653-7525-485d-83bf-d293558c4264 BYEBYE 8
uuid:50e65653-7525-485d-83bf-d293558c4264 SEARCH 132
uuid:55076f6e-6b79-4d65-6497-180373763bc1 ALIVE 113
uuid:55076f6e-6b79-4d65-6497-180373763bc1 BYEBYE 112
uuid:55076f6e-6b79-4d65-6497-180373763bc1 SEARCH 111
uuid:T0100203354 ALIVE 1
uuid:T0100203354 BYEBYE 2
uuid:T0100203354 SEARCH 3
My code :
#include<stdio.h>
#include<string.h>
struct uid
{
char uid_val[100];
char state[100];
int temp_count;
int alive_count;
int search_count;
int bye_count;
} UID[100];
int main()
{
char str[100];
int i = 0;
int line = 0;
char temp_val[100] = "waseem";
FILE *fp1 = fopen("input.txt","r");
FILE *fp2=fopen("output.txt","w");
printf("init value is %s \n",temp_val);
while(!feof(fp1))
{
fscanf(fp1,"%s %s
%d",UID[i].uid_val,UID[i].state,&UID[i].temp_count);
int ret = 0;
ret=strcmp(UID[i].uid_val,temp_val);
if (ret!=0)
{
printf("new UID_val is %s\n",UID[i].uid_val);
// i++;
}
else
{
}
temp_val[0] = '\0';
strcpy(temp_val,UID[i].uid_val);
// printf("value is %s and %s and ret is
%d\n",temp_val,UID[i].uid_val,ret);
if(strcmp(UID[i].state,"ALIVE")==0)
{
UID[i].alive_count = UID[i].temp_count;
}
else if(strcmp(UID[i].state,"BYEBYE")==0)
{
UID[i].search_count = UID[i].temp_count;
}
else
{
UID[i].bye_count = UID[i].temp_count;
}
//printf("UID is %s State is %s Count is
%d\n",UID[i].uid_val,UID[i].state,UID[i].alive_count);
line++;
if(line%3 == 0)
{
i++;
}
}
//printf("value of is %d and lines is %d\n",i,line);
int n = 0;
//fp2=fopen("output.txt","w");
if (fp2==NULL)
{
printf("cant output to file\n");
}
else
{
fprintf(fp2,"Device ID\t\t\t\t\tALIVE\tBYEBYE\tSEARCH\n");
for(n = 0;n < i;n++)
{
fprintf(fp2,"%s\t%d\t%d\t%d\n",UID[n].uid_val,UID[n].alive_count,UID[n].search_count,UID[n].bye_count);
}
}
// for(n = 0;n < i;n++)
{
// printf("%s %d %d
%d\n",UID[n].uid_val,UID[n].alive_count,UID[n].search_count,UID[n].bye_count);
// }
fclose(fp1);
fclose (fp2);
return 0;
}
}
Gives the following output :(output.txt)
Device ID ALIVE BYEBYE SEARCH
uuid:22314754-a597-490b-8a93-02cfae01036b 16 8 8
uuid:50e65653-7525-485d-83bf-d293558c4264 32 8 132
uuid:55076f6e-6b79-4d65-6497-180373763bc1 113 112 111
uuid:T0100203354 1 2 3
I want to generalize the code such that uuid occurrence does not have to
be all 3 (ALIVE/SEARCH/BYEBYE), the occurrences can be any combination and
code should work. e.g my code crashes when input.txt contains the
following:
uuid:22314754-a597-490b-8a93-02cfae01036b BYEBYE 8
uuid:22314754-a597-490b-8a93-02cfae01036b SEARCH 8
uuid:50e65653-7525-485d-83bf-d293558c4264 ALIVE 32
uuid:50e65653-7525-485d-83bf-d293558c4264 BYEBYE 8
uuid:55076f6e-6b79-4d65-6497-180373763bc1 ALIVE 113
uuid:55076f6e-6b79-4d65-6497-180373763bc1 BYEBYE 112
uuid:55076f6e-6b79-4d65-6497-180373763bc1 SEARCH 111
uuid:T0100203354 BYEBYE 2
I am using ubuntu for gcc/g+ compiler.
Webpage Live Streaming
Webpage Live Streaming
Okay, So... My brother recommended that I do kind of like Call of Duty's
live stream for a new website we have in mind. Eh, I understand this idea
might be like... He wants to stream Call of Duty's live feed?
No, like... Lets say someone is using their mobile device. They can visit
our website and click "Stream" and then their mobile device will prompt
their video recorder. Their video recorder typically acts as a normal
"Record" video thus streaming live feed to our website whistle saving the
clip to their mobile.
If you don't understand, please let me know. I'll be more the happy to
explain it further.
Note: I'm generally a PHP, HTML, CSS website developer.
How do I go about completing this goal?
Thanks in advance!
Okay, So... My brother recommended that I do kind of like Call of Duty's
live stream for a new website we have in mind. Eh, I understand this idea
might be like... He wants to stream Call of Duty's live feed?
No, like... Lets say someone is using their mobile device. They can visit
our website and click "Stream" and then their mobile device will prompt
their video recorder. Their video recorder typically acts as a normal
"Record" video thus streaming live feed to our website whistle saving the
clip to their mobile.
If you don't understand, please let me know. I'll be more the happy to
explain it further.
Note: I'm generally a PHP, HTML, CSS website developer.
How do I go about completing this goal?
Thanks in advance!
Application using a DLL, but Visual Studio 2010 not showing it in Modules window
Application using a DLL, but Visual Studio 2010 not showing it in Modules
window
I feel like this is a stupid question, but I can't seem to figure out the
answer. I've currently got a C++ application that's loading & utilizing a
DLL (I compiled both the application & the DLL with VS 2010). I'm positive
it's using the DLL, because a) if I rename the DLL, I get a not found
exception, and b) it's displaying output that only comes from (and I can
change it to see the output change) inside the DLL.
My problem is that in Visual Studio's Modules window while debugging, the
DLL does not appear to be loaded. Because of this, obviously its got no
symbols and I can't set breakpoints... But this doesn't make any sense to
me as it's clearly using the DLL.
I've seen several other similar questions, and the answer has generally
been too look at whether the code is native, managed, or mixed, and set
the "Attach to Process" field accordingly. I've tried all the options
there, and made sure my Debugger Type is set to "Mixed" (though I've tried
it with Native & Managed as well, just to verify none of these solve the
issue).
Does anyone have any suggestions?
Thanks in advance!
window
I feel like this is a stupid question, but I can't seem to figure out the
answer. I've currently got a C++ application that's loading & utilizing a
DLL (I compiled both the application & the DLL with VS 2010). I'm positive
it's using the DLL, because a) if I rename the DLL, I get a not found
exception, and b) it's displaying output that only comes from (and I can
change it to see the output change) inside the DLL.
My problem is that in Visual Studio's Modules window while debugging, the
DLL does not appear to be loaded. Because of this, obviously its got no
symbols and I can't set breakpoints... But this doesn't make any sense to
me as it's clearly using the DLL.
I've seen several other similar questions, and the answer has generally
been too look at whether the code is native, managed, or mixed, and set
the "Attach to Process" field accordingly. I've tried all the options
there, and made sure my Debugger Type is set to "Mixed" (though I've tried
it with Native & Managed as well, just to verify none of these solve the
issue).
Does anyone have any suggestions?
Thanks in advance!
Sending too much data over websocket?
Sending too much data over websocket?
I think I'm having issues sending too much data over a socket.io
connection. I'm subscribing to a RabbitMQ exchange and sending data
messages to the client for graphing real-time:
q.subscribe({routingKeyInPayload:true},function (message) {
socket.emit('message', {
key: message._routingKey,
//msg: decodeURIComponent(message.data),
client: qName,
ts: new Date()
});
console.log('broadcasting: ' + message._routingKey);
});
You can see that "msg" is commented out. When I comment this out, I am
able to send ~100-200 messages/second (~800/s peak). However, when the
"msg" is included in the JSON data, I get the following error:
events.js:72
throw er; // Unhandled 'error' event
I'm not sure what the error actually is or how to handle it. Any advice
would be appreciated.
EDIT: A typical message looks like (I've sanitized the userid's just in
case):
{"key":"message.1","client":"7raQ6vpCO-PZ5ZTWQVD9","ts":"2013-09-12T22:19:06.677Z"}]}
{"fromuserid": 62XXXX34, "deleted": 0, "messagetype": 1, "datetime":
1379024283000, "touserid": 12XXXX41, "message": "Bored lol, really bored
lol", "id": 27963323859}
I think I'm having issues sending too much data over a socket.io
connection. I'm subscribing to a RabbitMQ exchange and sending data
messages to the client for graphing real-time:
q.subscribe({routingKeyInPayload:true},function (message) {
socket.emit('message', {
key: message._routingKey,
//msg: decodeURIComponent(message.data),
client: qName,
ts: new Date()
});
console.log('broadcasting: ' + message._routingKey);
});
You can see that "msg" is commented out. When I comment this out, I am
able to send ~100-200 messages/second (~800/s peak). However, when the
"msg" is included in the JSON data, I get the following error:
events.js:72
throw er; // Unhandled 'error' event
I'm not sure what the error actually is or how to handle it. Any advice
would be appreciated.
EDIT: A typical message looks like (I've sanitized the userid's just in
case):
{"key":"message.1","client":"7raQ6vpCO-PZ5ZTWQVD9","ts":"2013-09-12T22:19:06.677Z"}]}
{"fromuserid": 62XXXX34, "deleted": 0, "messagetype": 1, "datetime":
1379024283000, "touserid": 12XXXX41, "message": "Bored lol, really bored
lol", "id": 27963323859}
Odd duplicate symbol error in C
Odd duplicate symbol error in C
Ok so i have a project, and i have some helper functions which need to be
shared in various other files. call it Helper.c /.h , with the
corresponding compilation flag to avoid multiple inclusion (#ifndef
SymbolName #define Symbolname blah blahblah
Ok so i have a project, and i have some helper functions which need to be
shared in various other files. call it Helper.c /.h , with the
corresponding compilation flag to avoid multiple inclusion (#ifndef
SymbolName #define Symbolname blah blahblah
Server receives request for google.com
Server receives request for google.com
I was looking through my site's error logs and noticed an unusual
occurrence. I found exceptions where the requested URL was
http://www.google.com/intl/zh-CN. My routing engine tried to route it to
/intl/zh-CN, which failed with a 404, since for my site it is an invalid
path. My question is.. how did I even get a request where the requested
domain is Google? I would think that any request with Google's domain
would get resolved to their IP by DNS, not my site's. It's happened three
times in the past few days, all from different IP addresses and I've been
unable to find anything by searching. Any insight would be appreciated.
I was looking through my site's error logs and noticed an unusual
occurrence. I found exceptions where the requested URL was
http://www.google.com/intl/zh-CN. My routing engine tried to route it to
/intl/zh-CN, which failed with a 404, since for my site it is an invalid
path. My question is.. how did I even get a request where the requested
domain is Google? I would think that any request with Google's domain
would get resolved to their IP by DNS, not my site's. It's happened three
times in the past few days, all from different IP addresses and I've been
unable to find anything by searching. Any insight would be appreciated.
Wednesday, 11 September 2013
cant retrieve data from select box while using its id
cant retrieve data from select box while using its id
this is my select tag but in the grid while editing and adding i cannot
retrieve country value only code value appears what shall i do nw?
<option value="" >select country</option>
<?php $select_query= mysql_query("Select * from country");
while($select_query_array = mysql_fetch_array($select_query))
{
?>
<option value="<?php echo $select_query_array['code'];?>" <?php
if($_POST['country']==$select_query_array['code']) { ?>
selected="selected" <?php } ?> > <?php echo
$select_query_array['country']; ?> </option>
<?php } ?>
</select>
this is my select tag but in the grid while editing and adding i cannot
retrieve country value only code value appears what shall i do nw?
<option value="" >select country</option>
<?php $select_query= mysql_query("Select * from country");
while($select_query_array = mysql_fetch_array($select_query))
{
?>
<option value="<?php echo $select_query_array['code'];?>" <?php
if($_POST['country']==$select_query_array['code']) { ?>
selected="selected" <?php } ?> > <?php echo
$select_query_array['country']; ?> </option>
<?php } ?>
</select>
when i gdb a process on a remote server, the ssh disconnect, how could i recover the ssh session work?
when i gdb a process on a remote server, the ssh disconnect, how could i
recover the ssh session work?
When I gdb a process on a remote server, the ssh disconnect.
How could I recover the old session's work when I ssh the server next time?
I try to kill the gdb process, but it causes the real process over.
thanks.
recover the ssh session work?
When I gdb a process on a remote server, the ssh disconnect.
How could I recover the old session's work when I ssh the server next time?
I try to kill the gdb process, but it causes the real process over.
thanks.
Is there another way to do this case statement?
Is there another way to do this case statement?
I have a case statement which evaluates an integer (result of a function)
for a result code, like this:
R:= DoSomething;
case R of
0: begin
//Success
end;
-MAXINT..-1: begin
//Failure
end;
end;
If it's a failure, it returns a negative number representing an error
code. DoSomething is just any function which returns an integer as a
response code (or error code, being a negative). If it is an error, it
gets passed on to another error handler. If it's a success, it gets passed
on to a success handler (continue, etc.). Positive values will be handled
by various specific handlers.
I was wondering if there's another way to write -MAXINT..-1. Something
more along the lines of "Anything -1 and under". I tried <=-1 but the
compiler didn't like that too much.
Is there a way to do this in a case statement?
I have a case statement which evaluates an integer (result of a function)
for a result code, like this:
R:= DoSomething;
case R of
0: begin
//Success
end;
-MAXINT..-1: begin
//Failure
end;
end;
If it's a failure, it returns a negative number representing an error
code. DoSomething is just any function which returns an integer as a
response code (or error code, being a negative). If it is an error, it
gets passed on to another error handler. If it's a success, it gets passed
on to a success handler (continue, etc.). Positive values will be handled
by various specific handlers.
I was wondering if there's another way to write -MAXINT..-1. Something
more along the lines of "Anything -1 and under". I tried <=-1 but the
compiler didn't like that too much.
Is there a way to do this in a case statement?
Javascript singleton inheritance
Javascript singleton inheritance
I would like to keep a single parent class. all clild classes that inherit
the parent class will be able to share the same parent class object. How
that can be achieved?
var ParentClass = function(){
this.a = null;
}
ParentClass.prototype.setA = function(inp){
this.a = inp;
}
ParentClass.prototype.getA = function(){
console.log("get a "+this.a);
}
// Clild Class
var ClassB = function(){}
ClassB.prototype = Object.create(ParentClass.prototype);
var b = new ClassB();
b.setA(10);
b.getA(); //it will return 10
//Another clild Class
var ClassC = function(){}
ClassC.prototype = Object.create(ParentClass.prototype);
var c = new ClassC();
c.getA(); //I want 10 here.
I understand, as for the second clild class the parent class is
instantiating again that is why I can't access the old object. How I can
achieve this singleton inheritance in Javascript? Any idea?
I would like to keep a single parent class. all clild classes that inherit
the parent class will be able to share the same parent class object. How
that can be achieved?
var ParentClass = function(){
this.a = null;
}
ParentClass.prototype.setA = function(inp){
this.a = inp;
}
ParentClass.prototype.getA = function(){
console.log("get a "+this.a);
}
// Clild Class
var ClassB = function(){}
ClassB.prototype = Object.create(ParentClass.prototype);
var b = new ClassB();
b.setA(10);
b.getA(); //it will return 10
//Another clild Class
var ClassC = function(){}
ClassC.prototype = Object.create(ParentClass.prototype);
var c = new ClassC();
c.getA(); //I want 10 here.
I understand, as for the second clild class the parent class is
instantiating again that is why I can't access the old object. How I can
achieve this singleton inheritance in Javascript? Any idea?
Scaleability of Remote EJB vs Local EJB
Scaleability of Remote EJB vs Local EJB
I have been trying to decide between a Local and Remote EJB for a Data
Access Layer. Through a lot of research, it seems like the general
consensus is that if I want scalability, I should use a Remote EJB.
What does that mean though? I can not find anything that explicitly shows
why Remote EJB can scale and Local can not.
I have been trying to decide between a Local and Remote EJB for a Data
Access Layer. Through a lot of research, it seems like the general
consensus is that if I want scalability, I should use a Remote EJB.
What does that mean though? I can not find anything that explicitly shows
why Remote EJB can scale and Local can not.
Android YouTube API access player from onClickListener
Android YouTube API access player from onClickListener
I'm following this tutorial to set up a custom youtube player via
youtubeapi:
http://www.techrepublic.com/blog/android-app-builder/using-googles-youtube-api-in-your-android-apps/
Here's the code for loading pre-set youtube video:
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
static private final String DEVELOPER_KEY = "mykey";
static private final String VIDEO = "Yc8YrVc47TI";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubeView = (YouTubePlayerView)
findViewById(R.id.youtube_view);
youTubeView.initialize(DEVELOPER_KEY, this);
}
@Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult error) {
Toast.makeText(this, "Oh no! "+error.toString(),
Toast.LENGTH_LONG).show();
}
@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer
player, boolean wasRestored) {
player.loadVideo(VIDEO);
}
}
Now I'm trying to load different youtube video by clicking a button. So I
setup onClickListener for my button1 and trying to access the youtube
player, but It wont work.
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
static private final String DEVELOPER_KEY = "mykey";
static private final String VIDEO = "Yc8YrVc47TI";
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubeView = (YouTubePlayerView)
findViewById(R.id.youtube_view);
youTubeView.initialize(DEVELOPER_KEY, this);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
youTubeView.loadVideo("Erd2k6EKxCQ");
}
});
}
@Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult error) {
Toast.makeText(this, "Oh no! "+error.toString(),
Toast.LENGTH_LONG).show();
}
@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer
player, boolean wasRestored) {
player.loadVideo(VIDEO);
}
}
How do I load a specific video from button1's onClickListener to
YouTubePlayer player.component?
I'm following this tutorial to set up a custom youtube player via
youtubeapi:
http://www.techrepublic.com/blog/android-app-builder/using-googles-youtube-api-in-your-android-apps/
Here's the code for loading pre-set youtube video:
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
static private final String DEVELOPER_KEY = "mykey";
static private final String VIDEO = "Yc8YrVc47TI";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubeView = (YouTubePlayerView)
findViewById(R.id.youtube_view);
youTubeView.initialize(DEVELOPER_KEY, this);
}
@Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult error) {
Toast.makeText(this, "Oh no! "+error.toString(),
Toast.LENGTH_LONG).show();
}
@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer
player, boolean wasRestored) {
player.loadVideo(VIDEO);
}
}
Now I'm trying to load different youtube video by clicking a button. So I
setup onClickListener for my button1 and trying to access the youtube
player, but It wont work.
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
static private final String DEVELOPER_KEY = "mykey";
static private final String VIDEO = "Yc8YrVc47TI";
Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubeView = (YouTubePlayerView)
findViewById(R.id.youtube_view);
youTubeView.initialize(DEVELOPER_KEY, this);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
youTubeView.loadVideo("Erd2k6EKxCQ");
}
});
}
@Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult error) {
Toast.makeText(this, "Oh no! "+error.toString(),
Toast.LENGTH_LONG).show();
}
@Override
public void onInitializationSuccess(Provider provider, YouTubePlayer
player, boolean wasRestored) {
player.loadVideo(VIDEO);
}
}
How do I load a specific video from button1's onClickListener to
YouTubePlayer player.component?
execute only whitelisted python scripts
execute only whitelisted python scripts
I want to use python on my machine but I want to restrict script
execution. I want to maintain a file (or in memory data-structure) that
will contain the list of python scripts that may be executed on the
machine; the scripts that are not in this list shouldn't be allowed to get
executed.
Is there any way or tool to achieve this in python?
I want to use python on my machine but I want to restrict script
execution. I want to maintain a file (or in memory data-structure) that
will contain the list of python scripts that may be executed on the
machine; the scripts that are not in this list shouldn't be allowed to get
executed.
Is there any way or tool to achieve this in python?
How to start Activity using instance of it?
How to start Activity using instance of it?
I used this code to start a activity but throw a NullPointer and
illegalState exceptions.this is the code.
String test="test";
DownloadActivity downloadAct=new DownloadActivity(test);
Intent intent=new Intent(this,DownloadActivity.class);
downloadAct.startActivity(intent);
Is this possible?And i also tried with
downloadAct.onCreate();
but it need to pass Bundle and i passed
new Bundle();
it throw null pointer exception,So how can i use DownloadActivity
constructers to set its data and start the activity?
I used this code to start a activity but throw a NullPointer and
illegalState exceptions.this is the code.
String test="test";
DownloadActivity downloadAct=new DownloadActivity(test);
Intent intent=new Intent(this,DownloadActivity.class);
downloadAct.startActivity(intent);
Is this possible?And i also tried with
downloadAct.onCreate();
but it need to pass Bundle and i passed
new Bundle();
it throw null pointer exception,So how can i use DownloadActivity
constructers to set its data and start the activity?
Tuesday, 10 September 2013
save the output from telnet
save the output from telnet
i'm already create the telnet with java, but i have no idea how to save
the output into file.. can help'me?? this is my code...
this is for connect to the target
public class telnetsample
{
private static TelnetClient telnet = new TelnetClient();
private InputStream in;
private PrintStream out;
private char prompt = '$';
public telnetsample( String server, String username, String password
, String command) {
try {
// Connect to the specified server
telnet.connect( server, 23 );
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream( telnet.getOutputStream() );
// Log the user on
readUntil( "Username: " );
write( username );
readUntil( "Password: " );
write( password );
readUntil ("hostname");
write (command);
// Advance to a prompt
readUntil( prompt + " " );
}
catch( Exception e ) {
e.printStackTrace();
}
}
this is for read the command on the terminal
public String readUntil( String pattern ) {
try {
char lastChar = pattern.charAt( pattern.length() - 1 );
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = ( char )in.read();
while( true ) {
System.out.print( ch );
sb.append( ch );
if( ch == lastChar ) {
if( sb.toString().endsWith( pattern ) ) {
return sb.toString();
}
}
ch = ( char )in.read();
}
}
catch( Exception e ) {
e.printStackTrace();
}
return null;
}
for send the command
public void write( String value ) {
try {
out.println( value );
out.flush();
System.out.println( value );
}
catch( Exception e ) {
e.printStackTrace();
}
}
for insert username etc
public static void main( String[] args ) {
try {
telnetsample telnet = new telnetsample( "ip",
"user",
"password",
"command");
}
catch( Exception e ) {
e.printStackTrace();
}
System.exit(0);
Runtime.getRuntime().exit(0);
}
}
i'm already create the telnet with java, but i have no idea how to save
the output into file.. can help'me?? this is my code...
this is for connect to the target
public class telnetsample
{
private static TelnetClient telnet = new TelnetClient();
private InputStream in;
private PrintStream out;
private char prompt = '$';
public telnetsample( String server, String username, String password
, String command) {
try {
// Connect to the specified server
telnet.connect( server, 23 );
// Get input and output stream references
in = telnet.getInputStream();
out = new PrintStream( telnet.getOutputStream() );
// Log the user on
readUntil( "Username: " );
write( username );
readUntil( "Password: " );
write( password );
readUntil ("hostname");
write (command);
// Advance to a prompt
readUntil( prompt + " " );
}
catch( Exception e ) {
e.printStackTrace();
}
}
this is for read the command on the terminal
public String readUntil( String pattern ) {
try {
char lastChar = pattern.charAt( pattern.length() - 1 );
StringBuffer sb = new StringBuffer();
boolean found = false;
char ch = ( char )in.read();
while( true ) {
System.out.print( ch );
sb.append( ch );
if( ch == lastChar ) {
if( sb.toString().endsWith( pattern ) ) {
return sb.toString();
}
}
ch = ( char )in.read();
}
}
catch( Exception e ) {
e.printStackTrace();
}
return null;
}
for send the command
public void write( String value ) {
try {
out.println( value );
out.flush();
System.out.println( value );
}
catch( Exception e ) {
e.printStackTrace();
}
}
for insert username etc
public static void main( String[] args ) {
try {
telnetsample telnet = new telnetsample( "ip",
"user",
"password",
"command");
}
catch( Exception e ) {
e.printStackTrace();
}
System.exit(0);
Runtime.getRuntime().exit(0);
}
}
rendering one item from a list in Ember
rendering one item from a list in Ember
In my Ember app, I get a list of all the restaurants using an ajax call
copied from Discourse co-founder's blog post
http://eviltrout.com/2013/02/27/adding-to-discourse-part-1.html
App.Restaurant.reopenClass({
findAll: function() {
return $.getJSON("restaurants").then(
function(response) {
var links = Em.A();
response.restaurants.map(function (attrs) {
links.pushObject(App.Restaurant.create(attrs));
});
return links;
}
);
},
I have a Restaurants route set up which calls the findAll shown above and
renders it into the application template
App.RestaurantsRoute = Ember.Route.extend({
model: function(params) {
return(App.Restaurant.findAll(params));
},
renderTemplate: function() {
this.render('restaurants', {into: 'application'});
}
});
The restaurants are displayed as a restaurants template like this with a
link to each individual restaurant. I've also included the restaurant
template
<script type="text/x-handlebars" id="restaurants">
<div class='span4'>
{{#each item in model}}
<li> {{#link-to 'restaurant' item}}
{{ item.name }}
</li>
{{/each}}
</ul>
</div>
<div class="span4 offset4">
</div>
</script>
In the Ember router, I have a parent/child route set up like this
this.resource("restaurants", function(){
this.resource("restaurant", { path: ':restaurant_id'});
});
Therefore, I'm hoping that when I click on the link to a particular
restaurant in the restaurants list, it'll insert this restaurant template
into the outlet defined in the restaurantS (plural) template
<script type="text/x-handlebars" id="restaurant">
this text is getting rendered
{{ item }} //item nor item.name are getting rendered
</script>
This restaurant template is getting rendered, however, the data for the
item is not getting displayed.
When I click {{#link-to 'restaurant' item}} in the list, item represents
that restaurant.
In this setup, does Ember need to make another ajax call to retrieve that
particular item, even though it's already been loaded from the findAll
call?
In the event that I do need to query for the individual restaurant (again)
I created a new route for the individual restaurant
App.RestaurantRoute = Ember.Route.extend({
model: function(params) {
console.log(params);
console.log('resto');
return App.Restaurant.findItem(params);
}
});
and a findItem on the Restaurant model
App.Restaurant.reopenClass({
findItem: function(){
console.log('is this getting called? No...');
return 'blah'
}
but none of those console.logs are getting called.
In the Ember starter video https://www.youtube.com/watch?v=1QHrlFlaXdI,
when Tom Dale clicks on a blog post from the list, the post appears in the
template defined for it without him having to do anything more than set up
the routes (as I did) and the {{outlet}} within the posts template to
receive the post.
Can you see why the same is not working for me in this situation?
In my Ember app, I get a list of all the restaurants using an ajax call
copied from Discourse co-founder's blog post
http://eviltrout.com/2013/02/27/adding-to-discourse-part-1.html
App.Restaurant.reopenClass({
findAll: function() {
return $.getJSON("restaurants").then(
function(response) {
var links = Em.A();
response.restaurants.map(function (attrs) {
links.pushObject(App.Restaurant.create(attrs));
});
return links;
}
);
},
I have a Restaurants route set up which calls the findAll shown above and
renders it into the application template
App.RestaurantsRoute = Ember.Route.extend({
model: function(params) {
return(App.Restaurant.findAll(params));
},
renderTemplate: function() {
this.render('restaurants', {into: 'application'});
}
});
The restaurants are displayed as a restaurants template like this with a
link to each individual restaurant. I've also included the restaurant
template
<script type="text/x-handlebars" id="restaurants">
<div class='span4'>
{{#each item in model}}
<li> {{#link-to 'restaurant' item}}
{{ item.name }}
</li>
{{/each}}
</ul>
</div>
<div class="span4 offset4">
</div>
</script>
In the Ember router, I have a parent/child route set up like this
this.resource("restaurants", function(){
this.resource("restaurant", { path: ':restaurant_id'});
});
Therefore, I'm hoping that when I click on the link to a particular
restaurant in the restaurants list, it'll insert this restaurant template
into the outlet defined in the restaurantS (plural) template
<script type="text/x-handlebars" id="restaurant">
this text is getting rendered
{{ item }} //item nor item.name are getting rendered
</script>
This restaurant template is getting rendered, however, the data for the
item is not getting displayed.
When I click {{#link-to 'restaurant' item}} in the list, item represents
that restaurant.
In this setup, does Ember need to make another ajax call to retrieve that
particular item, even though it's already been loaded from the findAll
call?
In the event that I do need to query for the individual restaurant (again)
I created a new route for the individual restaurant
App.RestaurantRoute = Ember.Route.extend({
model: function(params) {
console.log(params);
console.log('resto');
return App.Restaurant.findItem(params);
}
});
and a findItem on the Restaurant model
App.Restaurant.reopenClass({
findItem: function(){
console.log('is this getting called? No...');
return 'blah'
}
but none of those console.logs are getting called.
In the Ember starter video https://www.youtube.com/watch?v=1QHrlFlaXdI,
when Tom Dale clicks on a blog post from the list, the post appears in the
template defined for it without him having to do anything more than set up
the routes (as I did) and the {{outlet}} within the posts template to
receive the post.
Can you see why the same is not working for me in this situation?
Temporarily store User id when loading user page for multiple views/controllers
Temporarily store User id when loading user page for multiple
views/controllers
I want to create a multi user app with no authentication.
I want to have unique urls for each user and assume they will not know
other people's urls. So when user visits a user page, I want to store that
id and use it provide a nav link (to setup a nav like 'my page | feed page
| some other page')
I've been trying to figure out how to use current_user=sessions[:user_id]
in the Application Controller but am getting lost.
views/controllers
I want to create a multi user app with no authentication.
I want to have unique urls for each user and assume they will not know
other people's urls. So when user visits a user page, I want to store that
id and use it provide a nav link (to setup a nav like 'my page | feed page
| some other page')
I've been trying to figure out how to use current_user=sessions[:user_id]
in the Application Controller but am getting lost.
web app to mobile app
web app to mobile app
Am new into mobile app development but I have a web application i built
using jquery mobile its actually suppose to be a mobile application but it
all in html, css, php and javascript. it runs good on a browser and i can
loadit up from my wamp server but it originally suppose to be a phone app
how can i turn that into a phone app. I have tried sencha, and my xdk does
not even load. I need help cause i dont want to end up re-coding the
entire app; i just want to use my existing .html file and .css and and .js
and i understand their are some basic event handlers that will be
different from event handler on a web browser. Anyhelp is appreaciated.
Thanks
Am new into mobile app development but I have a web application i built
using jquery mobile its actually suppose to be a mobile application but it
all in html, css, php and javascript. it runs good on a browser and i can
loadit up from my wamp server but it originally suppose to be a phone app
how can i turn that into a phone app. I have tried sencha, and my xdk does
not even load. I need help cause i dont want to end up re-coding the
entire app; i just want to use my existing .html file and .css and and .js
and i understand their are some basic event handlers that will be
different from event handler on a web browser. Anyhelp is appreaciated.
Thanks
What is the LifeCycle of VM
What is the LifeCycle of VM
The Component that Start VM is we referred as Launcher, is
this launcher (ie java/javaws Other Launchers like JNI
(JNI_CreateJavaVM) command) follow this Lifecycle.
Typically the Process what we see when we invoke this command
Parsing of Command Line.
Heap Initialization
Lookup the Main Class.
Create the HotSpot VM using Native call.
Execute the main Class
Perform the CLeanup Operation
Is something more goes when the VM life cycle Initiate
The Component that Start VM is we referred as Launcher, is
this launcher (ie java/javaws Other Launchers like JNI
(JNI_CreateJavaVM) command) follow this Lifecycle.
Typically the Process what we see when we invoke this command
Parsing of Command Line.
Heap Initialization
Lookup the Main Class.
Create the HotSpot VM using Native call.
Execute the main Class
Perform the CLeanup Operation
Is something more goes when the VM life cycle Initiate
Responsive Javascript Slider with Multibox
Responsive Javascript Slider with Multibox
I want to make Slider like showing me a three slide at a time, like bit
small size images both side and middle image with large size, and when i
click on arrow this will show me a second images that right now we can see
on side image like below image.
Please help to find me slider like i tell you, thanks a lot in advance
I want to make Slider like showing me a three slide at a time, like bit
small size images both side and middle image with large size, and when i
click on arrow this will show me a second images that right now we can see
on side image like below image.
Please help to find me slider like i tell you, thanks a lot in advance
Why is this jQuery Validation not working on IE 7/8?
Why is this jQuery Validation not working on IE 7/8?
I'm encountering a small problem with a client-side validation script
which works on all browsers including IE 9 / 10, but is giving me
headaches on IE 7 and IE 8.
The page with the form which needs this validation can be accesed over
here and someone must definetly take a look in order to give a good
answer.
And here's the validation script I use for the form:
jQuery(document).ready(function(){
jQuery("#adaugareanunt").submit(function(event){
errornotice = jQuery("#eroareadaugare");
emptyerror = "Necompletat";
emailerror = "Email incorect";
email = jQuery('#contactEmail');
descriere = jQuery('#descriptionro_RO');
jQuery('#adaugareanunt input[type="text"]').each(function(){
if ((jQuery(this).val() == "") || (jQuery(this).val() ==
emptyerror)) {
jQuery(this).addClass("campuri-necesare");
jQuery(this).val(emptyerror);
errornotice.fadeIn(750);
} else {
jQuery(this).removeClass("campuri-necesare");
}
});
jQuery('#adaugareanunt select').each(function(){
if ((jQuery(this).val() == "")) {
jQuery(this).addClass("campuri-necesare");
errornotice.fadeIn(750);
} else {
jQuery(this).removeClass("campuri-necesare");
}
});
if(descriere.val() == "" || descriere.val() == emptyerror) {
descriere.addClass("campuri-necesare");
descriere.val(emptyerror);
errornotice.fadeIn(750);
} else {
descriere.removeClass("campuri-necesare");
}
if
(!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val()))
{
email.addClass("campuri-necesare");
email.val(emailerror);
}
if (jQuery(":input").hasClass("campuri-necesare")) {
return false;
}
});
// Clears any fields in the form when the user clicks on them
jQuery(":input").focus(function(){
if (jQuery(this).hasClass("campuri-necesare") ) {
jQuery(this).val("");
jQuery(this).removeClass("campuri-necesare");
}
});
});
Any hints?
Thanks!
I'm encountering a small problem with a client-side validation script
which works on all browsers including IE 9 / 10, but is giving me
headaches on IE 7 and IE 8.
The page with the form which needs this validation can be accesed over
here and someone must definetly take a look in order to give a good
answer.
And here's the validation script I use for the form:
jQuery(document).ready(function(){
jQuery("#adaugareanunt").submit(function(event){
errornotice = jQuery("#eroareadaugare");
emptyerror = "Necompletat";
emailerror = "Email incorect";
email = jQuery('#contactEmail');
descriere = jQuery('#descriptionro_RO');
jQuery('#adaugareanunt input[type="text"]').each(function(){
if ((jQuery(this).val() == "") || (jQuery(this).val() ==
emptyerror)) {
jQuery(this).addClass("campuri-necesare");
jQuery(this).val(emptyerror);
errornotice.fadeIn(750);
} else {
jQuery(this).removeClass("campuri-necesare");
}
});
jQuery('#adaugareanunt select').each(function(){
if ((jQuery(this).val() == "")) {
jQuery(this).addClass("campuri-necesare");
errornotice.fadeIn(750);
} else {
jQuery(this).removeClass("campuri-necesare");
}
});
if(descriere.val() == "" || descriere.val() == emptyerror) {
descriere.addClass("campuri-necesare");
descriere.val(emptyerror);
errornotice.fadeIn(750);
} else {
descriere.removeClass("campuri-necesare");
}
if
(!/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val()))
{
email.addClass("campuri-necesare");
email.val(emailerror);
}
if (jQuery(":input").hasClass("campuri-necesare")) {
return false;
}
});
// Clears any fields in the form when the user clicks on them
jQuery(":input").focus(function(){
if (jQuery(this).hasClass("campuri-necesare") ) {
jQuery(this).val("");
jQuery(this).removeClass("campuri-necesare");
}
});
});
Any hints?
Thanks!
Subscribe to:
Comments (Atom)