How do I create a Java Package and Test it Using Vim in Linux
I know how to create a java package, write code in the /src folder and
test it from the /tst folder. But, I want to learn how I can do that
without Eclipse, just using Vim.
For example, I have a java Hello World Class:
class HelloWorld {
public void disp() {
System.out.println("Hello World");
}
}
I save this in a directory home/javacode/HelloWorld
Now, I write a test for it in the same folder :
import org.junit.*;
class HelloWorldTest extends HelloWorld {
@Test testHelloWorld() {
HelloWorld hello = new HelloWorld();
hello.disp();
}
}
Now, can someone please help me as to how to get this test to run? As in I
have to compile Hello World as :
javac HelloWorld.java
and then compile the test as :
javac -cp "path to junit" HelloWorldTest.java
However, I always end up with a ClassPath error. I understand that I am
really messing up something very fundamental here. Please do help me out
with this!
Thursday, 3 October 2013
Wednesday, 2 October 2013
How to access var data from javascript and put into form value
How to access var data from javascript and put into form value
I've been using http://jscolor.com/ but I'm not getting one thing How can
i take out the value of the color and paste it to value area in the form
I tried to put the script there but didn't work. How can i get +this.color
into value area ?
<input value=""
onchange="document.getElementsByTagName('BODY')[0].style.backgroundColor =
'#'+this.color">
I've been using http://jscolor.com/ but I'm not getting one thing How can
i take out the value of the color and paste it to value area in the form
I tried to put the script there but didn't work. How can i get +this.color
into value area ?
<input value=""
onchange="document.getElementsByTagName('BODY')[0].style.backgroundColor =
'#'+this.color">
Better way to restrict object to certain attributes
Better way to restrict object to certain attributes
Suppose I have an object:
obj =
foo: 'foo'
bar: 'bar'
... and lots of other stuff ...
... these values vary, and are not actually hard coded ...
I'd like to create a copy of that object which contains only a subset of
its attributes.
obj2 =
foo: obj.foo
bar: obj.bar
// *doesn't* copy any other attributes from `obj`
Is there a more idiomatic way of doing this? Something like
obj2 = copy_only obj, ['foo', 'bar']
I mean, sure, I could write copy_only myself, but I'm looking for the
idiomatic way to do this, not the home baked way. Is there such an idiom
that you can recommend for this scenario?
Suppose I have an object:
obj =
foo: 'foo'
bar: 'bar'
... and lots of other stuff ...
... these values vary, and are not actually hard coded ...
I'd like to create a copy of that object which contains only a subset of
its attributes.
obj2 =
foo: obj.foo
bar: obj.bar
// *doesn't* copy any other attributes from `obj`
Is there a more idiomatic way of doing this? Something like
obj2 = copy_only obj, ['foo', 'bar']
I mean, sure, I could write copy_only myself, but I'm looking for the
idiomatic way to do this, not the home baked way. Is there such an idiom
that you can recommend for this scenario?
Cascalog deffilterop vs pure clojure
Cascalog deffilterop vs pure clojure
Is there a difference, performance or otherwise, between using a
deffilterop and using a purse clojure function?
http://nathanmarz.com/blog/introducing-cascalog-a-clojure-based-query-language-for-hado.html
mentions that filtering can be done with clojure functions like (< ?age2
?age1) however looking at
https://github.com/nathanmarz/cascalog/wiki/Guide-to-custom-operations it
looks like you can define a function like (deffilterop is-2? [x] (= x 2)).
So my question is, is there any difference between these two approaches
and if not which is the preferred syntax?
Note: It also looks like all of the defxxxop functions are being
deprecated for defxxxfn instead.
https://github.com/nathanmarz/cascalog/blob/develop/cascalog-core/src/clj/cascalog/logic/def.clj#L131
Is there a difference, performance or otherwise, between using a
deffilterop and using a purse clojure function?
http://nathanmarz.com/blog/introducing-cascalog-a-clojure-based-query-language-for-hado.html
mentions that filtering can be done with clojure functions like (< ?age2
?age1) however looking at
https://github.com/nathanmarz/cascalog/wiki/Guide-to-custom-operations it
looks like you can define a function like (deffilterop is-2? [x] (= x 2)).
So my question is, is there any difference between these two approaches
and if not which is the preferred syntax?
Note: It also looks like all of the defxxxop functions are being
deprecated for defxxxfn instead.
https://github.com/nathanmarz/cascalog/blob/develop/cascalog-core/src/clj/cascalog/logic/def.clj#L131
HTML Form $_POST wont owrk
HTML Form $_POST wont owrk
menus.php
<?php
$con=mysqli_connect("localhost","root","","mmogezgini");
$menuler = mysqli_query($con,"SELECT * FROM menuler");
while($menu = mysqli_fetch_array($menuler)) {
$isim = $menu["isim"];
$url = $menu["url"];
?>
<form method="post">Menü Ýsmi :<input name="menu_isim" value="<?php echo
$isim; ?>" disabled> | Menü URL : <input name="menu_url" value="<?php echo
$url;?>"disabled> <button type="submit" formmethod="post"
formaction="menu_duzenle.php">Düzenle</button> <button
formaction="menu_sil.php">Sil</button></form><br>
<?php
}
?>
edit_menu.php
<form method="post" action="menu_duzenle_islem.php">
Þuanki Ýsim : <input name="menu_isim" value="<?php echo
$_POST['menu_isim'] ?>"disabled>
Yeni Ýsim : <input name="yeni_menu_isim" placeholder="yeni menü ismini
giriniz.">
</form>
My Problem is form in menus.php wont send $_POST['menu_isim'] to
edit_menu.php
menus.php
<?php
$con=mysqli_connect("localhost","root","","mmogezgini");
$menuler = mysqli_query($con,"SELECT * FROM menuler");
while($menu = mysqli_fetch_array($menuler)) {
$isim = $menu["isim"];
$url = $menu["url"];
?>
<form method="post">Menü Ýsmi :<input name="menu_isim" value="<?php echo
$isim; ?>" disabled> | Menü URL : <input name="menu_url" value="<?php echo
$url;?>"disabled> <button type="submit" formmethod="post"
formaction="menu_duzenle.php">Düzenle</button> <button
formaction="menu_sil.php">Sil</button></form><br>
<?php
}
?>
edit_menu.php
<form method="post" action="menu_duzenle_islem.php">
Þuanki Ýsim : <input name="menu_isim" value="<?php echo
$_POST['menu_isim'] ?>"disabled>
Yeni Ýsim : <input name="yeni_menu_isim" placeholder="yeni menü ismini
giriniz.">
</form>
My Problem is form in menus.php wont send $_POST['menu_isim'] to
edit_menu.php
Tuesday, 1 October 2013
Qt signals and slots: permissions
Qt signals and slots: permissions
There are discrepancies between respected answers here on SO and the
actual Qt docs.
I've read this question and I want some further clarification. Can anyone
confirm:
A signal is always protected, therefore it can be emitted only by the
class or any of its subclasses. I'm not sure this is true; the question
above shows answers supporting this statement. But the Qt docs say:
Signals are public access functions and can be emitted from anywhere, but
we recommend to only emit them from the class that defines the signal and
its subclasses. So which is it?
The words public, private, protected have no use with working with the
signal keyword
The emitted signal is always available to all other classes, that is, any
other class may always connect to that signal (but not emit it).
Despite that all signals are viewable to by all classes, you could still
have two classes with signals of the same name since the connect function
takes the class name as a signal prefix (i.e. SomeClass::itsSignal)
Slots are just functions, and thus may be public, private or protected.
Obviously an outside class will have the ability to control if your class
connects one of its own signals to one of its own slots if the slot is
public. However, again the SO information differs from the docs, which
say: a signal emitted from an instance of an arbitrary class can cause a
private slot to be invoked in an instance of an unrelated class. This
means that private is not honored by the signal/slot mechanism?
There are discrepancies between respected answers here on SO and the
actual Qt docs.
I've read this question and I want some further clarification. Can anyone
confirm:
A signal is always protected, therefore it can be emitted only by the
class or any of its subclasses. I'm not sure this is true; the question
above shows answers supporting this statement. But the Qt docs say:
Signals are public access functions and can be emitted from anywhere, but
we recommend to only emit them from the class that defines the signal and
its subclasses. So which is it?
The words public, private, protected have no use with working with the
signal keyword
The emitted signal is always available to all other classes, that is, any
other class may always connect to that signal (but not emit it).
Despite that all signals are viewable to by all classes, you could still
have two classes with signals of the same name since the connect function
takes the class name as a signal prefix (i.e. SomeClass::itsSignal)
Slots are just functions, and thus may be public, private or protected.
Obviously an outside class will have the ability to control if your class
connects one of its own signals to one of its own slots if the slot is
public. However, again the SO information differs from the docs, which
say: a signal emitted from an instance of an arbitrary class can cause a
private slot to be invoked in an instance of an unrelated class. This
means that private is not honored by the signal/slot mechanism?
How do you sort a collection by distant relationships?
How do you sort a collection by distant relationships?
I have a tree-like relationship model with a fixed depth, and each level
has a code attribute - similar to this;
class Category < ActiveRecord::Base
has_many :sub_categories
default_scope order(:code)
end
class SubCategory < ActiveRecord::Base
belongs_to :category
has_many :items
def self.sorted
self.joins(:category).order('"categories".code ASC,
"sub_categories".code')
end
end
class Item < ActiveRecord::Base
belongs_to :sub_category
def self.sorted
# what goes here?
end
end
Category.all gets all the the categories ordered by categories.code.
SubCategory.sorted gets all the sub_categories ordered by categories.code,
sub_categories.code. I used this approach because default_scope :
joins(:categories).order('categories.code, sub_categories.code') makes
.find return read-only records.
I would like to call Items.sorted and get the all items ordered by
categories.code, sub_categories.code, items.code but I can't figure out
how. I imagine I need a second .joins, but I don't have a relationship
name to supply.
I have a tree-like relationship model with a fixed depth, and each level
has a code attribute - similar to this;
class Category < ActiveRecord::Base
has_many :sub_categories
default_scope order(:code)
end
class SubCategory < ActiveRecord::Base
belongs_to :category
has_many :items
def self.sorted
self.joins(:category).order('"categories".code ASC,
"sub_categories".code')
end
end
class Item < ActiveRecord::Base
belongs_to :sub_category
def self.sorted
# what goes here?
end
end
Category.all gets all the the categories ordered by categories.code.
SubCategory.sorted gets all the sub_categories ordered by categories.code,
sub_categories.code. I used this approach because default_scope :
joins(:categories).order('categories.code, sub_categories.code') makes
.find return read-only records.
I would like to call Items.sorted and get the all items ordered by
categories.code, sub_categories.code, items.code but I can't figure out
how. I imagine I need a second .joins, but I don't have a relationship
name to supply.
Proving $\gcd((a+b)^m,(a-b)^m)\le2^m$ for coprime $a,b$ and $m \in \Bbb N$
Proving $\gcd((a+b)^m,(a-b)^m)\le2^m$ for coprime $a,b$ and $m \in \Bbb N$
If $a$ and $b$ are two coprime integers then prove that $\gcd((a+b)^m,
(a-b)^m) \leq 2^m$
My attempt:
I took two cases first one in which a and b are both odd then very clearly
the gcd will be 2^m but I'm stuck in the second case in which one of the
integer is even and the other one is odd I am reaching no where I tried
everything even binomial expansion but I'm stuck.
If $a$ and $b$ are two coprime integers then prove that $\gcd((a+b)^m,
(a-b)^m) \leq 2^m$
My attempt:
I took two cases first one in which a and b are both odd then very clearly
the gcd will be 2^m but I'm stuck in the second case in which one of the
integer is even and the other one is odd I am reaching no where I tried
everything even binomial expansion but I'm stuck.
What should be teach about the reciprocity law for high school for gifted student
What should be teach about the reciprocity law for high school for gifted
student
This autumn I have to teach a mini course for a small group of high school
student (mathematical gifted class) on Quadratic Reciprocity Law (3
lectures in ten hours). This is the requirement of the school for me to
become an assistant lecturer. I have studied thís law in the second year
in university, but that was only a glimpse: the origin, the proof... and
my approach at that time was quite modern. I know that this law is very
beautiful and important in mathematics, but I did know much about its role
and applications.
So,
What are the books/lecture notes/papers should I read for preparing my talk?
What should be teach about this topic for high school student? (May be
like the reciprocity law with a view toward modern number
theory/mathematics?)
student
This autumn I have to teach a mini course for a small group of high school
student (mathematical gifted class) on Quadratic Reciprocity Law (3
lectures in ten hours). This is the requirement of the school for me to
become an assistant lecturer. I have studied thís law in the second year
in university, but that was only a glimpse: the origin, the proof... and
my approach at that time was quite modern. I know that this law is very
beautiful and important in mathematics, but I did know much about its role
and applications.
So,
What are the books/lecture notes/papers should I read for preparing my talk?
What should be teach about this topic for high school student? (May be
like the reciprocity law with a view toward modern number
theory/mathematics?)
Monday, 30 September 2013
Assistance diagnosing SenderID PermError in Exchange 2010
Assistance diagnosing SenderID PermError in Exchange 2010
We're having issues with a customer's domain. They're wanting to do a
mail-out with a service called Act-On, and so far all the tests seem to be
getting flagged as spam.
The customer has tried sending to:
Themselves (Office 365): Goes to junk folder.
Gmail: Goes to junk folder.
Our Exchange: Gets quarantined.
So it seems clear there's an issue, and I believe it is SenderID, as in
our Quarantine mailbox, the NDR showed:
Received-SPF: PermError (exchange.ourdomain.com: domain of
person@customerdomain.com used an invalid SPF mechanism)
My issue is that I need assistance trying to figure out why it's giving
this error. The only tool that seems to be confirming the issue is
Exchange's own Test-SenderID cmdlet. Every other tool shows no issue.
According to Microsoft, and the OpenSPF docs, PermError should be some
kind of syntax or formatting issue. But I can't spot one, and none of the
tools I've used have hinted to one.
I've used the following SPF record, and also explicitly specified a
SenderID record in case this issue is at play.
;; QUESTION SECTION:
;customerdomain.com. IN TXT
;; ANSWER SECTION:
customerdomain.com. 2335 IN TXT "spf2.0/pra
include:spf.protection.outlook.com include:_spf.act-on.net -all"
customerdomain.com. 2335 IN TXT "MS=msxxxxxxxx"
customerdomain.com. 2335 IN TXT "v=spf1
include:spf.protection.outlook.com include:_spf.act-on.net -all"
What I've Tried
Checked for the SPF vs. SenderID issue.
Tested using this SPF Syntax checker:
http://www.kitterman.com/spf/validate.html - Passes
And this one: http://mxtoolbox.com/spf.aspx - Passes
Used the Microsoft SenderID Wizard to compare my SPF record, and then
generate the SenderID record - Seem to match, though interestingly, the
wizard never seems to detect the existing records.
As per this post I've checked both the Office 365 and Act-On SPF records I
am including, and they both seem valid.
And this:
http://www.port25.com/support/authentication-center/email-verification/ -
Passes
Below are details from the Port25 report - I asked for a copy of the
mail-out to be sent via Act-On as it would normally, so the email is
actually coming from Act-On (@b2b-mail.net):
==========================================================
Summary of Results
==========================================================
SPF check: pass
DomainKeys check: neutral
DKIM check: pass
Sender-ID check: pass
SpamAssassin check: ham
==========================================================
Details:
==========================================================
HELO hostname: mx139.b2b-mail.net
Source IP: 209.162.194.139
mail-from: delivery@b2b-mail.net
----------------------------------------------------------
SPF check details:
----------------------------------------------------------
Result: pass
ID(s) verified: smtp.mailfrom=delivery@b2b-mail.net
DNS record(s):
b2b-mail.net. SPF (no records)
b2b-mail.net. 3600 IN TXT "v=spf1 ip4:69.30.4.0/27 ip4:69.30.45.96/27
ip4:207.189.98.224/27 ip4:207.189.124.224/27 ip4:207.189.125.224/27
ip4:209.162.194.0/24 ~all"
----------------------------------------------------------
DomainKeys check details:
----------------------------------------------------------
Result: neutral (message not signed)
ID(s) verified: header.From=person@customerdomain.com
DNS record(s):
We're having issues with a customer's domain. They're wanting to do a
mail-out with a service called Act-On, and so far all the tests seem to be
getting flagged as spam.
The customer has tried sending to:
Themselves (Office 365): Goes to junk folder.
Gmail: Goes to junk folder.
Our Exchange: Gets quarantined.
So it seems clear there's an issue, and I believe it is SenderID, as in
our Quarantine mailbox, the NDR showed:
Received-SPF: PermError (exchange.ourdomain.com: domain of
person@customerdomain.com used an invalid SPF mechanism)
My issue is that I need assistance trying to figure out why it's giving
this error. The only tool that seems to be confirming the issue is
Exchange's own Test-SenderID cmdlet. Every other tool shows no issue.
According to Microsoft, and the OpenSPF docs, PermError should be some
kind of syntax or formatting issue. But I can't spot one, and none of the
tools I've used have hinted to one.
I've used the following SPF record, and also explicitly specified a
SenderID record in case this issue is at play.
;; QUESTION SECTION:
;customerdomain.com. IN TXT
;; ANSWER SECTION:
customerdomain.com. 2335 IN TXT "spf2.0/pra
include:spf.protection.outlook.com include:_spf.act-on.net -all"
customerdomain.com. 2335 IN TXT "MS=msxxxxxxxx"
customerdomain.com. 2335 IN TXT "v=spf1
include:spf.protection.outlook.com include:_spf.act-on.net -all"
What I've Tried
Checked for the SPF vs. SenderID issue.
Tested using this SPF Syntax checker:
http://www.kitterman.com/spf/validate.html - Passes
And this one: http://mxtoolbox.com/spf.aspx - Passes
Used the Microsoft SenderID Wizard to compare my SPF record, and then
generate the SenderID record - Seem to match, though interestingly, the
wizard never seems to detect the existing records.
As per this post I've checked both the Office 365 and Act-On SPF records I
am including, and they both seem valid.
And this:
http://www.port25.com/support/authentication-center/email-verification/ -
Passes
Below are details from the Port25 report - I asked for a copy of the
mail-out to be sent via Act-On as it would normally, so the email is
actually coming from Act-On (@b2b-mail.net):
==========================================================
Summary of Results
==========================================================
SPF check: pass
DomainKeys check: neutral
DKIM check: pass
Sender-ID check: pass
SpamAssassin check: ham
==========================================================
Details:
==========================================================
HELO hostname: mx139.b2b-mail.net
Source IP: 209.162.194.139
mail-from: delivery@b2b-mail.net
----------------------------------------------------------
SPF check details:
----------------------------------------------------------
Result: pass
ID(s) verified: smtp.mailfrom=delivery@b2b-mail.net
DNS record(s):
b2b-mail.net. SPF (no records)
b2b-mail.net. 3600 IN TXT "v=spf1 ip4:69.30.4.0/27 ip4:69.30.45.96/27
ip4:207.189.98.224/27 ip4:207.189.124.224/27 ip4:207.189.125.224/27
ip4:209.162.194.0/24 ~all"
----------------------------------------------------------
DomainKeys check details:
----------------------------------------------------------
Result: neutral (message not signed)
ID(s) verified: header.From=person@customerdomain.com
DNS record(s):
Update repositories on Ubuntu 8.04
Update repositories on Ubuntu 8.04
I just finished of installing ubuntu 8.04 on a low-resources computer.
When I try to update it says an repository error.
The support of 8.04 has finished, I suspect that the repositories too.
There are another repository for this version??
I just finished of installing ubuntu 8.04 on a low-resources computer.
When I try to update it says an repository error.
The support of 8.04 has finished, I suspect that the repositories too.
There are another repository for this version??
Get data for current month using Linq - VB
Get data for current month using Linq - VB
I have the following code which is listing the top 3 'names' in descending
order with a count of how many records that 'name' appears in in the
table. This is working ok.
Dim top3 = From s In dc.Suggestions
Group By Name = s.name
Into t3 = Group, Count()
Order By Count Descending
Take 3
I want to amend this so that it will only get a count of the number of
records each 'name' appears in for the current month. I can use
s.dateRaised to get the date of the record but i'm not entirely sure how
to write the code to get only the current month's records?
I have the following code which is listing the top 3 'names' in descending
order with a count of how many records that 'name' appears in in the
table. This is working ok.
Dim top3 = From s In dc.Suggestions
Group By Name = s.name
Into t3 = Group, Count()
Order By Count Descending
Take 3
I want to amend this so that it will only get a count of the number of
records each 'name' appears in for the current month. I can use
s.dateRaised to get the date of the record but i'm not entirely sure how
to write the code to get only the current month's records?
how to change attribute values using xsl
how to change attribute values using xsl
im still learning xsl and i'm trying to change the value im getting from
the xsl to another value. (im using xsl to convert my xml to another xml)
xml
<?xml version="1.0" encoding="UTF-8"?>
<Person>
<Info Name="Jen" Age="20" Class="C" />
</Person>
xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:template match="/">
<Person>
<lookuptable>
<name first="Jen" ori="Jenny" />
<name first="Sam" ori="Sammy" />
</lookuptable>
<xsl:for-each select="Person">
<Info Name="{Info/@Name}" Age="{Info/@Age}" Class="{Info/@Class}" />
</xsl:for-each>
</Person>
</xsl:template>
</xsl:stylesheet>
i created a lookuptable. {Info/@Name} gives me "Jen" in the converted
xml(using xsl) i want to change it to "Jenny" using table but i dont know
how to do it. thanks in advance..
im still learning xsl and i'm trying to change the value im getting from
the xsl to another value. (im using xsl to convert my xml to another xml)
xml
<?xml version="1.0" encoding="UTF-8"?>
<Person>
<Info Name="Jen" Age="20" Class="C" />
</Person>
xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
<xsl:template match="/">
<Person>
<lookuptable>
<name first="Jen" ori="Jenny" />
<name first="Sam" ori="Sammy" />
</lookuptable>
<xsl:for-each select="Person">
<Info Name="{Info/@Name}" Age="{Info/@Age}" Class="{Info/@Class}" />
</xsl:for-each>
</Person>
</xsl:template>
</xsl:stylesheet>
i created a lookuptable. {Info/@Name} gives me "Jen" in the converted
xml(using xsl) i want to change it to "Jenny" using table but i dont know
how to do it. thanks in advance..
Sunday, 29 September 2013
Allow user post products
Allow user post products
I need to know if I can in prestashop or another eccommerce framework
allow the users to publish his own products.
I ask this because i need that feature to my site.
Thanks in advance !
I need to know if I can in prestashop or another eccommerce framework
allow the users to publish his own products.
I ask this because i need that feature to my site.
Thanks in advance !
Get seed based on id and date with minimal number of objects
Get seed based on id and date with minimal number of objects
I need to create a seed for shuffling and the seed should be based on an
id (int) and the current date (without the time). This is to preserve the
ordering for an id for a single day and change it the next day. I have got
the following method for this now:
private static long getSeedForShuffle(int id)
{
Date date = new Date();
Calendar cal = MyConstants.UTC_CALENDAR;
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
double seed = id * 1e8 + year * 1e4 + month * 1e2 + day;
return (long) seed;
}
and this in MyConstants:
public class MyConstants {
public static final Calendar UTC_CALENDAR = Calendar.getInstance(TimeZone
.getTimeZone("UTC"));
}
Is there any way to avoid creating the new date object every time the
method is invoked? i.e. is there something better than doing
Date date = new Date();
in the getSeedForShuffle method, since all this method needs is the
current day, month and year, which can, in principle, be generated only
once daily?
NOTE: This code is running in a web application.
(Started thinking about this after reading Effective Java Item 5: Avoid
creating unnecessary objects.)
I need to create a seed for shuffling and the seed should be based on an
id (int) and the current date (without the time). This is to preserve the
ordering for an id for a single day and change it the next day. I have got
the following method for this now:
private static long getSeedForShuffle(int id)
{
Date date = new Date();
Calendar cal = MyConstants.UTC_CALENDAR;
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
double seed = id * 1e8 + year * 1e4 + month * 1e2 + day;
return (long) seed;
}
and this in MyConstants:
public class MyConstants {
public static final Calendar UTC_CALENDAR = Calendar.getInstance(TimeZone
.getTimeZone("UTC"));
}
Is there any way to avoid creating the new date object every time the
method is invoked? i.e. is there something better than doing
Date date = new Date();
in the getSeedForShuffle method, since all this method needs is the
current day, month and year, which can, in principle, be generated only
once daily?
NOTE: This code is running in a web application.
(Started thinking about this after reading Effective Java Item 5: Avoid
creating unnecessary objects.)
which activity will be opened via external link?
which activity will be opened via external link?
I'm deubgging an android app.
I have a bug that happens when someone open the app using http link:
i.e.
http://appName.to/hsv8wrq6bd
how can I see where is the entry point that this link opens and run my
application?
Can i see it in AndroidManifest?
I'm deubgging an android app.
I have a bug that happens when someone open the app using http link:
i.e.
http://appName.to/hsv8wrq6bd
how can I see where is the entry point that this link opens and run my
application?
Can i see it in AndroidManifest?
Android home screen swipe feature
Android home screen swipe feature
How can i implement home screen swipe feature of android for a user to
swipe between 2 view which covers the entire page. During the swipe the
View must animate 100%, but the background must move by only 20%.
How can i implement home screen swipe feature of android for a user to
swipe between 2 view which covers the entire page. During the swipe the
View must animate 100%, but the background must move by only 20%.
Saturday, 28 September 2013
In golang how do you convert a slice into an array
In golang how do you convert a slice into an array
I am new to go and trying to write an application that reads RPM files.
The start of each block has a Magic char of [4]byte.
Here is my struct
type Lead struct {
Magic [4]byte
Major, Minor byte
Type uint16
Arch uint16
Name string
OS uint16
SigType uint16
}
I am trying to do the following:
lead := Lead{}
lead.Magic = buffer[0:4]
I am searching online and not sure how to go from a slice to an array
(without copying). I can always make the Magic []byte (or even uint64),
but I was more curious on how would I go from type []byte to [4]byte if
needed to?
I am new to go and trying to write an application that reads RPM files.
The start of each block has a Magic char of [4]byte.
Here is my struct
type Lead struct {
Magic [4]byte
Major, Minor byte
Type uint16
Arch uint16
Name string
OS uint16
SigType uint16
}
I am trying to do the following:
lead := Lead{}
lead.Magic = buffer[0:4]
I am searching online and not sure how to go from a slice to an array
(without copying). I can always make the Magic []byte (or even uint64),
but I was more curious on how would I go from type []byte to [4]byte if
needed to?
Close and open another div after the loop increments by 3 every time
Close and open another div after the loop increments by 3 every time
I have an array. I am looping over that. First what I need is that when
the loop is run first it should already open up a div and add text to it.
Next I want that if a loop has run 3 times then close the previous div and
open a new div.
Code:
var counter = 0;
for (var i = 0; i < tag_array.length; i++) {
counter++;
if (counter == 3) {
counter = 0;
document.write("</div>");
document.write("<div class='span6'>");
} else {
document.write("<div class='span6'>");
}
document.write("<div class='tag'>" + toTitleCase(tag_array[i]) +
"</div>");
}
The above code is not working. I don't know why. Please explain me what I
am doing wrong and how can I fix it?
I have an array. I am looping over that. First what I need is that when
the loop is run first it should already open up a div and add text to it.
Next I want that if a loop has run 3 times then close the previous div and
open a new div.
Code:
var counter = 0;
for (var i = 0; i < tag_array.length; i++) {
counter++;
if (counter == 3) {
counter = 0;
document.write("</div>");
document.write("<div class='span6'>");
} else {
document.write("<div class='span6'>");
}
document.write("<div class='tag'>" + toTitleCase(tag_array[i]) +
"</div>");
}
The above code is not working. I don't know why. Please explain me what I
am doing wrong and how can I fix it?
how to retrieve Data from Intent ??
how to retrieve Data from Intent ??
I just want to show an simple Employee record on next layoutPage/Activity !!
this is my EmpLogin Java File
public class EmpLogin extends Activity {
private Button show;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// TODO Auto-generated method stub
show=(Button)findViewById(R.id.show);
show.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText no=(EditText)findViewById(R.id.getno);
EditText name=(EditText)findViewById(R.id.getname);
EditText sal=(EditText)findViewById(R.id.getsalary);
Intent emp = new Intent(getApplicationContext(),EmpShow.class);
emp.putExtra("EmpNO",(no.getText().toString()));
emp.putExtra("EmpName",(name.getText().toString()));
emp.putExtra("Sal",(sal.getText().toString()));
startActivity(emp);
}
});
}
}
How to use Retrieve data from the Intent ??? By using getExtra() method
??? or there is simple way ?? this my EmpShow.class file !!
public class EmpShow extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.empshow);
// TODO Auto-generated method stub
Intent show = getIntent();
}
}
I just want to show an simple Employee record on next layoutPage/Activity !!
this is my EmpLogin Java File
public class EmpLogin extends Activity {
private Button show;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
// TODO Auto-generated method stub
show=(Button)findViewById(R.id.show);
show.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
EditText no=(EditText)findViewById(R.id.getno);
EditText name=(EditText)findViewById(R.id.getname);
EditText sal=(EditText)findViewById(R.id.getsalary);
Intent emp = new Intent(getApplicationContext(),EmpShow.class);
emp.putExtra("EmpNO",(no.getText().toString()));
emp.putExtra("EmpName",(name.getText().toString()));
emp.putExtra("Sal",(sal.getText().toString()));
startActivity(emp);
}
});
}
}
How to use Retrieve data from the Intent ??? By using getExtra() method
??? or there is simple way ?? this my EmpShow.class file !!
public class EmpShow extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.empshow);
// TODO Auto-generated method stub
Intent show = getIntent();
}
}
How to generate a function that will algebraically encode a sequence?
How to generate a function that will algebraically encode a sequence?
Is there any way to generate a function F that, given a sequence, such as:
seq = [1 2 4 3 0 5 4 2 6]
Then F(seq) will return a function that generates that sequence? That is,
F(seq)(0) = 1
F(seq)(1) = 2
F(seq)(2) = 4
... and so on
Also, if it is, what is the function of lowest complexity that does so,
and what is the complexity of the generated functions?
EDIT It seems like I'm not clear, so I'll try to exemplify:
F(seq([1 3 5 7 9])}
# returns something like:
F(x) = 1 + 2*x
# limited to the domain x ¸ [1 2 3 4 5]
In other words, I want to compute a function that can be used to
algebraically, using mathematical functions such as +, *, etc, restore a
sequence of integers, even if you cleaned it from memory. I don't know if
it is possible, but, as one could easily code an approximation for such
function for trivial cases, I'm wondering how far it goes and if there is
some actual research concerning that.
EDIT 2 Answering another question, I'm only interested in sequences of
integers - if that is important.
Please let me know if it is still not clear!
Is there any way to generate a function F that, given a sequence, such as:
seq = [1 2 4 3 0 5 4 2 6]
Then F(seq) will return a function that generates that sequence? That is,
F(seq)(0) = 1
F(seq)(1) = 2
F(seq)(2) = 4
... and so on
Also, if it is, what is the function of lowest complexity that does so,
and what is the complexity of the generated functions?
EDIT It seems like I'm not clear, so I'll try to exemplify:
F(seq([1 3 5 7 9])}
# returns something like:
F(x) = 1 + 2*x
# limited to the domain x ¸ [1 2 3 4 5]
In other words, I want to compute a function that can be used to
algebraically, using mathematical functions such as +, *, etc, restore a
sequence of integers, even if you cleaned it from memory. I don't know if
it is possible, but, as one could easily code an approximation for such
function for trivial cases, I'm wondering how far it goes and if there is
some actual research concerning that.
EDIT 2 Answering another question, I'm only interested in sequences of
integers - if that is important.
Please let me know if it is still not clear!
Friday, 27 September 2013
How to do the following in case of Ruby on rails
How to do the following in case of Ruby on rails
How to do subdomains & seperated databases for a rails app as shown in
tutorial below for php
i am a newbie to to rails & ruby as well so i would like now that is any
thing possible which shown in this tutorial by anatgarg in php
1.subdomains 2.multiples databases 3.database switching based on subdomain
How to do subdomains & seperated databases for a rails app as shown in
tutorial below for php
i am a newbie to to rails & ruby as well so i would like now that is any
thing possible which shown in this tutorial by anatgarg in php
1.subdomains 2.multiples databases 3.database switching based on subdomain
Kohana welcome page not shown xampp
Kohana welcome page not shown xampp
My website path is c:\xamp\dhtdocs\egotist\kohana init \egotist\kohana\
RewriteBase /egotist/kohana/ RewriteRule
^(?:application|modules|system)\b.* index.php/$0 [L] Welcome controller
path C:\xampp\htdocs\egotist\kohana\application\classes\controller
Why when I load http://www.localhost:1337/egotist/kohana welcome
controller not shown
spent 3 days on this
I cannot post with localhost, I have to add www
My website path is c:\xamp\dhtdocs\egotist\kohana init \egotist\kohana\
RewriteBase /egotist/kohana/ RewriteRule
^(?:application|modules|system)\b.* index.php/$0 [L] Welcome controller
path C:\xampp\htdocs\egotist\kohana\application\classes\controller
Why when I load http://www.localhost:1337/egotist/kohana welcome
controller not shown
spent 3 days on this
I cannot post with localhost, I have to add www
Conditional select statement in SQL
Conditional select statement in SQL
Consider the following table (snapshot):
I would like to write a query to select rows from the table for which
At least 4 out of 7 column values (VAL, EQ, EFF, ..., SY) are not NULL..
Any idea how to do that?
Thanks!
Consider the following table (snapshot):
I would like to write a query to select rows from the table for which
At least 4 out of 7 column values (VAL, EQ, EFF, ..., SY) are not NULL..
Any idea how to do that?
Thanks!
Object reference not set to an instance of an object
Object reference not set to an instance of an object
The purpose of this program is to run through a range of pictureboxes and
set it's .image property to a particular image. I keep getting the error
"Object reference not set to an instance of an object". Coming from the
line that shows "DirectCast(Me.Controls(pic(i)), PictureBox).Image =
My.Resources.glass_buttonred"....Whats weird is if i move that code
outside of the for loop it runs just fine.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)
Handles Button1.Click
Dim pic(2) As Object
For i = 0 To 2
pic(i) = "picturebox" + Convert.ToString(i)
DirectCast(Me.Controls(pic(i)), PictureBox).Image =
My.Resources.glass_buttonred
Next
Label1.Text = pic(1)
End Sub
The purpose of this program is to run through a range of pictureboxes and
set it's .image property to a particular image. I keep getting the error
"Object reference not set to an instance of an object". Coming from the
line that shows "DirectCast(Me.Controls(pic(i)), PictureBox).Image =
My.Resources.glass_buttonred"....Whats weird is if i move that code
outside of the for loop it runs just fine.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs)
Handles Button1.Click
Dim pic(2) As Object
For i = 0 To 2
pic(i) = "picturebox" + Convert.ToString(i)
DirectCast(Me.Controls(pic(i)), PictureBox).Image =
My.Resources.glass_buttonred
Next
Label1.Text = pic(1)
End Sub
Creating Fragments from List with tabs
Creating Fragments from List with tabs
After way to long of a time between learning to code and now, I am trying
to create an Android app that is using a card list view and use tabs.
I want to be able to have the cards list in all 3 tabs but a different
list in each.Right now with what I have done, I get the same set in all 3
tabs. I know I am doing something wrong but after reading on Fragments and
tabs, I cannot figure out how to implement this.
I have the following in my MainActivity.
public class MainActivity extends FragmentActivity implements
Card.CardMenuListener<Card>{
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
private Drawable oldBackground = null;
private int currentColor = 0xFF3F9FE0;
@Override
public void onCreate(Bundle savedInstanceState) {
// This is quick way of theming the action bar without using
styles.xml (e.g. using ActionBar Style Generator)
getActionBar().setBackgroundDrawable(new
ColorDrawable(getResources().getColor(android.R.color.holo_blue_dark)));
getActionBar().setDisplayShowHomeEnabled(false);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new
MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
// Initializes a CardAdapter with a blue accent color and
basic popup menu for each card
CardAdapter<Card> cardsAdapter = new CardAdapter<Card>(this)
.setAccentColorRes(android.R.color.holo_blue_light)
.setPopupMenu(R.menu.card_popup, this);
cardsAdapter.add(new CardHeader(this, R.string.themeheader));
cardsAdapter.add(new Card("Action", "Launcher")
.setThumbnail(this,
R.drawable.apps_actionlauncherpro)); // sets
a thumbnail image from drawable resources
cardsAdapter.add(new Card("ADW", "Launcher")
.setThumbnail(this,
R.drawable.apps_adwex)); // sets a
thumbnail image from drawable
resources
cardsAdapter.add(new Card("Apex", "Launcher")
.setThumbnail(this,
R.drawable.apps_apexlauncher)); //
sets a thumbnail image from drawable
resources
cardsAdapter.add(new Card("Nova", "Launcher")
.setThumbnail(this,
R.drawable.apps_novalauncher)); //
sets a thumbnail image from drawable
resources
CardListView cardsList = (CardListView)
findViewById(R.id.cardsList);
cardsList.setAdapter(cardsAdapter);
final int pageMargin = (int)
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
}
@Override
public void onMenuItemClick(Card card, MenuItem item) {
Toast.makeText(this, card.getTitle() + ": " + item.getTitle(),
Toast.LENGTH_SHORT).show();
}
I have this to set the tabs to provide the 3 that I want
public class MyPagerAdapter extends FragmentPagerAdapter {
private final int[] TITLES = { R.string.tab1, R.string.tab2,
R.string.tab3 };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.tab1).toUpperCase(l);
case 1:
return getString(R.string.tab2).toUpperCase(l);
case 2:
return getString(R.string.tab3).toUpperCase(l);
}
return null;
}
@Override
public Fragment getItem(int position) {
Fragment f = new Fragment();
switch(position){
case 0:
f=ThemeCardFragment.newInstance(position);
break;
case 1:
f=ThemeCardFragment.newInstance(position);
break;
}
return f;
}
@Override
public int getCount() {
return TITLES.length;
}
I placed the following in my Fragment which I am sure is wrong.
public class ThemeCardFragment extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
public static ThemeCardFragment newInstance(int position) {
ThemeCardFragment f = new ThemeCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
FrameLayout fl = new FrameLayout(getActivity());
fl.setLayoutParams(params);
return fl;
}
}
I have tried to look at examples on here, tutorials and the Android dev
but I am missing something that would allow me to do this.
Realistically I would like to define the
("Action", "Launcher")
in the CardsAdapter as strings from my Strings.xml
Any insight to pointing me in the right direction would be appreciated. I
seem to keep heading in wrong directions and have spent at least 10 hours
trying to figure it out. Thanks.
After way to long of a time between learning to code and now, I am trying
to create an Android app that is using a card list view and use tabs.
I want to be able to have the cards list in all 3 tabs but a different
list in each.Right now with what I have done, I get the same set in all 3
tabs. I know I am doing something wrong but after reading on Fragments and
tabs, I cannot figure out how to implement this.
I have the following in my MainActivity.
public class MainActivity extends FragmentActivity implements
Card.CardMenuListener<Card>{
private final Handler handler = new Handler();
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private MyPagerAdapter adapter;
private Drawable oldBackground = null;
private int currentColor = 0xFF3F9FE0;
@Override
public void onCreate(Bundle savedInstanceState) {
// This is quick way of theming the action bar without using
styles.xml (e.g. using ActionBar Style Generator)
getActionBar().setBackgroundDrawable(new
ColorDrawable(getResources().getColor(android.R.color.holo_blue_dark)));
getActionBar().setDisplayShowHomeEnabled(false);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
pager = (ViewPager) findViewById(R.id.pager);
adapter = new
MyPagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
// Initializes a CardAdapter with a blue accent color and
basic popup menu for each card
CardAdapter<Card> cardsAdapter = new CardAdapter<Card>(this)
.setAccentColorRes(android.R.color.holo_blue_light)
.setPopupMenu(R.menu.card_popup, this);
cardsAdapter.add(new CardHeader(this, R.string.themeheader));
cardsAdapter.add(new Card("Action", "Launcher")
.setThumbnail(this,
R.drawable.apps_actionlauncherpro)); // sets
a thumbnail image from drawable resources
cardsAdapter.add(new Card("ADW", "Launcher")
.setThumbnail(this,
R.drawable.apps_adwex)); // sets a
thumbnail image from drawable
resources
cardsAdapter.add(new Card("Apex", "Launcher")
.setThumbnail(this,
R.drawable.apps_apexlauncher)); //
sets a thumbnail image from drawable
resources
cardsAdapter.add(new Card("Nova", "Launcher")
.setThumbnail(this,
R.drawable.apps_novalauncher)); //
sets a thumbnail image from drawable
resources
CardListView cardsList = (CardListView)
findViewById(R.id.cardsList);
cardsList.setAdapter(cardsAdapter);
final int pageMargin = (int)
TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
4, getResources()
.getDisplayMetrics());
pager.setPageMargin(pageMargin);
tabs.setViewPager(pager);
}
@Override
public void onMenuItemClick(Card card, MenuItem item) {
Toast.makeText(this, card.getTitle() + ": " + item.getTitle(),
Toast.LENGTH_SHORT).show();
}
I have this to set the tabs to provide the 3 that I want
public class MyPagerAdapter extends FragmentPagerAdapter {
private final int[] TITLES = { R.string.tab1, R.string.tab2,
R.string.tab3 };
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.tab1).toUpperCase(l);
case 1:
return getString(R.string.tab2).toUpperCase(l);
case 2:
return getString(R.string.tab3).toUpperCase(l);
}
return null;
}
@Override
public Fragment getItem(int position) {
Fragment f = new Fragment();
switch(position){
case 0:
f=ThemeCardFragment.newInstance(position);
break;
case 1:
f=ThemeCardFragment.newInstance(position);
break;
}
return f;
}
@Override
public int getCount() {
return TITLES.length;
}
I placed the following in my Fragment which I am sure is wrong.
public class ThemeCardFragment extends Fragment {
private static final String ARG_POSITION = "position";
private int position;
public static ThemeCardFragment newInstance(int position) {
ThemeCardFragment f = new ThemeCardFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
FrameLayout fl = new FrameLayout(getActivity());
fl.setLayoutParams(params);
return fl;
}
}
I have tried to look at examples on here, tutorials and the Android dev
but I am missing something that would allow me to do this.
Realistically I would like to define the
("Action", "Launcher")
in the CardsAdapter as strings from my Strings.xml
Any insight to pointing me in the right direction would be appreciated. I
seem to keep heading in wrong directions and have spent at least 10 hours
trying to figure it out. Thanks.
regex pattern for only number & dot & comma in java
regex pattern for only number & dot & comma in java
actually read all of the links regarding the pattern in java for using a
numbers including dot & comma but none of them works for me !!i want to
have some thing like this 1111111.2222222.
the number of digits is not important but i wanna use dot or comma in
between anywhere i would like . i already tried this
"^[0-9-\\+]([,.][0-9])?$"; but not works. & i visited the link below as
well Regex only numbers and dot or comma
actually read all of the links regarding the pattern in java for using a
numbers including dot & comma but none of them works for me !!i want to
have some thing like this 1111111.2222222.
the number of digits is not important but i wanna use dot or comma in
between anywhere i would like . i already tried this
"^[0-9-\\+]([,.][0-9])?$"; but not works. & i visited the link below as
well Regex only numbers and dot or comma
Thursday, 26 September 2013
App crash when receiving big file via bluetooth
App crash when receiving big file via bluetooth
package com.simonguest.btxfr;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
class DataTransferThread extends Thread {
private final String TAG = "android-btxfr/DataTransferThread";
private final BluetoothSocket socket;
private Handler handler;
public DataTransferThread(BluetoothSocket socket, Handler handler) {
this.socket = socket;
this.handler = handler;
}
public void run() {
try {
InputStream inputStream = socket.getInputStream();
boolean waitingForHeader = true;
ByteArrayOutputStream dataOutputStream = new ByteArrayOutputStream();
byte[] headerBytes = new byte[22];
byte[] digest = new byte[16];
int headerIndex = 0;
ProgressData progressData = new ProgressData();
while (true) {
if (waitingForHeader) {
byte[] header = new byte[1];
inputStream.read(header, 0, 1);
Log.v(TAG, "Received Header Byte: " + header[0]);
headerBytes[headerIndex++] = header[0];
if (headerIndex == 22) {
if ((headerBytes[0] == Constants.HEADER_MSB) &&
(headerBytes[1] == Constants.HEADER_LSB)) {
Log.v(TAG, "Header Received. Now obtaining length");
byte[] dataSizeBuffer =
Arrays.copyOfRange(headerBytes, 2, 6);
progressData.totalSize =
Utils.byteArrayToInt(dataSizeBuffer);
progressData.remainingSize = progressData.totalSize;
Log.v(TAG, "Data size: " + progressData.totalSize);
digest = Arrays.copyOfRange(headerBytes, 6, 22);
waitingForHeader = false;
sendProgress(progressData);
} else {
Log.e(TAG, "Did not receive correct header.
Closing socket");
socket.close();
handler.sendEmptyMessage(MessageType.INVALID_HEADER);
break;
}
}
} else {
// Read the data from the stream in chunks
byte[] buffer = new byte[Constants.CHUNK_SIZE];////////bfsize
Log.v(TAG, "Waiting for data. Expecting " +
progressData.remainingSize + " more bytes.");
int bytesRead = inputStream.read(buffer);
Log.v(TAG, "Read " + bytesRead + " bytes into buffer");
dataOutputStream.write(buffer, 0, bytesRead);
progressData.remainingSize -= bytesRead;
sendProgress(progressData);
if (progressData.remainingSize <= 0) {
Log.v(TAG, "Expected data has been received.");
break;
}
//System.gc();///////
}
}
// check the integrity of the data
final byte[] data = dataOutputStream.toByteArray();
if (Utils.digestMatch(data, digest)) {
Log.v(TAG, "Digest matches OK.");
Message message = new Message();
message.obj = data;
message.what = MessageType.DATA_RECEIVED;
handler.sendMessage(message);
// Send the digest back to the client as a confirmation
Log.v(TAG, "Sending back digest for confirmation");
OutputStream outputStream = socket.getOutputStream();
outputStream.write(digest);
} else {
Log.e(TAG, "Digest did not match. Corrupt transfer?");
handler.sendEmptyMessage(MessageType.DIGEST_DID_NOT_MATCH);
}
Log.v(TAG, "Closing server socket");
socket.close();
} catch (Exception ex) {
Log.d(TAG, ex.toString());
}
}
private void sendProgress(ProgressData progressData) {
Message message = new Message();
message.obj = progressData;
message.what = MessageType.DATA_PROGRESS_UPDATE;
handler.sendMessage(message);
}
}
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
from following code, i got crash when receiving large size file about 27
MB via bluetooth at progress upper 50%. can anyone please suggest me why
and how to fix it?Thank everyone.
package com.simonguest.btxfr;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
class DataTransferThread extends Thread {
private final String TAG = "android-btxfr/DataTransferThread";
private final BluetoothSocket socket;
private Handler handler;
public DataTransferThread(BluetoothSocket socket, Handler handler) {
this.socket = socket;
this.handler = handler;
}
public void run() {
try {
InputStream inputStream = socket.getInputStream();
boolean waitingForHeader = true;
ByteArrayOutputStream dataOutputStream = new ByteArrayOutputStream();
byte[] headerBytes = new byte[22];
byte[] digest = new byte[16];
int headerIndex = 0;
ProgressData progressData = new ProgressData();
while (true) {
if (waitingForHeader) {
byte[] header = new byte[1];
inputStream.read(header, 0, 1);
Log.v(TAG, "Received Header Byte: " + header[0]);
headerBytes[headerIndex++] = header[0];
if (headerIndex == 22) {
if ((headerBytes[0] == Constants.HEADER_MSB) &&
(headerBytes[1] == Constants.HEADER_LSB)) {
Log.v(TAG, "Header Received. Now obtaining length");
byte[] dataSizeBuffer =
Arrays.copyOfRange(headerBytes, 2, 6);
progressData.totalSize =
Utils.byteArrayToInt(dataSizeBuffer);
progressData.remainingSize = progressData.totalSize;
Log.v(TAG, "Data size: " + progressData.totalSize);
digest = Arrays.copyOfRange(headerBytes, 6, 22);
waitingForHeader = false;
sendProgress(progressData);
} else {
Log.e(TAG, "Did not receive correct header.
Closing socket");
socket.close();
handler.sendEmptyMessage(MessageType.INVALID_HEADER);
break;
}
}
} else {
// Read the data from the stream in chunks
byte[] buffer = new byte[Constants.CHUNK_SIZE];////////bfsize
Log.v(TAG, "Waiting for data. Expecting " +
progressData.remainingSize + " more bytes.");
int bytesRead = inputStream.read(buffer);
Log.v(TAG, "Read " + bytesRead + " bytes into buffer");
dataOutputStream.write(buffer, 0, bytesRead);
progressData.remainingSize -= bytesRead;
sendProgress(progressData);
if (progressData.remainingSize <= 0) {
Log.v(TAG, "Expected data has been received.");
break;
}
//System.gc();///////
}
}
// check the integrity of the data
final byte[] data = dataOutputStream.toByteArray();
if (Utils.digestMatch(data, digest)) {
Log.v(TAG, "Digest matches OK.");
Message message = new Message();
message.obj = data;
message.what = MessageType.DATA_RECEIVED;
handler.sendMessage(message);
// Send the digest back to the client as a confirmation
Log.v(TAG, "Sending back digest for confirmation");
OutputStream outputStream = socket.getOutputStream();
outputStream.write(digest);
} else {
Log.e(TAG, "Digest did not match. Corrupt transfer?");
handler.sendEmptyMessage(MessageType.DIGEST_DID_NOT_MATCH);
}
Log.v(TAG, "Closing server socket");
socket.close();
} catch (Exception ex) {
Log.d(TAG, ex.toString());
}
}
private void sendProgress(ProgressData progressData) {
Message message = new Message();
message.obj = progressData;
message.what = MessageType.DATA_PROGRESS_UPDATE;
handler.sendMessage(message);
}
}
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
from following code, i got crash when receiving large size file about 27
MB via bluetooth at progress upper 50%. can anyone please suggest me why
and how to fix it?Thank everyone.
Wednesday, 25 September 2013
How to handle column names not supported by sqldf in R
How to handle column names not supported by sqldf in R
I've a data frame where some of the column names are of the format .
format. For ex: Company.1 when i'm using that column in a sqldf function
it throws an error
data=sqldf(select Company.1 from test)
Error in sqliteExecStatement(con, statement, bind.data) :
RS-DBI driver: (error in statement: near ".1": syntax error)
Any workaround so that i can use the column name as it is?
I've a data frame where some of the column names are of the format .
format. For ex: Company.1 when i'm using that column in a sqldf function
it throws an error
data=sqldf(select Company.1 from test)
Error in sqliteExecStatement(con, statement, bind.data) :
RS-DBI driver: (error in statement: near ".1": syntax error)
Any workaround so that i can use the column name as it is?
Thursday, 19 September 2013
Scaling two items
Scaling two items
Imagine I have two boxes, one(A) has the following dimensions: width =
120, height = 80 and the other(B) has width = 300 and height 120. Using
the above values, how would I scale A to B's dimensions while maintaining
either the width or height of B. I want to maintain either of them. I have
been stuck on this problem and I am not very good with Math. Any help
would be appreciated.
Question: Does this require the use of an aspect ratio?
Imagine I have two boxes, one(A) has the following dimensions: width =
120, height = 80 and the other(B) has width = 300 and height 120. Using
the above values, how would I scale A to B's dimensions while maintaining
either the width or height of B. I want to maintain either of them. I have
been stuck on this problem and I am not very good with Math. Any help
would be appreciated.
Question: Does this require the use of an aspect ratio?
Call function in indexController from another controller Zend
Call function in indexController from another controller Zend
Need to call some function from another controller (not IndexController),
for example:
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$someFunction = new CustomController();
$someFunction->someFunc();
}
} But this throws an error :
Fatal error: Class 'CustomController' not found in
C:\xampp\htdocs\demo.ru\application\controllers\IndexController.php on
line 13
Need to call some function from another controller (not IndexController),
for example:
class IndexController extends Zend_Controller_Action
{
public function indexAction()
{
$someFunction = new CustomController();
$someFunction->someFunc();
}
} But this throws an error :
Fatal error: Class 'CustomController' not found in
C:\xampp\htdocs\demo.ru\application\controllers\IndexController.php on
line 13
How to handle requests with unsupported content type correctly?
How to handle requests with unsupported content type correctly?
I have a REST interface build with Jersey. Actually I only support as
content type only application/json for all incoming requests. That is why
I defined my message body reader and writer as
@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class MarshallerProvider
implements MessageBodyReader<Object>, MessageBodyWriter<Object>
{
}
Now I wrote a test where I try to get a document via GET and expected
content type application/xml. Jersey answers this request with an
MessageBodyProviderNotFoundException.
So what would be the best way to handle such unsupported requests
correctly? Should I write an exception mapper? Since it is an internal
exception I don't like this approach?
The solution should allow my to return an HTTP 415 (Unsupported Media Type).
I have a REST interface build with Jersey. Actually I only support as
content type only application/json for all incoming requests. That is why
I defined my message body reader and writer as
@Provider
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class MarshallerProvider
implements MessageBodyReader<Object>, MessageBodyWriter<Object>
{
}
Now I wrote a test where I try to get a document via GET and expected
content type application/xml. Jersey answers this request with an
MessageBodyProviderNotFoundException.
So what would be the best way to handle such unsupported requests
correctly? Should I write an exception mapper? Since it is an internal
exception I don't like this approach?
The solution should allow my to return an HTTP 415 (Unsupported Media Type).
Using Not In with a sub query
Using Not In with a sub query
I have the following query:
select *
from Table1 tb1
where ((tb1.Field1 + tb1.Field2 + tb1.Field3) not in
(
select (tb2.Field1 + tb2.Field2 + tb2.Field3)
from Table2 tb2 )
)
The query runs in about 10 seconds on sql server 2000, but on sql server
2005 it runs for hours. The machines are identical and both environments
have the same keys and indexes. Each table has about 350,000 records. The
only thing I can think of is sql2005 doesn't handle the concatenations the
same. I am working on an upgrade to sql2005 (haha, I wish it would be to
2008 or 2012 but that is out of my control). Any Ideas would greatly be
appreciated.
Thanks, Frank
I have the following query:
select *
from Table1 tb1
where ((tb1.Field1 + tb1.Field2 + tb1.Field3) not in
(
select (tb2.Field1 + tb2.Field2 + tb2.Field3)
from Table2 tb2 )
)
The query runs in about 10 seconds on sql server 2000, but on sql server
2005 it runs for hours. The machines are identical and both environments
have the same keys and indexes. Each table has about 350,000 records. The
only thing I can think of is sql2005 doesn't handle the concatenations the
same. I am working on an upgrade to sql2005 (haha, I wish it would be to
2008 or 2012 but that is out of my control). Any Ideas would greatly be
appreciated.
Thanks, Frank
How to use Dropbox Datastore API in Symfony2
How to use Dropbox Datastore API in Symfony2
I've developed an HTML5 app using Symfony2 with my own data model (using
Doctrine2). Right now, I want to integrate my app with others apps (for
iOS and Android), sharing and syncronizing the same data model, using
Dropbox Datastore API.
The apps for iOS and Android (developed by others) mentioned above are
working perfectly with Dropbox Datastore API.
I was reading the official documentation and I've seen that exists an SDK
for JS but I don't know if this SDK is valid for working with Symfony2
because I think the best way to call to the data model is in the
controllers (server side, via PHP) and not in views (client side, via JS).
Maybe exists a bundle for this functionality (I haven't found anything
about it) or a good way for work with this API in PHP or, maybe, it's
possible in JavaScript (recalling the app has been developed in Symfony).
Someone has tried that? What is the best way to work with that API and how
I can do it?
Thanks in advance!
I've developed an HTML5 app using Symfony2 with my own data model (using
Doctrine2). Right now, I want to integrate my app with others apps (for
iOS and Android), sharing and syncronizing the same data model, using
Dropbox Datastore API.
The apps for iOS and Android (developed by others) mentioned above are
working perfectly with Dropbox Datastore API.
I was reading the official documentation and I've seen that exists an SDK
for JS but I don't know if this SDK is valid for working with Symfony2
because I think the best way to call to the data model is in the
controllers (server side, via PHP) and not in views (client side, via JS).
Maybe exists a bundle for this functionality (I haven't found anything
about it) or a good way for work with this API in PHP or, maybe, it's
possible in JavaScript (recalling the app has been developed in Symfony).
Someone has tried that? What is the best way to work with that API and how
I can do it?
Thanks in advance!
Amazon S3 CORS (Cross-Origin Resource )
Amazon S3 CORS (Cross-Origin Resource )
I am using S3 + CORS + Jquery File upload to upload files to s3 directly
from the javascript. For those html5 supported browser I can get the file
size in javascript, however I have problem getting file size in IE9. Is it
possible so that when uploading file S3 can give me back the file size as
a part of response in IE9?
I am using S3 + CORS + Jquery File upload to upload files to s3 directly
from the javascript. For those html5 supported browser I can get the file
size in javascript, however I have problem getting file size in IE9. Is it
possible so that when uploading file S3 can give me back the file size as
a part of response in IE9?
Grails autocompile broken after upgrade from 2.1 to 2.2.4
Grails autocompile broken after upgrade from 2.1 to 2.2.4
I hope you might can help me.
I recently upgraded our grails project from version 2.1 to 2.2.4 and now
the autocompile/reload is broken => Everytime a make changes in
Controller/Services/Taglibs I have to restart the app to see them.
Console attributes like in this thread Grails autocompile not in
development environment don't work for me. I also did some research on
google but I couldn't find anything which helped.
Thanks for your help!
I hope you might can help me.
I recently upgraded our grails project from version 2.1 to 2.2.4 and now
the autocompile/reload is broken => Everytime a make changes in
Controller/Services/Taglibs I have to restart the app to see them.
Console attributes like in this thread Grails autocompile not in
development environment don't work for me. I also did some research on
google but I couldn't find anything which helped.
Thanks for your help!
Wednesday, 18 September 2013
need to print two different strings from a text file using tcl script
need to print two different strings from a text file using tcl script
I have arequirement to get two different strings from two consecutive
lines from a file using tcl script I tried following but it doesn't work.
So here below i need to print string "Clock" and "b0". I am able to print
Clock. but i need both "clock" "b0"
set f [eval exec "cat src.txt"]
set linenumber 0
while {[gets $f line] >= 0} {
incr linenumber
if {[string match "Clock" $line] >= 0 } {
# ignore by just going straight to the next loop iteration
while {[gets $f line] >= 0} {
incr linenumber
if { [string match "b0" $line"]} {
close $out
puts "final $line"
}
puts "\n$line"
continue
}
}
}
close $f
I have arequirement to get two different strings from two consecutive
lines from a file using tcl script I tried following but it doesn't work.
So here below i need to print string "Clock" and "b0". I am able to print
Clock. but i need both "clock" "b0"
set f [eval exec "cat src.txt"]
set linenumber 0
while {[gets $f line] >= 0} {
incr linenumber
if {[string match "Clock" $line] >= 0 } {
# ignore by just going straight to the next loop iteration
while {[gets $f line] >= 0} {
incr linenumber
if { [string match "b0" $line"]} {
close $out
puts "final $line"
}
puts "\n$line"
continue
}
}
}
close $f
Dividers on Horizontal Nav list
Dividers on Horizontal Nav list
My task is to input some horizontal bars between links on a simple,
unsorted nav list for my company's website.
I've tried each method listed on Vertical dividers on horizontal UL menu ,
to no avail. One of the links in that thread led me to
http://www.jackreichert.com/2011/07/31/how-to-add-a-divider-between-menu-items-in-css-using-only-one-selector/
, which worked!...kind of.
http://s21.postimg.org/nno183jl3/problems.jpg
That's what I'm getting right now: the dividers have moved off to the left
hand side of the nav list. At this point, I'm a little stumped, so I was
hoping you guys could help me out.
Here's the HTML. "cart_count.tpl" is the shopping cart stuff on the right.
<div style=float:right id="topbar">
<nav>
<div id="thisisthecartfunction" style=float:right>
{include file="cart_count.tpl"}</div>
<ul style=float:right>
<li><a href="/member">My Account</a></li>
<li><a href="/member_wishlist">Wish List</a></li>
<li><a href="/tracking">Order Status</a></li>
<li><a href="/category/customer-service">Customer Service</a></li>
</ul>
</nav>
</div>
And here's the CSS. I know it's a bit long and cluttered.
#container > header > #topbar { width: 100%; background: #f8f8f8; margin:
0 auto;}
#container > header > #topbar > nav { width: 980px; overflow: hidden;
margin: 0px auto;}
#container > header > #topbar > nav > div > #cartitems {vertical-align:
bottom; margin: 3px 0px 10px 10px; }
#container > header > #topbar > nav > ul {list-style-type: none; margin:
0; padding: 0;}
#container > header > #topbar > nav > ul > li {display:
inline;list-style-type: none;}
#container > header > #topbar > nav > ul > li+li { border-left: 1px solid
#000000 }
#container > header > #topbar > nav > ul > li > a {display: inline; float:
right; background: #f8f8f8; color: #666666; text-decoration: none;
vertical-align: bottom; margin: 5px 0px 10px 10px; }
#container > header > #topbar > nav > ul > li > a:hover { text-decoration:
underline; }
Any help would be greatly appreciated.
My task is to input some horizontal bars between links on a simple,
unsorted nav list for my company's website.
I've tried each method listed on Vertical dividers on horizontal UL menu ,
to no avail. One of the links in that thread led me to
http://www.jackreichert.com/2011/07/31/how-to-add-a-divider-between-menu-items-in-css-using-only-one-selector/
, which worked!...kind of.
http://s21.postimg.org/nno183jl3/problems.jpg
That's what I'm getting right now: the dividers have moved off to the left
hand side of the nav list. At this point, I'm a little stumped, so I was
hoping you guys could help me out.
Here's the HTML. "cart_count.tpl" is the shopping cart stuff on the right.
<div style=float:right id="topbar">
<nav>
<div id="thisisthecartfunction" style=float:right>
{include file="cart_count.tpl"}</div>
<ul style=float:right>
<li><a href="/member">My Account</a></li>
<li><a href="/member_wishlist">Wish List</a></li>
<li><a href="/tracking">Order Status</a></li>
<li><a href="/category/customer-service">Customer Service</a></li>
</ul>
</nav>
</div>
And here's the CSS. I know it's a bit long and cluttered.
#container > header > #topbar { width: 100%; background: #f8f8f8; margin:
0 auto;}
#container > header > #topbar > nav { width: 980px; overflow: hidden;
margin: 0px auto;}
#container > header > #topbar > nav > div > #cartitems {vertical-align:
bottom; margin: 3px 0px 10px 10px; }
#container > header > #topbar > nav > ul {list-style-type: none; margin:
0; padding: 0;}
#container > header > #topbar > nav > ul > li {display:
inline;list-style-type: none;}
#container > header > #topbar > nav > ul > li+li { border-left: 1px solid
#000000 }
#container > header > #topbar > nav > ul > li > a {display: inline; float:
right; background: #f8f8f8; color: #666666; text-decoration: none;
vertical-align: bottom; margin: 5px 0px 10px 10px; }
#container > header > #topbar > nav > ul > li > a:hover { text-decoration:
underline; }
Any help would be greatly appreciated.
What is the difference between a integer that is a string and a number that is just a string?
What is the difference between a integer that is a string and a number
that is just a string?
numbertwo = int(str(numberone[2]+numberone[1]+numberone[0]))
the above works but the bottom when run gives me an error why what is the
differnce
numbertwo = str(numberone[2]+numberone[1]+numberone[0]))
that is just a string?
numbertwo = int(str(numberone[2]+numberone[1]+numberone[0]))
the above works but the bottom when run gives me an error why what is the
differnce
numbertwo = str(numberone[2]+numberone[1]+numberone[0]))
Pattern Matching for java using regex
Pattern Matching for java using regex
I have a Long string that I have to parse for different keywords. For
example, I have the String:
"==References== This is a reference ==Further reading== *{{cite
book|editor1-last=Lukes|editor1-first=Steven|editor2-last=Carrithers|}} *
==External links=="
And my keywords are
'==References==' '==External links==' '==Further reading=='
I have tried a lot of combination of regex but i am not able to recover
all the strings.
the code i have tried:
Pattern pattern = Pattern.compile("\\=+[A-Za-z]\\=+");
Matcher matcher = pattern.matcher(textBuffer.toString());
while (matcher.find()) {
System.out.println(matcher.group(0));
}
I have a Long string that I have to parse for different keywords. For
example, I have the String:
"==References== This is a reference ==Further reading== *{{cite
book|editor1-last=Lukes|editor1-first=Steven|editor2-last=Carrithers|}} *
==External links=="
And my keywords are
'==References==' '==External links==' '==Further reading=='
I have tried a lot of combination of regex but i am not able to recover
all the strings.
the code i have tried:
Pattern pattern = Pattern.compile("\\=+[A-Za-z]\\=+");
Matcher matcher = pattern.matcher(textBuffer.toString());
while (matcher.find()) {
System.out.println(matcher.group(0));
}
Load Data in Divs on another page based on dropdown form selections
Load Data in Divs on another page based on dropdown form selections
I have a form that has 2 dropdown menu's:
<form id="form1">
<select name="sweets" id="sweets">
<option value="Cake">Cake</option>
<option value="Pie">Pie</option>
</select>
<select name="candy" id="candy">
<option value="Chocolate">Chocolate</option>
<option value="Gum">Gum</option>
</select>
<input type="submit" value="Submit">
</form>
Say that I select option 'Cake' in first dropdown and option 'Gum' in
second dropdown and hit submit, I would like to load 2 divs on the next
page i.e.
<div id="cake">some data</div> and <div id="gum">some data</div>
Since 'Pie' and 'Chocolate' weren't selected, I would not want them to
load any related data on the next page.
Similarly, if I choose 'Cake' and 'Chocolate', the related divs should
open up on the next page.
I'm trying to Load Data on another page based on multiple form selections.
I'm completely zonked and don't have a clue of how to pass data to another
page based on these dropdown selections. I have tried a bit of javascript
as well as php but didn't come close to any solution.
Can someone please help! Or point me out in the right direction. Thank you!
I have a form that has 2 dropdown menu's:
<form id="form1">
<select name="sweets" id="sweets">
<option value="Cake">Cake</option>
<option value="Pie">Pie</option>
</select>
<select name="candy" id="candy">
<option value="Chocolate">Chocolate</option>
<option value="Gum">Gum</option>
</select>
<input type="submit" value="Submit">
</form>
Say that I select option 'Cake' in first dropdown and option 'Gum' in
second dropdown and hit submit, I would like to load 2 divs on the next
page i.e.
<div id="cake">some data</div> and <div id="gum">some data</div>
Since 'Pie' and 'Chocolate' weren't selected, I would not want them to
load any related data on the next page.
Similarly, if I choose 'Cake' and 'Chocolate', the related divs should
open up on the next page.
I'm trying to Load Data on another page based on multiple form selections.
I'm completely zonked and don't have a clue of how to pass data to another
page based on these dropdown selections. I have tried a bit of javascript
as well as php but didn't come close to any solution.
Can someone please help! Or point me out in the right direction. Thank you!
Convert String to java.util.Date in the (yyyy-MM-dd) format
Convert String to java.util.Date in the (yyyy-MM-dd) format
I have a string in the form "2013-09-18". I want to convert it into a
java.util.Date. I am doing this
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date convertedCurrentDate = sdf.parse(currentDateText);
The convertedCurrentDate is coming as 'Wed Sep 18 00:00:00 IST 2013'
I want my output in the form '2013-09-18'
Hour, minutes and seconds shouldnt come and it should be in the form
yyyy-MM-dd.
I have a string in the form "2013-09-18". I want to convert it into a
java.util.Date. I am doing this
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date convertedCurrentDate = sdf.parse(currentDateText);
The convertedCurrentDate is coming as 'Wed Sep 18 00:00:00 IST 2013'
I want my output in the form '2013-09-18'
Hour, minutes and seconds shouldnt come and it should be in the form
yyyy-MM-dd.
Date formatter issue in iOS
Date formatter issue in iOS
I'm trying to set date-formatter for the time 01/09/13 20:55:00+02:00,
NSDateFormatter *departureFormatter = [[NSDateFormatter alloc] init];
[departureFormatter setDateFormat:@"dd/MM/yy HH:mm:ss+Z"];
NSDate *departureDate = [departureFormatter dateFromString:fullDateString];
but it's not succeeding.
Any pointers?
I'm trying to set date-formatter for the time 01/09/13 20:55:00+02:00,
NSDateFormatter *departureFormatter = [[NSDateFormatter alloc] init];
[departureFormatter setDateFormat:@"dd/MM/yy HH:mm:ss+Z"];
NSDate *departureDate = [departureFormatter dateFromString:fullDateString];
but it's not succeeding.
Any pointers?
Nohup is not working inside a for loop
Nohup is not working inside a for loop
I am trying to execute commands on multiple linux remote server. I have
written a shell script but it is not able to execute remote command. The
script is correctly reading username and ip from a config file but not
able to execute remote command.
interval==${1:-1}
delay=${2:-1800}
b=Server-
c=1
d=-
a=$(date +%Y-%m-%d-%H-%M)
INDEX=0
while read NAMES[${INDEX}] IP[${INDEX}]
do
((INDEX=$INDEX+1))
done < config
for (( i=0,j=i+1; i<${INDEX}; i++,j++ ))
do
echo "Server $j Username : "${NAMES[i]}
echo "Server $j IP : "${IP[i]}
file=$b$c$d$a
echo "Server $j file name : "$file
nohup ssh ${NAMES[i]}@${IP[i]} 'vmstat -n ${interval} ${delay} >
$file.csv' >& /dev/null &
let c++
done
In config file,entries are like "username ip" :
ajX 11.22.33.44
mnc 55.66.77.88
I don't get any error while executing my script. Output of Script is :
Server 1 Username : ajX
Server 1 IP : 11.22.33.44
Server 1 file name : Server-1-2013-09-18-07-39
Server 2 Username : mnc
Server 2 IP : 55.66.77.88
Server 2 file name : Server-2-2013-09-18-07-39
But on remote servers, commands are not executed but if I execute it
individually
nohup ssh ajx@11.22.33.44 'vmstat -n 1 30 > vmfile.csv' >& /dev/null &
it works fine. Does nohup doesn't work inside for loop or is there some
other way to do the same. Thanks in advance.
I am trying to execute commands on multiple linux remote server. I have
written a shell script but it is not able to execute remote command. The
script is correctly reading username and ip from a config file but not
able to execute remote command.
interval==${1:-1}
delay=${2:-1800}
b=Server-
c=1
d=-
a=$(date +%Y-%m-%d-%H-%M)
INDEX=0
while read NAMES[${INDEX}] IP[${INDEX}]
do
((INDEX=$INDEX+1))
done < config
for (( i=0,j=i+1; i<${INDEX}; i++,j++ ))
do
echo "Server $j Username : "${NAMES[i]}
echo "Server $j IP : "${IP[i]}
file=$b$c$d$a
echo "Server $j file name : "$file
nohup ssh ${NAMES[i]}@${IP[i]} 'vmstat -n ${interval} ${delay} >
$file.csv' >& /dev/null &
let c++
done
In config file,entries are like "username ip" :
ajX 11.22.33.44
mnc 55.66.77.88
I don't get any error while executing my script. Output of Script is :
Server 1 Username : ajX
Server 1 IP : 11.22.33.44
Server 1 file name : Server-1-2013-09-18-07-39
Server 2 Username : mnc
Server 2 IP : 55.66.77.88
Server 2 file name : Server-2-2013-09-18-07-39
But on remote servers, commands are not executed but if I execute it
individually
nohup ssh ajx@11.22.33.44 'vmstat -n 1 30 > vmfile.csv' >& /dev/null &
it works fine. Does nohup doesn't work inside for loop or is there some
other way to do the same. Thanks in advance.
Tuesday, 17 September 2013
How to check current date between two dates in ios?
How to check current date between two dates in ios?
I have two dates, starting date and ending date. Now i want to check
whether my current date is in between these two dates.
e.g. start date: 2013-09-17 15:05:00 +0000 end date: 013-09-25 17:05:00 +0000
I have two dates, starting date and ending date. Now i want to check
whether my current date is in between these two dates.
e.g. start date: 2013-09-17 15:05:00 +0000 end date: 013-09-25 17:05:00 +0000
how to create circular import from view to model in django?
how to create circular import from view to model in django?
So I know how to avoid this pitfall, what does a circular import look like
from a model to a view and view to model?
Also what would be a solution to the example given?
So I know how to avoid this pitfall, what does a circular import look like
from a model to a view and view to model?
Also what would be a solution to the example given?
Insert unique random numbers in array
Insert unique random numbers in array
Hi am newbie to algorithm and wanted to check if given an array of n
elements, what is the best way to fill random elements in it without any
duplication. I dont want to use the C++ STL containers, else I can surely
find a way around like using set and random_shuffle.
Also when I say, I want random numbers to fill in n blocks, it doesnt
necessarily mean 1 to n values . eg array of size 4 can have values
{3,214,5124,24}, not 1-4 Also I would be just using random function to
generate random number.
Hi am newbie to algorithm and wanted to check if given an array of n
elements, what is the best way to fill random elements in it without any
duplication. I dont want to use the C++ STL containers, else I can surely
find a way around like using set and random_shuffle.
Also when I say, I want random numbers to fill in n blocks, it doesnt
necessarily mean 1 to n values . eg array of size 4 can have values
{3,214,5124,24}, not 1-4 Also I would be just using random function to
generate random number.
VBA to create new worksheet and copy formats and values only
VBA to create new worksheet and copy formats and values only
I have a worksheet pulling Bloomberg data that is often shared with
non-Bloomberg users. As the data feed is only available from Bloomberg
terminals, I need to copy and past the worksheet to a new tab and have the
data static. I have added a button that will automatically copy and past
the format and values, then name the new tab based on the time it was
created.
Am struggling with the VBA code. Any thought?
I have a worksheet pulling Bloomberg data that is often shared with
non-Bloomberg users. As the data feed is only available from Bloomberg
terminals, I need to copy and past the worksheet to a new tab and have the
data static. I have added a button that will automatically copy and past
the format and values, then name the new tab based on the time it was
created.
Am struggling with the VBA code. Any thought?
JQuery Catergory Search with Remote Results and Cashing
JQuery Catergory Search with Remote Results and Cashing
I have looked extensively through SO and I have looked at many examples,
however I can not figure out how to get my project working as a whole.
Here is the code I am using:
http://jsfiddle.net/7mY3N/
HTML5:
<div class="ui-widget">
<label for="search">Search: </label>
<input id="search" />
<p id="empty-message"></p>
</div>
CSS3:
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center
no-repeat;
}
JQuery:
<script>
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category +
"</li>" );
currentCategory = item.category;
}
that._renderItemData( ul, item );
});
}
});
</script>
<script>
$(function() {
var cache ={};
$( "#search" ).catcomplete({
minLength: 0,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "search_basic.php", request, function( data,
status, xhr ) { // Remote results file is located at
search_basic.php
cache[ term ] = data;
response( data );
});
// If there are no results notify the user
if (ui.content.length === 0) {
$("#empty-message").text("No results found");
} else {
$("#empty-message").empty();
}
}
});
});
</script>
What I am trying to do is be able to search through results that are in
another file located at "/search_basic.php". I would like the results to
be categorized and cached in browser for future. If no results are
available, the user should also be notified. I am able to do each of these
separately except for pulling the results from a remote file and caching.
The following is the contents of search_basic.php:
header('Content-Type: application/json');
[
{ "label": "annhhx10", "category": "Products" },
{ "label": "annttop", "category": "Products" },
{ "label": "anders", "category": "People" },
{ "label": "andreas", "category": "People" }
]
If you don't mind walking me through how to get this working so that I can
learn from my mistake that would be great! Thank you!
I have looked extensively through SO and I have looked at many examples,
however I can not figure out how to get my project working as a whole.
Here is the code I am using:
http://jsfiddle.net/7mY3N/
HTML5:
<div class="ui-widget">
<label for="search">Search: </label>
<input id="search" />
<p id="empty-message"></p>
</div>
CSS3:
.ui-autocomplete-category {
font-weight: bold;
padding: .2em .4em;
margin: .8em 0 .2em;
line-height: 1.5;
}
.ui-autocomplete-loading {
background: white url('images/ui-anim_basic_16x16.gif') right center
no-repeat;
}
JQuery:
<script>
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var that = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category +
"</li>" );
currentCategory = item.category;
}
that._renderItemData( ul, item );
});
}
});
</script>
<script>
$(function() {
var cache ={};
$( "#search" ).catcomplete({
minLength: 0,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
$.getJSON( "search_basic.php", request, function( data,
status, xhr ) { // Remote results file is located at
search_basic.php
cache[ term ] = data;
response( data );
});
// If there are no results notify the user
if (ui.content.length === 0) {
$("#empty-message").text("No results found");
} else {
$("#empty-message").empty();
}
}
});
});
</script>
What I am trying to do is be able to search through results that are in
another file located at "/search_basic.php". I would like the results to
be categorized and cached in browser for future. If no results are
available, the user should also be notified. I am able to do each of these
separately except for pulling the results from a remote file and caching.
The following is the contents of search_basic.php:
header('Content-Type: application/json');
[
{ "label": "annhhx10", "category": "Products" },
{ "label": "annttop", "category": "Products" },
{ "label": "anders", "category": "People" },
{ "label": "andreas", "category": "People" }
]
If you don't mind walking me through how to get this working so that I can
learn from my mistake that would be great! Thank you!
preg_match_all get last match
preg_match_all get last match
Is it possible to get the last match using preg_match_all? Using this
regex will only return 126 81 and that's not what I'm after. In this case
I want 183 34 to be returned.
$string = 'Korpstigen 126 183 34 Kalmar';
preg_match_all("/[0-9]{5}|[0-9]{3} [0-9]{2}/", $string, $matches,
PREG_OFFSET_CAPTURE);
Is it possible to get the last match using preg_match_all? Using this
regex will only return 126 81 and that's not what I'm after. In this case
I want 183 34 to be returned.
$string = 'Korpstigen 126 183 34 Kalmar';
preg_match_all("/[0-9]{5}|[0-9]{3} [0-9]{2}/", $string, $matches,
PREG_OFFSET_CAPTURE);
Sunday, 15 September 2013
Code breakpoint
Code breakpoint
Hi I have a code that when I run quits and says there is a breakpoint
(void)checkCollision{
if(CGRectIntersectsRect(penny.frame, hand.frame))
{ [randomMain invalidate];
[startButton setHidden:NO];
pos= CGPointMake(0.0, 0.0);
CGRect frame = [penny frame];
frame.origin.x=137.0f;
frame.origin.y=326.0;
[penny setFrame:frame]; (the breakpoint is here)
CGRect frame2 = [hand frame];
frame2.origin.x=137.0f;
frame2.origin.y=20.0;
[hand setFrame:frame2];
`
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You Lose"
message:[NSString stringWithFormat:@"He got the penny!"] delegate:nil
cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[alert show];
[alert release];
} }
any ideas? i apologize for the sloppy format Im new to the website, thanks!
Hi I have a code that when I run quits and says there is a breakpoint
(void)checkCollision{
if(CGRectIntersectsRect(penny.frame, hand.frame))
{ [randomMain invalidate];
[startButton setHidden:NO];
pos= CGPointMake(0.0, 0.0);
CGRect frame = [penny frame];
frame.origin.x=137.0f;
frame.origin.y=326.0;
[penny setFrame:frame]; (the breakpoint is here)
CGRect frame2 = [hand frame];
frame2.origin.x=137.0f;
frame2.origin.y=20.0;
[hand setFrame:frame2];
`
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"You Lose"
message:[NSString stringWithFormat:@"He got the penny!"] delegate:nil
cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
[alert show];
[alert release];
} }
any ideas? i apologize for the sloppy format Im new to the website, thanks!
Paramter Binding not working in WebAPI
Paramter Binding not working in WebAPI
for below two controllers, /api/container/dasdada is returning "a". If i
do a container?value=hello i do get "hello". What can cause the parameter
binding not to work?
public HttpResponseMessage Get()
{
return Request.CreateResponse<string>("a");
}
public HttpResponseMessage Get(string value)
{
return Request.CreateResponse<string>(value);
}
I am using Katana to host it:
HttpConfiguration apiConfig = new HttpConfiguration();
apiConfig.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
apiConfig.Formatters.Remove(apiConfig.Formatters.XmlFormatter);
apiConfig.Formatters.JsonFormatter.SerializerSettings.ContractResolver
= new CamelCasePropertyNamesContractResolver();
app.UseDependencyResolver(resolver)
.UseWebApiWithOwinDependencyResolver(resolver, apiConfig);
app.UseWebApi(apiConfig);
for below two controllers, /api/container/dasdada is returning "a". If i
do a container?value=hello i do get "hello". What can cause the parameter
binding not to work?
public HttpResponseMessage Get()
{
return Request.CreateResponse<string>("a");
}
public HttpResponseMessage Get(string value)
{
return Request.CreateResponse<string>(value);
}
I am using Katana to host it:
HttpConfiguration apiConfig = new HttpConfiguration();
apiConfig.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
apiConfig.Formatters.Remove(apiConfig.Formatters.XmlFormatter);
apiConfig.Formatters.JsonFormatter.SerializerSettings.ContractResolver
= new CamelCasePropertyNamesContractResolver();
app.UseDependencyResolver(resolver)
.UseWebApiWithOwinDependencyResolver(resolver, apiConfig);
app.UseWebApi(apiConfig);
Format Exported Excel Results File with Macro in Imagej
Format Exported Excel Results File with Macro in Imagej
I have created a macro that generates many different data points in the
results window. For each image, a angle, lengths, etc. is generated. Is
there a way I can format the column headers in the exported excel results
file? For example, I have many different lengths generated in the macro,
but they import into the excel file on individual rows with repeating
image names. I would like each length in a different column corresponding
to the same image name.
This is what I get:
Label X Y Angle Length
1 IMG_1227.JPG 285 882 -48.406 714.025
2 IMG_1227.JPG 0 0 0 1003.544
3 IMG_1227.JPG 0 0 0 532
4 IMG_1227.JPG 0 0 0 5623
This is what I want:
Label X Y Angle Length1 LengthN LengthTot LengthSeg
1 IMG_1227.JPG 285 882 -48.406 714.025 1003.544 532 5632
It would be ideal to modify the macro I have to do this.
dir=getDirectory("image");
name = "Results";
index = lastIndexOf(name, "\\");
if (index!=-1) name = substring(name, 0, index);
name = name + ".xls"; ///can change xls to csv, txt, etc.
saveAs("Measurements", dir+name);
close();
}
run("Clear Results");
I have created a macro that generates many different data points in the
results window. For each image, a angle, lengths, etc. is generated. Is
there a way I can format the column headers in the exported excel results
file? For example, I have many different lengths generated in the macro,
but they import into the excel file on individual rows with repeating
image names. I would like each length in a different column corresponding
to the same image name.
This is what I get:
Label X Y Angle Length
1 IMG_1227.JPG 285 882 -48.406 714.025
2 IMG_1227.JPG 0 0 0 1003.544
3 IMG_1227.JPG 0 0 0 532
4 IMG_1227.JPG 0 0 0 5623
This is what I want:
Label X Y Angle Length1 LengthN LengthTot LengthSeg
1 IMG_1227.JPG 285 882 -48.406 714.025 1003.544 532 5632
It would be ideal to modify the macro I have to do this.
dir=getDirectory("image");
name = "Results";
index = lastIndexOf(name, "\\");
if (index!=-1) name = substring(name, 0, index);
name = name + ".xls"; ///can change xls to csv, txt, etc.
saveAs("Measurements", dir+name);
close();
}
run("Clear Results");
how to instantiate wtforms.ext.sqlalchemy.fields.QuerySelectMultipleField with SQLAlchemy many to many relationship
how to instantiate wtforms.ext.sqlalchemy.fields.QuerySelectMultipleField
with SQLAlchemy many to many relationship
I am attempting to display a list of checkboxes using
wtforms.ext.sqlalchemy QuerySelectMultipleField, but I cannot get the
model data to display on the form on a GET.
Here is my models.py
user_permissions = db.Table('user_permissions',
db.Column('permission_id', db.Integer, db.ForeignKey('permission.id')),
db.Column('user_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), nullable=False, unique=True)
email = db.Column(db.String(120), nullable=False, unique=True)
password = db.Column(db.String(80), nullable=False)
permissions = db.relationship('Permission', secondary=user_permissions,
backref=db.backref('permissions', lazy='dynamic'))
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
def __repr__(self):
return '<User %r>' % self.username
class Permission(db.Model):
id = db.Column(db.Integer, primary_key=True)
desc = db.Column(db.String(80), nullable=False)
def __init__(self, desc):
self.desc = desc
def __repr__(self):
return '<Permission %r>' % self.desc
Here is my forms.py
class EditUserForm(Form):
username = TextField('Name', validators=[DataRequired()])
email = TextField('Email', validators=[DataRequired()])
permissions = QuerySelectMultipleField(
query_factory=Permission.query.all,
get_label=lambda a: a.desc,
widget=widgets.ListWidget(prefix_label=False),
option_widget=widgets.CheckboxInput()
)
Here is my views.py
@app.endpoint('edit_user')
@require_login()
@require_permission('edit_user')
def edit_user(user_id):
user = User.query.filter_by(id=user_id).first()
if not user:
abort(404)
data = {
"username": user.username,
"email": user.email,
"permissions": user.permissions
}
form = EditUserForm(**data)
The problem, is that the WTForm doesn't display the selected values from
user.permissions, which is a list of Permission models. It displays a list
of empty checkboxes.
(Pdb) print user.permissions
[<Permission u'admin'>, <Permission u'create_user'>, <Permission
u'edit_user'>]
I am fairly certain the issue lies within how the "permissions" data value
is structured, but I have tried every possibility I can think of. Any help
would be appreciated.
with SQLAlchemy many to many relationship
I am attempting to display a list of checkboxes using
wtforms.ext.sqlalchemy QuerySelectMultipleField, but I cannot get the
model data to display on the form on a GET.
Here is my models.py
user_permissions = db.Table('user_permissions',
db.Column('permission_id', db.Integer, db.ForeignKey('permission.id')),
db.Column('user_id', db.Integer, db.ForeignKey('user.id'))
)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), nullable=False, unique=True)
email = db.Column(db.String(120), nullable=False, unique=True)
password = db.Column(db.String(80), nullable=False)
permissions = db.relationship('Permission', secondary=user_permissions,
backref=db.backref('permissions', lazy='dynamic'))
def __init__(self, username, email, password):
self.username = username
self.email = email
self.password = password
def __repr__(self):
return '<User %r>' % self.username
class Permission(db.Model):
id = db.Column(db.Integer, primary_key=True)
desc = db.Column(db.String(80), nullable=False)
def __init__(self, desc):
self.desc = desc
def __repr__(self):
return '<Permission %r>' % self.desc
Here is my forms.py
class EditUserForm(Form):
username = TextField('Name', validators=[DataRequired()])
email = TextField('Email', validators=[DataRequired()])
permissions = QuerySelectMultipleField(
query_factory=Permission.query.all,
get_label=lambda a: a.desc,
widget=widgets.ListWidget(prefix_label=False),
option_widget=widgets.CheckboxInput()
)
Here is my views.py
@app.endpoint('edit_user')
@require_login()
@require_permission('edit_user')
def edit_user(user_id):
user = User.query.filter_by(id=user_id).first()
if not user:
abort(404)
data = {
"username": user.username,
"email": user.email,
"permissions": user.permissions
}
form = EditUserForm(**data)
The problem, is that the WTForm doesn't display the selected values from
user.permissions, which is a list of Permission models. It displays a list
of empty checkboxes.
(Pdb) print user.permissions
[<Permission u'admin'>, <Permission u'create_user'>, <Permission
u'edit_user'>]
I am fairly certain the issue lies within how the "permissions" data value
is structured, but I have tried every possibility I can think of. Any help
would be appreciated.
Can't get responseText from $.post
Can't get responseText from $.post
I need to get a string from the server using jquery $.post, the issue is
that I can't get the responseText from it. So if I run
role = $.post('user_helper/return_current_role', {id: 3}, null,
"json").responseText;
console.log(role);
I get undefined If I try
role = $.post('user_helper/return_current_role', {id: 3}, null, "json");
console.log(role);
I get an object Object { readyState=1, getResponseHeader=function(),
getAllResponseHeaders=function(), more...}, where responceText is, for
example, teacher. Here is this response, copied from firebug:
readyState
4
responseText
"teacher"
status
200
statusText
"OK "
I need to get a string from the server using jquery $.post, the issue is
that I can't get the responseText from it. So if I run
role = $.post('user_helper/return_current_role', {id: 3}, null,
"json").responseText;
console.log(role);
I get undefined If I try
role = $.post('user_helper/return_current_role', {id: 3}, null, "json");
console.log(role);
I get an object Object { readyState=1, getResponseHeader=function(),
getAllResponseHeaders=function(), more...}, where responceText is, for
example, teacher. Here is this response, copied from firebug:
readyState
4
responseText
"teacher"
status
200
statusText
"OK "
SyntaxError: missing ; before statement Jquery
SyntaxError: missing ; before statement Jquery
i have a javascript file (generated dynamically from php with javascript
headers). Now this code results in error, i tried to debug for quite some
time without a clue:
Error: SyntaxError: missing ; before statement
document.write('$(function() '+
'{ $("#verify").click(function() '+
'{var order = ""; '+
'$(".captchaimage").each(function() '+
'{order += "ggggg"+ $(this).attr("name");}) '+
'console.log(order); '+
'$.ajax({ '+
'url: "http://healtheworld.com/own/json.php?var=" + order.substring(5), '+
'dataType: "text", '+
'cache: false, '+
'success: function(data){console.log(data);} }); '+
'}); '+
'});');
i have a javascript file (generated dynamically from php with javascript
headers). Now this code results in error, i tried to debug for quite some
time without a clue:
Error: SyntaxError: missing ; before statement
document.write('$(function() '+
'{ $("#verify").click(function() '+
'{var order = ""; '+
'$(".captchaimage").each(function() '+
'{order += "ggggg"+ $(this).attr("name");}) '+
'console.log(order); '+
'$.ajax({ '+
'url: "http://healtheworld.com/own/json.php?var=" + order.substring(5), '+
'dataType: "text", '+
'cache: false, '+
'success: function(data){console.log(data);} }); '+
'}); '+
'});');
how can I arrange this list of products in another column?
how can I arrange this list of products in another column?
Can any one please tell me how can I show the computers and its
subcategories in another column?
like next to cellphones category.
I only want to show two main categories on left (cell phones and cameras)
rest I want to show in another colum.
Images is showing hover state. When I hover over electronics I get that.
Furniture Living Room Bedroom Electronics Cell Phones Cameras
Accessories
Digital Cameras
Computers
Build Your Own
Laptops
Hard Drives
Monitors
RAM / Memory
Cases
Processors
Peripherals
Apparel Shirts Shoes
Mens
Womens
Hoodies
Can any one please tell me how can I show the computers and its
subcategories in another column?
like next to cellphones category.
I only want to show two main categories on left (cell phones and cameras)
rest I want to show in another colum.
Images is showing hover state. When I hover over electronics I get that.
Furniture Living Room Bedroom Electronics Cell Phones Cameras
Accessories
Digital Cameras
Computers
Build Your Own
Laptops
Hard Drives
Monitors
RAM / Memory
Cases
Processors
Peripherals
Apparel Shirts Shoes
Mens
Womens
Hoodies
Saturday, 14 September 2013
ajax.beginform to call many actions
ajax.beginform to call many actions
Can someone explain to me how (if possible) to call multiple actions using
one Ajax.BeginForm in an MVC4 view? Let me explain what I'm trying to do.
I have a form in my view that provides two parameters to the Controller.
In this view I also have four partial views to update when the form is
submitted. Each action returns a partial view that updates the 4 sections
of the page.
From what I understand, each Ajax.BeginForm can call one and only one
action on the Controller. What is the best way to update four partial
views on a page at the click of a button in the form?
Here is what my view looks like.
<div id="dayTab" data-metro-container="dashboardForm">
@using (Ajax.BeginForm("Products", "Dashboard", new AjaxOptions {
UpdateTargetId="ProductsDiv", OnComplete = "processDay" }))
{
<table>
<tr>@Html.ValidationSummary()</tr>
<tr>
<td>@Strings.LabelDashboardDate :
</td>
<td>
@Html.HiddenFor(model => model.DateRangeFilter)
@Html.TextBoxFor(model => model.DateRangeCriteria, new {
@class = "dateRangeClass" })
</td>
<td>
<input id="btnApply" type="submit" name="btnApply"
value="@Strings.LabelApply"
title="@Strings.TooltipDashboardApply" />
</td>
<td>
<span class="customNoWrap" data-metro-spinner="spinner"
style="display: none;">
<img
src="@ConfigurationCache.Settings.CSSPath/Content/themes/metro/Images/loading.gif")"
alt="" class="metroCenterTag"/>
</span>
</td>
</tr>
</table>
}
<div style="float:left;">
<div id="ProductsDiv">
@{ Html.RenderAction("Products"); }
</div>
<div id="QuantitiesDiv" style="height: 200px;">
@{ Html.RenderAction("Quantities"); }
</div>
</div>
<div style="float: left;">
<div id="PurchaseOrdersDiv" style="margin-left: 10px;">
@{ Html.RenderAction("PurchaseOrders"); }
</div>
<div id="BoxesDiv" style="margin-left: 10px;">
@{ Html.RenderAction("Boxes"); }
</div>
<div id="PalletsDiv" style="margin-left: 10px;">
@{ Html.RenderAction("Pallets"); }
</div>
</div>
<div style="clear: both"></div>
I actually have four tabs in a jQuery tab and each tab has the same
structure, same partial views. The form has to be submitted and updates
the 4 partial views in the current tab.
Can someone explain to me how (if possible) to call multiple actions using
one Ajax.BeginForm in an MVC4 view? Let me explain what I'm trying to do.
I have a form in my view that provides two parameters to the Controller.
In this view I also have four partial views to update when the form is
submitted. Each action returns a partial view that updates the 4 sections
of the page.
From what I understand, each Ajax.BeginForm can call one and only one
action on the Controller. What is the best way to update four partial
views on a page at the click of a button in the form?
Here is what my view looks like.
<div id="dayTab" data-metro-container="dashboardForm">
@using (Ajax.BeginForm("Products", "Dashboard", new AjaxOptions {
UpdateTargetId="ProductsDiv", OnComplete = "processDay" }))
{
<table>
<tr>@Html.ValidationSummary()</tr>
<tr>
<td>@Strings.LabelDashboardDate :
</td>
<td>
@Html.HiddenFor(model => model.DateRangeFilter)
@Html.TextBoxFor(model => model.DateRangeCriteria, new {
@class = "dateRangeClass" })
</td>
<td>
<input id="btnApply" type="submit" name="btnApply"
value="@Strings.LabelApply"
title="@Strings.TooltipDashboardApply" />
</td>
<td>
<span class="customNoWrap" data-metro-spinner="spinner"
style="display: none;">
<img
src="@ConfigurationCache.Settings.CSSPath/Content/themes/metro/Images/loading.gif")"
alt="" class="metroCenterTag"/>
</span>
</td>
</tr>
</table>
}
<div style="float:left;">
<div id="ProductsDiv">
@{ Html.RenderAction("Products"); }
</div>
<div id="QuantitiesDiv" style="height: 200px;">
@{ Html.RenderAction("Quantities"); }
</div>
</div>
<div style="float: left;">
<div id="PurchaseOrdersDiv" style="margin-left: 10px;">
@{ Html.RenderAction("PurchaseOrders"); }
</div>
<div id="BoxesDiv" style="margin-left: 10px;">
@{ Html.RenderAction("Boxes"); }
</div>
<div id="PalletsDiv" style="margin-left: 10px;">
@{ Html.RenderAction("Pallets"); }
</div>
</div>
<div style="clear: both"></div>
I actually have four tabs in a jQuery tab and each tab has the same
structure, same partial views. The form has to be submitted and updates
the 4 partial views in the current tab.
converting curl to ajax call
converting curl to ajax call
I have a curl call like this
curl -X GET \
-H "X-Parse-Application-Id: **************" \
-H "X-Parse-REST-API-Key: ************" \
-G \
--data-urlencode 'username=cooldude6' \
--data-urlencode 'password=p_n7!-e8' \
https://api.parse.com/1/login
I want this to make an ajax call. I know how to add the headers but what i
don't know is what to do with the "urlencode" arguments.
This is the method that i wrote to take care of the headers
function getResponse(type, url, data, responseHandler) {
var result = $.ajax(
{
url: url,
data: data,
processData: false,
type: type,
contentType: 'application/json',
async: false,
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader('X-Parse-Application-Id','**************');
xhr.setRequestHeader('X-Parse-REST-API-Key', '**************');
}
return result;
}
I have a curl call like this
curl -X GET \
-H "X-Parse-Application-Id: **************" \
-H "X-Parse-REST-API-Key: ************" \
-G \
--data-urlencode 'username=cooldude6' \
--data-urlencode 'password=p_n7!-e8' \
https://api.parse.com/1/login
I want this to make an ajax call. I know how to add the headers but what i
don't know is what to do with the "urlencode" arguments.
This is the method that i wrote to take care of the headers
function getResponse(type, url, data, responseHandler) {
var result = $.ajax(
{
url: url,
data: data,
processData: false,
type: type,
contentType: 'application/json',
async: false,
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader('X-Parse-Application-Id','**************');
xhr.setRequestHeader('X-Parse-REST-API-Key', '**************');
}
return result;
}
How Do I Route Audio to Speaker in iOS7?
How Do I Route Audio to Speaker in iOS7?
As AudioSessionSetProperty is deprecated, I'm trying to find an code
example of how to route audio to the speaker for iOS 7.
Previously I did the following:
-(void)setSpeakerEnabled
{
debugLog(@"%s",__FUNCTION__);
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (
kAudioSessionProperty_OverrideAudioRoute,
sizeof (audioRouteOverride),
&audioRouteOverride
);
}
Trying to get same result but without call to deprecated call to
AudioSessionSetProperty.
As AudioSessionSetProperty is deprecated, I'm trying to find an code
example of how to route audio to the speaker for iOS 7.
Previously I did the following:
-(void)setSpeakerEnabled
{
debugLog(@"%s",__FUNCTION__);
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (
kAudioSessionProperty_OverrideAudioRoute,
sizeof (audioRouteOverride),
&audioRouteOverride
);
}
Trying to get same result but without call to deprecated call to
AudioSessionSetProperty.
Call class method of Objective C category
Call class method of Objective C category
AFNetworking has a class method called + af_sharedImageCache that I want
to access from my own category, but I can't figure out the syntax to
reference this. Internally it is doing [[self class] af_sharedImageCache]
but obviously that's not gonna work for me. :)
AFNetworking has a class method called + af_sharedImageCache that I want
to access from my own category, but I can't figure out the syntax to
reference this. Internally it is doing [[self class] af_sharedImageCache]
but obviously that's not gonna work for me. :)
How can I determine an Entities' Attribute datatype in Core Data?
How can I determine an Entities' Attribute datatype in Core Data?
In Core Data I have an entity called item which has the the attribute score.
Currently score has the type int16_t.
scores value is updated from different places within the project, by
parsing it via [[UITextField text] integerValue], while keeping an open
eye for overflow.
scores datatype is very likely to change in the future. I want to minimise
future risk associated with that change.
The only way I can think of is by the preprocessor macro #define
itemScore_t int16_t.
Is there a better way, such as determining the datatype directly from Core
Data?
In Core Data I have an entity called item which has the the attribute score.
Currently score has the type int16_t.
scores value is updated from different places within the project, by
parsing it via [[UITextField text] integerValue], while keeping an open
eye for overflow.
scores datatype is very likely to change in the future. I want to minimise
future risk associated with that change.
The only way I can think of is by the preprocessor macro #define
itemScore_t int16_t.
Is there a better way, such as determining the datatype directly from Core
Data?
How to read this PHP array
How to read this PHP array
I'm creating this array:
foreach($html->find('.position4') as $test) {
$aanvaller['naam'] = $test->find('.col1', 0)->plaintext;
$aanvaller['club'] = $test->find('.col2', 0)->plaintext;
$aanvaller['type'] = 'Aanvaller';
$aanvaller['wedstrijden'] = $test->find('.col3', 0)->plaintext;
$aanvaller['goals'] = $test->find('.col4', 0)->plaintext;
$aanvaller['punten'] = $test->find('.col5', 0)->plaintext;
$aanvallers[] = $aanvaller;
}
When I use print_r($aanvallers) I get this:
Array ( [0] => Array (
[naam] => Catalin Tira
[club] => ADO
[type] => Aanvaller
[wedstrijden] => 0
[goals] => 0
[punten] => 0 )
and a lot more values. But the array is filled with the right values. Now
I want to ready the values using this:
for($i=0; $i<count($aanvallers); $i++){
echo $aanvallers[$i]->naam;
}
But when I use this, I don't get any values showed. So what am I doing wrong?
I'm creating this array:
foreach($html->find('.position4') as $test) {
$aanvaller['naam'] = $test->find('.col1', 0)->plaintext;
$aanvaller['club'] = $test->find('.col2', 0)->plaintext;
$aanvaller['type'] = 'Aanvaller';
$aanvaller['wedstrijden'] = $test->find('.col3', 0)->plaintext;
$aanvaller['goals'] = $test->find('.col4', 0)->plaintext;
$aanvaller['punten'] = $test->find('.col5', 0)->plaintext;
$aanvallers[] = $aanvaller;
}
When I use print_r($aanvallers) I get this:
Array ( [0] => Array (
[naam] => Catalin Tira
[club] => ADO
[type] => Aanvaller
[wedstrijden] => 0
[goals] => 0
[punten] => 0 )
and a lot more values. But the array is filled with the right values. Now
I want to ready the values using this:
for($i=0; $i<count($aanvallers); $i++){
echo $aanvallers[$i]->naam;
}
But when I use this, I don't get any values showed. So what am I doing wrong?
Jqm datebox dynamic adding in script highdays
Jqm datebox dynamic adding in script highdays
I want to high light the days in a calendar using script ...using array .
can some one post the example to high light the dates in the script using
options .
I want to high light the days in a calendar using script ...using array .
can some one post the example to high light the dates in the script using
options .
Friday, 13 September 2013
How to trace programs in turkik without accessid and password for aws amazon services?
How to trace programs in turkik without accessid and password for aws
amazon services?
Is there any way so that I can trace quick sort algorithm in Turkik
without access key and id of amazon services?
amazon services?
Is there any way so that I can trace quick sort algorithm in Turkik
without access key and id of amazon services?
Change color based on recursion depth Python Turtle
Change color based on recursion depth Python Turtle
I have a coding problem I'm having trouble with. I am learning recursion
and so far having a pretty good time with it. We've starting with basic
turtle drawings using the python turtle graphics module. I've got the
picture code down, but I'm also supposed to change the color of the
turtle's pen based on depth. My professor only briefly touched on mod (%)
to achieve this, but I have no idea where to begin and was hoping for some
assistance. Thanks in advance. I can't add pics because my rep isn't high
enough, but basically if you run the code it draws "S" figures. The first
"S" should be green, second two red, third three green, etc. Thanks again.
Here's the code:
from turtle import *
def drawzig2(depth,size):
if depth == 0:
pass
elif depth:
left(90)
fd(size/2)
right(90)
fd(size)
left(45)
drawzig2(depth-1,size/2)
right(45)
fd(-size)
left(90)
fd(-size)
right(90)
fd(-size)
left(45)
drawzig2(depth-1,size/2)
right(45)
fd(size)
left(90)
fd(size/2)
right(90)
drawzig2(4,100)
I have a coding problem I'm having trouble with. I am learning recursion
and so far having a pretty good time with it. We've starting with basic
turtle drawings using the python turtle graphics module. I've got the
picture code down, but I'm also supposed to change the color of the
turtle's pen based on depth. My professor only briefly touched on mod (%)
to achieve this, but I have no idea where to begin and was hoping for some
assistance. Thanks in advance. I can't add pics because my rep isn't high
enough, but basically if you run the code it draws "S" figures. The first
"S" should be green, second two red, third three green, etc. Thanks again.
Here's the code:
from turtle import *
def drawzig2(depth,size):
if depth == 0:
pass
elif depth:
left(90)
fd(size/2)
right(90)
fd(size)
left(45)
drawzig2(depth-1,size/2)
right(45)
fd(-size)
left(90)
fd(-size)
right(90)
fd(-size)
left(45)
drawzig2(depth-1,size/2)
right(45)
fd(size)
left(90)
fd(size/2)
right(90)
drawzig2(4,100)
PHP strcmp is not returning the correct answer with session variable
PHP strcmp is not returning the correct answer with session variable
I have a session variable $_SESSION['condition'], I know it is set because
when I entered this:
echo $_SESSION['condition']." = "."Below Average";
It returns:
Below Average = Below Average
When I do a gettype() on the session variable it returns type "string".
Yet when I do strcmp() it returns: -34
I have also tried an IF statement with == rather than strcmp testing for
equality AND an IF statement casting them both as strings and testing if
they are equal with no luck.
Any reason why this could be?
I have a session variable $_SESSION['condition'], I know it is set because
when I entered this:
echo $_SESSION['condition']." = "."Below Average";
It returns:
Below Average = Below Average
When I do a gettype() on the session variable it returns type "string".
Yet when I do strcmp() it returns: -34
I have also tried an IF statement with == rather than strcmp testing for
equality AND an IF statement casting them both as strings and testing if
they are equal with no luck.
Any reason why this could be?
Database design for a reservation system with assets which can travel between locations
Database design for a reservation system with assets which can travel
between locations
I'm developing a database structure which consists of assets which travel
between a couple of locations. I want to make a reservation system for
these assets. If assets don't travel between the different locations it's
very easy to get the availability: just check how many reservations for a
certain day exists and substract them from the normally available number
assets.
available = Normal.Available - already reserved
But the complicating factor is the fact people can travel between
different locations. A customer can pick up an asset at Location A and
drop it of at Location B. For instance pickup on september 13th 10:00am
dropoff at LocB september 13th 13:00.
If I now want to have the available assets at Location B at 13:00 this is
the normal available number +1 because of the asset which travelled from
A->B. The availability at location A is one less then normal, obviously.
How can I graph these movements in a database structure?
between locations
I'm developing a database structure which consists of assets which travel
between a couple of locations. I want to make a reservation system for
these assets. If assets don't travel between the different locations it's
very easy to get the availability: just check how many reservations for a
certain day exists and substract them from the normally available number
assets.
available = Normal.Available - already reserved
But the complicating factor is the fact people can travel between
different locations. A customer can pick up an asset at Location A and
drop it of at Location B. For instance pickup on september 13th 10:00am
dropoff at LocB september 13th 13:00.
If I now want to have the available assets at Location B at 13:00 this is
the normal available number +1 because of the asset which travelled from
A->B. The availability at location A is one less then normal, obviously.
How can I graph these movements in a database structure?
Showing a lot of points on Google Maps Android v2.0
Showing a lot of points on Google Maps Android v2.0
I have a lot of points to show on Google Maps Android. I decided to draw
them on the map by drawing circles with small radiuses. However, I noticed
that drawing a lot of circles (around 1000) is very slow and the app does
not respond well, even when the drawing is made in an AsyncTask. Any ideas
how to get around this?
I have a lot of points to show on Google Maps Android. I decided to draw
them on the map by drawing circles with small radiuses. However, I noticed
that drawing a lot of circles (around 1000) is very slow and the app does
not respond well, even when the drawing is made in an AsyncTask. Any ideas
how to get around this?
GWT+Eclipse without GWT_CONTAINER
GWT+Eclipse without GWT_CONTAINER
The situation
I'm using GWT with Eclipse and Google Plugin for Eclipse (GPE). Gradle is
the build tool and the Eclipse classpath is generated by Gradle. As I have
no "com.google.gwt.eclipse.core.GWT_CONTAINER" on my classpath, GPE always
shows the error "The project 'Test' does not have any GWT SDKs on its
build path" and the Console sometimes prints "GWT SDK not installed.".
Annother effect is that Eclipse doesn't let me GWT-compile the project
(but running dev mode works fine). But that one is ok for me, as I compile
using Gradle.
Things I'm aware of
I know that I can exclude all GWT depedencies from the Eclipse classpath
and add the container through Gradle (I did that for other projects). But
as I can't enforce the GWT version provided by Eclipse (I can only specify
the SDK's name in the classpath by adding the suffix "/" to the
conatiner), I think thats an ugly solution. Another point is that the GPE
update site only lists the latest GWT version available. There's no way to
automatically install an older version (yes you can provide one
externally).
When using GPE together with Maven and m2e it simply works: GPE links no
real SDK for Maven projects but there's a link to the "com.google.gwt"
group in the local Maven repository. But that's magic I can't use because:
Gradle's local repository format is different to Maven's
This logic is implemented in the plugin "com.google.gdt.eclipse.maven" and
I can't use that without adding a pom.xml to the project
The questions
Is there a possibility to deactivate this nasty error without loosing
other GPE features?
Is it possible to do something similar to what GPE+m2e does without
creating my own Eclipse plugin?
Am I right that excluding the jars and adding the container is the only
viable solution by now?
The situation
I'm using GWT with Eclipse and Google Plugin for Eclipse (GPE). Gradle is
the build tool and the Eclipse classpath is generated by Gradle. As I have
no "com.google.gwt.eclipse.core.GWT_CONTAINER" on my classpath, GPE always
shows the error "The project 'Test' does not have any GWT SDKs on its
build path" and the Console sometimes prints "GWT SDK not installed.".
Annother effect is that Eclipse doesn't let me GWT-compile the project
(but running dev mode works fine). But that one is ok for me, as I compile
using Gradle.
Things I'm aware of
I know that I can exclude all GWT depedencies from the Eclipse classpath
and add the container through Gradle (I did that for other projects). But
as I can't enforce the GWT version provided by Eclipse (I can only specify
the SDK's name in the classpath by adding the suffix "/" to the
conatiner), I think thats an ugly solution. Another point is that the GPE
update site only lists the latest GWT version available. There's no way to
automatically install an older version (yes you can provide one
externally).
When using GPE together with Maven and m2e it simply works: GPE links no
real SDK for Maven projects but there's a link to the "com.google.gwt"
group in the local Maven repository. But that's magic I can't use because:
Gradle's local repository format is different to Maven's
This logic is implemented in the plugin "com.google.gdt.eclipse.maven" and
I can't use that without adding a pom.xml to the project
The questions
Is there a possibility to deactivate this nasty error without loosing
other GPE features?
Is it possible to do something similar to what GPE+m2e does without
creating my own Eclipse plugin?
Am I right that excluding the jars and adding the container is the only
viable solution by now?
Facing difficulty in Installation of Interactive Ruby shell and ruby in ubuntu 13.04 and getting started with rails
Facing difficulty in Installation of Interactive Ruby shell and ruby in
ubuntu 13.04 and getting started with rails
Accidently I have installed both versions of ruby on my system and now the
default version is set to $ ruby -v ruby 1.9.3p194 (2012-04-20 revision
35410) [x86_64-linux] but I need to set the default version to 2.0.0...
for this I used the command $ rvm 2.0.0p294 --default but it says rvm is
not currently installed though I installed it, typing various commands(via
google) . Also I want to install an Integrated Ruby shell in ubuntu 13.04,
do suggest how to do it. I have also installed Aptana Studio on my system,
now how should I get started with it. Finally, the last problem is tell me
how to check whether rails is currently installed in my system or not...
Thanx in advance!!
ubuntu 13.04 and getting started with rails
Accidently I have installed both versions of ruby on my system and now the
default version is set to $ ruby -v ruby 1.9.3p194 (2012-04-20 revision
35410) [x86_64-linux] but I need to set the default version to 2.0.0...
for this I used the command $ rvm 2.0.0p294 --default but it says rvm is
not currently installed though I installed it, typing various commands(via
google) . Also I want to install an Integrated Ruby shell in ubuntu 13.04,
do suggest how to do it. I have also installed Aptana Studio on my system,
now how should I get started with it. Finally, the last problem is tell me
how to check whether rails is currently installed in my system or not...
Thanx in advance!!
Thursday, 12 September 2013
Rails - grouping by day for the last week, and adding them together
Rails - grouping by day for the last week, and adding them together
I'm trying to create an array that has the total of all sales a company
does for each day of the week. Right now I have something similar to this
@sales = Sale.all
@sales_total = @sales.map{|sale|sale.total.to_i}
Which returns an array of each total for every single sale.
Before turning it into an array, how can I group Sale by day, and adding
total together?
I'm trying to create an array that has the total of all sales a company
does for each day of the week. Right now I have something similar to this
@sales = Sale.all
@sales_total = @sales.map{|sale|sale.total.to_i}
Which returns an array of each total for every single sale.
Before turning it into an array, how can I group Sale by day, and adding
total together?
Rails 4: how to use $(document).ready() with turbo-links
Rails 4: how to use $(document).ready() with turbo-links
pI ran into an issue in my Rails 4 app while trying to organize JS files
the rails way. They were previously scattered across different views. I
organized them into separate files and compile them with the assets
pipeline. However, I just learned that jQuery's ready event doesn't fire
on subsequent clicks when turbo-linking is turned on. The first time you
load a page it works. But when you click a link, anything inside the
codeready( fucntion($) {/code won't get executed (because the page doesn't
actually load again). Good explanation: a
href=http://stackoverflow.com/questions/18769109/rails-4-turbo-link-error-uncaught-typeerror-cannot-read-property-position-of/18770219?noredirect=1#18770219here/a./p
pSo my question is: What is the right way to ensure that jquery events
work properly while turbo-links are on? Do you wrap the scripts in a
Rails-specific listener? Or maybe rails has some magic that makes it
unnecessary? The docs are a bit vague on how this should work, especially
with respect to loading multiple files via the manifest(s) like
application.js./p
pI ran into an issue in my Rails 4 app while trying to organize JS files
the rails way. They were previously scattered across different views. I
organized them into separate files and compile them with the assets
pipeline. However, I just learned that jQuery's ready event doesn't fire
on subsequent clicks when turbo-linking is turned on. The first time you
load a page it works. But when you click a link, anything inside the
codeready( fucntion($) {/code won't get executed (because the page doesn't
actually load again). Good explanation: a
href=http://stackoverflow.com/questions/18769109/rails-4-turbo-link-error-uncaught-typeerror-cannot-read-property-position-of/18770219?noredirect=1#18770219here/a./p
pSo my question is: What is the right way to ensure that jquery events
work properly while turbo-links are on? Do you wrap the scripts in a
Rails-specific listener? Or maybe rails has some magic that makes it
unnecessary? The docs are a bit vague on how this should work, especially
with respect to loading multiple files via the manifest(s) like
application.js./p
using extjs when json is dynamically passed pie-chart is not drawn
using extjs when json is dynamically passed pie-chart is not drawn
I've drawn the pie-chart successfully when i directly pass the data like
as shown below
data: [{
'name': 'metric one',
'data': 10
}, {
'name': 'metric two',
'data': 7
}, {
'name': 'metric three',
'data': 5
}, {
'name': 'metric four',
'data': 2
}, {
'name': 'metric five',
'data': 27
}]
});
but when i tried to bring those json datas through ajax i'm not getting
the pie-chart. can anyone please tell me some solution for this.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Ext.chart.series.Pie Example</title>
<link rel="stylesheet"
href="http://cdn.sencha.io/try/extjs/4.1.0/resources/css/ext-all-gray.css"/>
<script
src="http://cdn.sencha.io/try/extjs/4.1.0/ext-all-debug.js"></script>
<script src="extJS/app.js"></script>
</head>
<body>
<div id="myExample"></div>
</body>
</html>
app.js
Ext.onReady(function() {
Ext.Ajax.request({
url: 'getJsonforPie.action',
dataType : "json",
params: {
},
success: function(response){
getResources = response.responseText;
alert(JSON.stringify(getResources))
}
});
// var store = Ext.create('myStore');
//to load data use store.load()
var store = Ext.create('Ext.data.JsonStore', {
fields: ['name', 'data'],
data: getResources
// [{
// 'name': 'metric one',
// 'data': 10
// }, {
// 'name': 'metric two',
// 'data': 7
// }, {
// 'name': 'metric three',
// 'data': 5
// }, {
// 'name': 'metric four',
// 'data': 2
// }, {
// 'name': 'metric five',
// 'data': 27
// }]
});
Ext.create('Ext.chart.Chart', {
renderTo: 'myExample',
width: 500,
height: 350,
animate: true,
store: store,
theme: 'Base:gradients',
series: [{
type: 'pie',
angleField: 'data',
showInLegend: true,
tips: {
trackMouse: true,
width: 140,
height: 28,
renderer: function(storeItem, item) {
// calculate and display percentage on hover
var total = 0;
store.each(function(rec) {
total += rec.get('data');
});
this.setTitle(storeItem.get('name') + ': ' +
Math.round(storeItem.get('data') / total * 100) +
'%');
}
},
highlight: {
segment: {
margin: 20
}
},
label: {
field: 'name',
display: 'rotate',
contrast: true,
font: '18px Arial'
}
}]
});
});
struts.xml
<action name="getJsonforPie" class="commonpackage.DashboardUtilities"
method="getJsonforPie"/>
getJsonforPie method
public void getJsonforPie() throws IOException
{
HttpServletResponse response= (HttpServletResponse)
ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE);
JSONArray zoneAreas = new JSONArray();
for(int i=1;i<5;i++)
{
HashMap map=new HashMap();
map.put("name", "metric "+i);
map.put("data", 10);
zoneAreas.put(map);
}
System.out.println(zoneAreas.toString());
response.getWriter().write(zoneAreas.toString());
}
I've drawn the pie-chart successfully when i directly pass the data like
as shown below
data: [{
'name': 'metric one',
'data': 10
}, {
'name': 'metric two',
'data': 7
}, {
'name': 'metric three',
'data': 5
}, {
'name': 'metric four',
'data': 2
}, {
'name': 'metric five',
'data': 27
}]
});
but when i tried to bring those json datas through ajax i'm not getting
the pie-chart. can anyone please tell me some solution for this.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Ext.chart.series.Pie Example</title>
<link rel="stylesheet"
href="http://cdn.sencha.io/try/extjs/4.1.0/resources/css/ext-all-gray.css"/>
<script
src="http://cdn.sencha.io/try/extjs/4.1.0/ext-all-debug.js"></script>
<script src="extJS/app.js"></script>
</head>
<body>
<div id="myExample"></div>
</body>
</html>
app.js
Ext.onReady(function() {
Ext.Ajax.request({
url: 'getJsonforPie.action',
dataType : "json",
params: {
},
success: function(response){
getResources = response.responseText;
alert(JSON.stringify(getResources))
}
});
// var store = Ext.create('myStore');
//to load data use store.load()
var store = Ext.create('Ext.data.JsonStore', {
fields: ['name', 'data'],
data: getResources
// [{
// 'name': 'metric one',
// 'data': 10
// }, {
// 'name': 'metric two',
// 'data': 7
// }, {
// 'name': 'metric three',
// 'data': 5
// }, {
// 'name': 'metric four',
// 'data': 2
// }, {
// 'name': 'metric five',
// 'data': 27
// }]
});
Ext.create('Ext.chart.Chart', {
renderTo: 'myExample',
width: 500,
height: 350,
animate: true,
store: store,
theme: 'Base:gradients',
series: [{
type: 'pie',
angleField: 'data',
showInLegend: true,
tips: {
trackMouse: true,
width: 140,
height: 28,
renderer: function(storeItem, item) {
// calculate and display percentage on hover
var total = 0;
store.each(function(rec) {
total += rec.get('data');
});
this.setTitle(storeItem.get('name') + ': ' +
Math.round(storeItem.get('data') / total * 100) +
'%');
}
},
highlight: {
segment: {
margin: 20
}
},
label: {
field: 'name',
display: 'rotate',
contrast: true,
font: '18px Arial'
}
}]
});
});
struts.xml
<action name="getJsonforPie" class="commonpackage.DashboardUtilities"
method="getJsonforPie"/>
getJsonforPie method
public void getJsonforPie() throws IOException
{
HttpServletResponse response= (HttpServletResponse)
ActionContext.getContext().get(StrutsStatics.HTTP_RESPONSE);
JSONArray zoneAreas = new JSONArray();
for(int i=1;i<5;i++)
{
HashMap map=new HashMap();
map.put("name", "metric "+i);
map.put("data", 10);
zoneAreas.put(map);
}
System.out.println(zoneAreas.toString());
response.getWriter().write(zoneAreas.toString());
}
Python text to xml converting solutions
Python text to xml converting solutions
Hi guys i have write some code in python and its look like :
! /usr/bin/env python
import re
output = open('epg.xml','w') n = 0 print >> output, ''+'\t' print >>
output, ''
with open('epg_slo_utf_xml.txt','r') as txt: for line in txt: if
re.search('Program', line) !=None:
n =n + 1 e =''+line+''
if re.search('Start', line) !=None:
n = n + 1
f ='<start>'+line+'</start>'
if re.search('duration', line) !=None:
n = n + 1
g ='<duration>'+line+'<duration>'
wo = e + f
print >> output, wo
print >> output , '
But when I wanna add code for discovering Duration from my text file, like
this:
if re.search('duration', line) !=None: n = n + 1 g =''+line+''
And when I run script i get this error message :
Traceback (most recent call last):
File "./epg_transform.py", line 25, in <module>
wo = e + f + g
NameError: name 'g' is not defined
My text file look's like this :
Program 5
Start 2013-09-12 05:30:00
Duration 06:15:00
Title INFOCANALE
Program 6
Start 2013-09-12 06:40:00
Duration 00:50:00
Title Vihar
Program 9
Start 2013-09-12 06:45:00
Duration 00:29:00
Title TV prodaja
Program 7
Program 6
Program 13
Start 2013-09-12 06:20:00
Duration 00:50:00
Title Kursadije
I think that problem is when re.search find Program but without other
element's in text file or maybe Program with multiplay start, duration,
title like:
Program 7
Start 2013-09-16 00:10:00 Duration 02:00:00 Title Love TV
Start 2013-09-16 02:10:00 Duration 01:50:00 Title Noèna ptica
Thx, for reading and can you help me with this problem?
Hi guys i have write some code in python and its look like :
! /usr/bin/env python
import re
output = open('epg.xml','w') n = 0 print >> output, ''+'\t' print >>
output, ''
with open('epg_slo_utf_xml.txt','r') as txt: for line in txt: if
re.search('Program', line) !=None:
n =n + 1 e =''+line+''
if re.search('Start', line) !=None:
n = n + 1
f ='<start>'+line+'</start>'
if re.search('duration', line) !=None:
n = n + 1
g ='<duration>'+line+'<duration>'
wo = e + f
print >> output, wo
print >> output , '
But when I wanna add code for discovering Duration from my text file, like
this:
if re.search('duration', line) !=None: n = n + 1 g =''+line+''
And when I run script i get this error message :
Traceback (most recent call last):
File "./epg_transform.py", line 25, in <module>
wo = e + f + g
NameError: name 'g' is not defined
My text file look's like this :
Program 5
Start 2013-09-12 05:30:00
Duration 06:15:00
Title INFOCANALE
Program 6
Start 2013-09-12 06:40:00
Duration 00:50:00
Title Vihar
Program 9
Start 2013-09-12 06:45:00
Duration 00:29:00
Title TV prodaja
Program 7
Program 6
Program 13
Start 2013-09-12 06:20:00
Duration 00:50:00
Title Kursadije
I think that problem is when re.search find Program but without other
element's in text file or maybe Program with multiplay start, duration,
title like:
Program 7
Start 2013-09-16 00:10:00 Duration 02:00:00 Title Love TV
Start 2013-09-16 02:10:00 Duration 01:50:00 Title Noèna ptica
Thx, for reading and can you help me with this problem?
How to save the data from DataGridView1 to SQL using this code?
How to save the data from DataGridView1 to SQL using this code?
I want to save my data to SQL using this code that contains for loop but I
found this problem "Input string was not in a correct format.".
private void btnDataSave_Click(object sender, EventArgs e)
{
using (SqlConnection CN = new SqlConnection(txtConString.Text))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = CN;
command.CommandText = "insert into MRRDataStore(id, unit,
qty, desc, remark) values(@id, @unit, @qty, @desc,
@remark)";
CN.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow)
{
int id;
string unit;
string qty;
string desc;
string remark;
for (int i = 0; i <= dataGridView1.Rows.Count - 1;
i++)
{
id =
int.Parse(dataGridView1.Rows[i].Cells["Id"].Value.ToString());
unit =
dataGridView1.Rows[i].Cells["Unit"].Value.ToString();
qty =
dataGridView1.Rows[i].Cells["Qty"].Value.ToString();
desc =
dataGridView1.Rows[i].Cells["ItemDesc"].Value.ToString();
remark =
dataGridView1.Rows[i].Cells["Remarks"].Value.ToString();
}
}
}
}
}
}
I want to save my data to SQL using this code that contains for loop but I
found this problem "Input string was not in a correct format.".
private void btnDataSave_Click(object sender, EventArgs e)
{
using (SqlConnection CN = new SqlConnection(txtConString.Text))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = CN;
command.CommandText = "insert into MRRDataStore(id, unit,
qty, desc, remark) values(@id, @unit, @qty, @desc,
@remark)";
CN.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (!row.IsNewRow)
{
int id;
string unit;
string qty;
string desc;
string remark;
for (int i = 0; i <= dataGridView1.Rows.Count - 1;
i++)
{
id =
int.Parse(dataGridView1.Rows[i].Cells["Id"].Value.ToString());
unit =
dataGridView1.Rows[i].Cells["Unit"].Value.ToString();
qty =
dataGridView1.Rows[i].Cells["Qty"].Value.ToString();
desc =
dataGridView1.Rows[i].Cells["ItemDesc"].Value.ToString();
remark =
dataGridView1.Rows[i].Cells["Remarks"].Value.ToString();
}
}
}
}
}
}
Wednesday, 11 September 2013
How I realize master page in Rails just as in .NET
How I realize master page in Rails just as in .NET
so,I am a beginner,I know there is layout in rails .
but I want a shared part that many pages will use,include all of the mvc
other than just v .just like the master page in .Net webform.
for example .every site will own may manage pages,and this pages will use
a common left sidebar which is consists of a few menus.
how can I realize this?
so,I am a beginner,I know there is layout in rails .
but I want a shared part that many pages will use,include all of the mvc
other than just v .just like the master page in .Net webform.
for example .every site will own may manage pages,and this pages will use
a common left sidebar which is consists of a few menus.
how can I realize this?
css: correct way to put a div element right down to another div (which is not right next in the html)
css: correct way to put a div element right down to another div (which is
not right next in the html)
Let's say we have something like:
<div id="1" class="A"> </div>
<div id="2" class="B"> </div>
<div id="3" class="C"> </div>
How could we put the div with id 3 right down to the div with id 1?
I tried to do it with negative margins:
.C{
margin-top:-45px;
}
It usually looks good:
But sometimes, if I resize the font with the internet browser, it looks bad:
not right next in the html)
Let's say we have something like:
<div id="1" class="A"> </div>
<div id="2" class="B"> </div>
<div id="3" class="C"> </div>
How could we put the div with id 3 right down to the div with id 1?
I tried to do it with negative margins:
.C{
margin-top:-45px;
}
It usually looks good:
But sometimes, if I resize the font with the internet browser, it looks bad:
Ruby print function
Ruby print function
# Call the each method of each collection in turn.
# This is not a parallel iteration and does not require enumerators.
def sequence(*enumerables, &block)
enumerables.each do |enumerable|
enumerable.each(&block)
end
end
# Examples of how these iterator methods work
a,b,c = [1,2,3],4..6,'a'..'e'
print "#{sequence(a,b,c) {|x| print x}}\n"
why the results is:
123456abcde[[1, 2, 3], 4..6, "a".."e"]
anyone could tell me why [[1, 2, 3], 4..6, "a".."e"] is getting printed?
or tell me why the return value of the 'sequence' method is [[1, 2, 3],
4..6, "a".."e"]?? Many thanks
# Call the each method of each collection in turn.
# This is not a parallel iteration and does not require enumerators.
def sequence(*enumerables, &block)
enumerables.each do |enumerable|
enumerable.each(&block)
end
end
# Examples of how these iterator methods work
a,b,c = [1,2,3],4..6,'a'..'e'
print "#{sequence(a,b,c) {|x| print x}}\n"
why the results is:
123456abcde[[1, 2, 3], 4..6, "a".."e"]
anyone could tell me why [[1, 2, 3], 4..6, "a".."e"] is getting printed?
or tell me why the return value of the 'sequence' method is [[1, 2, 3],
4..6, "a".."e"]?? Many thanks
Flex Boxes wont translate into Mozilla
Flex Boxes wont translate into Mozilla
Hard to link this into js fiddle but ill try and explain.
Heres My Portfolio
In the portfolio section you can see in webkit the .flex-item portfolio
items stack and change width when the window is resized. but in mozilla it
seems to stick to 1 width and remains floated left.
VERY new to the whole flex idea, and as you can see my code is a little
sloppy.
any advice will help allot to try and translate my website to mozilla
browsers
Hard to link this into js fiddle but ill try and explain.
Heres My Portfolio
In the portfolio section you can see in webkit the .flex-item portfolio
items stack and change width when the window is resized. but in mozilla it
seems to stick to 1 width and remains floated left.
VERY new to the whole flex idea, and as you can see my code is a little
sloppy.
any advice will help allot to try and translate my website to mozilla
browsers
Successful Ajax post displays error message
Successful Ajax post displays error message
My form properly submits data via POST utilizing Ajax. However I am trying
to redirect the user upon successful submission. The problem is, even
though the form successfully submits, instead of redirecting the user it
displays an error. According to firebug the page I am submitting to, is
throwing up a 200 success code. I am using jquery 1.8.3.
My Code:
$(document).ready(function() {
$("#form4").submit(function(e) {
e.preventDefault();
var frm = $('#form4');
$.ajax({
type: 'POST',
url: 'http://requestb.in',
data: frm.serialize(),
success : function() {
window.location = "http://www.google.com";
},
/*error : function() {
alert("Something went bad");
}*/
});
});
Here is my form HTML:
<form action="" method="post" id="form4" name="form4"
enctype="multipart/form-data">
<input id="name" name="name" type="text" tabindex="1" value="Insert
your name" class="required">
<input id="email" name="email" type="text" tabindex="2" value="Insert
your e-mail" class="required email">
<input id="phone" name="phone" type="text" tabindex="3" value="Insert
your phone number">
<input type="submit" name="submit_button" value="Try it free">
</form>
In an attempt to figure out the exact error, I added the following code to
the top of my script, which I found from this POST:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
After adding that code, that following error I get is from the first error
code check: 'Not connect.\n Verify Network.'. I tested this is both
firefox and Chrome with same results.
My form properly submits data via POST utilizing Ajax. However I am trying
to redirect the user upon successful submission. The problem is, even
though the form successfully submits, instead of redirecting the user it
displays an error. According to firebug the page I am submitting to, is
throwing up a 200 success code. I am using jquery 1.8.3.
My Code:
$(document).ready(function() {
$("#form4").submit(function(e) {
e.preventDefault();
var frm = $('#form4');
$.ajax({
type: 'POST',
url: 'http://requestb.in',
data: frm.serialize(),
success : function() {
window.location = "http://www.google.com";
},
/*error : function() {
alert("Something went bad");
}*/
});
});
Here is my form HTML:
<form action="" method="post" id="form4" name="form4"
enctype="multipart/form-data">
<input id="name" name="name" type="text" tabindex="1" value="Insert
your name" class="required">
<input id="email" name="email" type="text" tabindex="2" value="Insert
your e-mail" class="required email">
<input id="phone" name="phone" type="text" tabindex="3" value="Insert
your phone number">
<input type="submit" name="submit_button" value="Try it free">
</form>
In an attempt to figure out the exact error, I added the following code to
the top of my script, which I found from this POST:
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
After adding that code, that following error I get is from the first error
code check: 'Not connect.\n Verify Network.'. I tested this is both
firefox and Chrome with same results.
replace() does not take into consideration the "g" flag when used with string instead of regex
replace() does not take into consideration the "g" flag when used with
string instead of regex
var a = 'Construction,Airports,Construction|Commercial
Construction,Construction|Education,Construction|Healthcare,Construction|Housing,Construction|Industrial
Construction,Construction|Other,Construction|Ports,Construction|Rail,Construction|Residential
Construction,Construction|Roads & Bridges,Social Infrastructure|Commercial
Construction,Social Infrastructure|Education,Social
Infrastructure|Healthcare,Social Infrastructure|Housing,Social
Infrastructure|Other,Social Infrastructure|Residential Construction';
alert(a.replace('|', ',', 'g'));
On chrome, it is replacing only the first occurrence of |, while using the
g flag in the regex form of the replace() function, it replaces all the
occurrences:
alert(a.replace(/\|/g, ',', 'g'));
Can anyone please help me understand if I'm doing something wrong in the
first form of the replace? is that the intended behavior or is it a bug?
string instead of regex
var a = 'Construction,Airports,Construction|Commercial
Construction,Construction|Education,Construction|Healthcare,Construction|Housing,Construction|Industrial
Construction,Construction|Other,Construction|Ports,Construction|Rail,Construction|Residential
Construction,Construction|Roads & Bridges,Social Infrastructure|Commercial
Construction,Social Infrastructure|Education,Social
Infrastructure|Healthcare,Social Infrastructure|Housing,Social
Infrastructure|Other,Social Infrastructure|Residential Construction';
alert(a.replace('|', ',', 'g'));
On chrome, it is replacing only the first occurrence of |, while using the
g flag in the regex form of the replace() function, it replaces all the
occurrences:
alert(a.replace(/\|/g, ',', 'g'));
Can anyone please help me understand if I'm doing something wrong in the
first form of the replace? is that the intended behavior or is it a bug?
PandaBoard running Ubunto + Java App with 200 Threads
PandaBoard running Ubunto + Java App with 200 Threads
I'm developing a distributed application where a PandaBoard MASTER have to
be a server with approximately 200 peers... And I was thinking in the
performance of having 200 threads (one per peer)... basically in the start
of the day I can config to distribute the information to 10 peer and after
more 10 peer successively... so, transfer all command/files on the
start...
And the rest of the day just have to be all connected making nothing... if
someone disconnect this PandaBoard MASTER have to put in a log file that
peer x was disconnected.
Someone can tell me if it works fine?? Would I have some problem?
PandaBoard Config:
Dual-core ARM® Cortex™-A9 MPCore™ with Symmetric Multiprocessing (SMP) at
1GHz each;
1GB low power DDR2 RAM;
Full size SD/MMC card cage with support for High-Speed & High-Capacity SD
cards;
Wireless.
I'm developing a distributed application where a PandaBoard MASTER have to
be a server with approximately 200 peers... And I was thinking in the
performance of having 200 threads (one per peer)... basically in the start
of the day I can config to distribute the information to 10 peer and after
more 10 peer successively... so, transfer all command/files on the
start...
And the rest of the day just have to be all connected making nothing... if
someone disconnect this PandaBoard MASTER have to put in a log file that
peer x was disconnected.
Someone can tell me if it works fine?? Would I have some problem?
PandaBoard Config:
Dual-core ARM® Cortex™-A9 MPCore™ with Symmetric Multiprocessing (SMP) at
1GHz each;
1GB low power DDR2 RAM;
Full size SD/MMC card cage with support for High-Speed & High-Capacity SD
cards;
Wireless.
Subscribe to:
Posts (Atom)