How can I fix this error with the booting sequence
Ubuntu will not boot from my computer even after installing.
http://paste.ubuntu.com/616784/
Monday, 30 September 2013
About the existence of a generic point on an irreducible closed subset of a prescheme
About the existence of a generic point on an irreducible closed subset of
a prescheme
This is Proposition 2 on page 81 of Mumford's The Red Book of Varieties
and Schemes:
Let $X$ be a prescheme, and $Z \subset X$ an irreducible closed subset.
Then there is one and only one point $z \in Z$ such that $Z = \overline{\{
z \}}$.
Proof. Let $U \subset X$ be an open affine set such that $Z \cap U \neq
\emptyset$. Then any point $z \in Z$ dense in $Z$ must be in $Z \cap U$;
and a point $z \in Z \cap U$ whose closure contains $Z \cap U$ is also
dense in $Z$. Therefore it suffices to prove the theorem for the closed
subset $Z \cap U$. But by Prop. 1 of section 4 there is a unique $z \in Z
\cap U$ dense in $Z \cap U$.
I have some questions about this proof.
Why does every dense point in $Z$ lie in $Z \cap U$?
Why must $z \in Z \cap U$ whose closure contains $Z \cap U$ be dense in $Z$?
Why is there a unique $z \in Z \cap U$ dense in $Z \cap U$? I can't find
the proposition the author mentioned.
I think these are concerned with affineness, but I don't know the exact
reason.
Thanks for everyone.
a prescheme
This is Proposition 2 on page 81 of Mumford's The Red Book of Varieties
and Schemes:
Let $X$ be a prescheme, and $Z \subset X$ an irreducible closed subset.
Then there is one and only one point $z \in Z$ such that $Z = \overline{\{
z \}}$.
Proof. Let $U \subset X$ be an open affine set such that $Z \cap U \neq
\emptyset$. Then any point $z \in Z$ dense in $Z$ must be in $Z \cap U$;
and a point $z \in Z \cap U$ whose closure contains $Z \cap U$ is also
dense in $Z$. Therefore it suffices to prove the theorem for the closed
subset $Z \cap U$. But by Prop. 1 of section 4 there is a unique $z \in Z
\cap U$ dense in $Z \cap U$.
I have some questions about this proof.
Why does every dense point in $Z$ lie in $Z \cap U$?
Why must $z \in Z \cap U$ whose closure contains $Z \cap U$ be dense in $Z$?
Why is there a unique $z \in Z \cap U$ dense in $Z \cap U$? I can't find
the proposition the author mentioned.
I think these are concerned with affineness, but I don't know the exact
reason.
Thanks for everyone.
VBA Objected Required Error
VBA Objected Required Error
I have a function that creates a text file for the directory location and
then calls a batch script that I wrote. I keep getting the object required
error and am having difficulty troubleshooting it.
Sub fncNewDirectoryLocation()
Set sC = Sheets("Control")
Dim FolderName As String
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
On Error Resume Next
FolderName = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End With
fncDeleteDirectoryLocation
fncCreateDirectoryLocation (FolderName)
fncCallExtractAndDelete
End Sub
Sub fncDeleteDirectoryLocation()
On Error Resume Next
Kill (ThisWorkbook.Path & "\drive_path.txt")
End Sub
Sub fncCreateDirectoryLocation(folderLocation As String)
Set FS = CreateObject("Scripting.FileSystemObject")
Set a = FS.CreateTextFile(ThisWorkbook.Path & "\drive_path.txt", True)
a.WriteLine (folderLocation)
a.Close
End Sub
Sub fncShellAndWait(script As String)
Dim cmdline As String: cmdline = "cmd.exe /k " & """" & "cd /d " & "" &
Environ("temp") & " && " & script & """"
Dim x As Integer
x = ShellAndWait.ShellAndWait(cmdline, 21600000, vbMinimizedFocus,
AbandonWait)
End Sub
Sub fncCallExtractAndDelete()
fncShellAndWait ("ExtractAndDelete.bat")
End Sub
I have a function that creates a text file for the directory location and
then calls a batch script that I wrote. I keep getting the object required
error and am having difficulty troubleshooting it.
Sub fncNewDirectoryLocation()
Set sC = Sheets("Control")
Dim FolderName As String
With Application.FileDialog(msoFileDialogFolderPicker)
.AllowMultiSelect = False
.Show
On Error Resume Next
FolderName = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End With
fncDeleteDirectoryLocation
fncCreateDirectoryLocation (FolderName)
fncCallExtractAndDelete
End Sub
Sub fncDeleteDirectoryLocation()
On Error Resume Next
Kill (ThisWorkbook.Path & "\drive_path.txt")
End Sub
Sub fncCreateDirectoryLocation(folderLocation As String)
Set FS = CreateObject("Scripting.FileSystemObject")
Set a = FS.CreateTextFile(ThisWorkbook.Path & "\drive_path.txt", True)
a.WriteLine (folderLocation)
a.Close
End Sub
Sub fncShellAndWait(script As String)
Dim cmdline As String: cmdline = "cmd.exe /k " & """" & "cd /d " & "" &
Environ("temp") & " && " & script & """"
Dim x As Integer
x = ShellAndWait.ShellAndWait(cmdline, 21600000, vbMinimizedFocus,
AbandonWait)
End Sub
Sub fncCallExtractAndDelete()
fncShellAndWait ("ExtractAndDelete.bat")
End Sub
Change content of the same column and write to the same file
Change content of the same column and write to the same file
I wanted to change the content of column 2(a single character) of every
line in a file into alphabet "k", here is my code:
f = open('test.txt')
f_str = f.readlines()
f.close()
for line in f_str:
s = list(line)
s[1] = "k"
line = ''.join(s)
print line
f = open('test.txt', 'w')
f.writelines(f_str)
f.close()
I managed to change the content in the for loop(the print result shows
that), but I failed to write the changed result to the file. Please, any
suggestions will be greatly appreciated.
I wanted to change the content of column 2(a single character) of every
line in a file into alphabet "k", here is my code:
f = open('test.txt')
f_str = f.readlines()
f.close()
for line in f_str:
s = list(line)
s[1] = "k"
line = ''.join(s)
print line
f = open('test.txt', 'w')
f.writelines(f_str)
f.close()
I managed to change the content in the for loop(the print result shows
that), but I failed to write the changed result to the file. Please, any
suggestions will be greatly appreciated.
Sunday, 29 September 2013
Targeting single directory for rewrite rule
Targeting single directory for rewrite rule
I need a rewrite rule to act on just one directory. I have tried:
RewriteCond %{REQUEST_URI} ^/test_db RewriteRule ^([^/])/([^/])/$
/test_db/main.php?page=$1&dep_id=$2 [L]
The conditional is doing something as the rewrite rule is not being
applied outside of test_db but its also not doing anything to files
requested in test_db either. Any idea how to make this work?
I need a rewrite rule to act on just one directory. I have tried:
RewriteCond %{REQUEST_URI} ^/test_db RewriteRule ^([^/])/([^/])/$
/test_db/main.php?page=$1&dep_id=$2 [L]
The conditional is doing something as the rewrite rule is not being
applied outside of test_db but its also not doing anything to files
requested in test_db either. Any idea how to make this work?
Bootstrap static navbar force expand on small screen
Bootstrap static navbar force expand on small screen
Given this menu code from a boostrap template, I want each menu item to
both stack and take up the full width when the screen size is detected to
be small. Essentially, identical functionality to when the "triple bar"
menu button is hit, except the user does not have to manually press it.
Thanks in advance.
<!-- Static navbar -->
<div class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
Given this menu code from a boostrap template, I want each menu item to
both stack and take up the full width when the screen size is detected to
be small. Essentially, identical functionality to when the "triple bar"
menu button is hit, except the user does not have to manually press it.
Thanks in advance.
<!-- Static navbar -->
<div class="navbar navbar-default">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
</div><!--/.nav-collapse -->
</div>
how do i edit the input fields of paypal sanbox?
how do i edit the input fields of paypal sanbox?
WeBoss - Downpayment Combat P1,000.00 PHP Battlefield P1,500.00 PHP
Warfield P2,100.00 PHP Cancel
i would like to edit the price, how would i do that? and also i tried in
"BUY NOW" button and change amount but still it wont change the price.
is there a way to edit the paypal sandbox page?
WeBoss - Downpayment Combat P1,000.00 PHP Battlefield P1,500.00 PHP
Warfield P2,100.00 PHP Cancel
i would like to edit the price, how would i do that? and also i tried in
"BUY NOW" button and change amount but still it wont change the price.
is there a way to edit the paypal sandbox page?
Tomcat use of static variables
Tomcat use of static variables
Is it possible to use static variables in my project to store data for all
Servlets (they are in one .war file) and different requests? (It's not
data that belongs to a distinct session)
Is it possible to use static variables in my project to store data for all
Servlets (they are in one .war file) and different requests? (It's not
data that belongs to a distinct session)
Saturday, 28 September 2013
sum of datetime.datetime object gave an error TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
sum of datetime.datetime object gave an error TypeError: unsupported
operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
I'm trying to sum a list of datetime.datetime object using :
from datetime import datetime, timedelta
d= [datetime.datetime(2013, 5, 1, 9, 31, 24), datetime.datetime(2013, 6,
11, 17, 22, 18), datetime.datetime(2013, 4, 3, 16, 6, 59)]
sum_d = sum(d, timedelta())
I get the error :
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and
'datetime.datetime'
any idea how to sum up this list?
Thanks!
operand type(s) for +: 'datetime.datetime' and 'datetime.datetime'
I'm trying to sum a list of datetime.datetime object using :
from datetime import datetime, timedelta
d= [datetime.datetime(2013, 5, 1, 9, 31, 24), datetime.datetime(2013, 6,
11, 17, 22, 18), datetime.datetime(2013, 4, 3, 16, 6, 59)]
sum_d = sum(d, timedelta())
I get the error :
TypeError: unsupported operand type(s) for +: 'datetime.datetime' and
'datetime.datetime'
any idea how to sum up this list?
Thanks!
Explanation for Tomcat server
Explanation for Tomcat server
How does a tomcat server load the different servlets? are they all in one
vm? so when I create a Object in one Request, does it still exist in the
other one? and does the same thing apply to different servlets?
How does a tomcat server load the different servlets? are they all in one
vm? so when I create a Object in one Request, does it still exist in the
other one? and does the same thing apply to different servlets?
How can I trigger heapification of a PriorityQueue?
How can I trigger heapification of a PriorityQueue?
I'm using the following code for a PriorityQueue<Node<T>>, where Node<T>
is not Comparable:
final Map<Node<T>, Double> distances = new HashMap<>();
PriorityQueue<Node<T>> queue = new PriorityQueue<Node<T>>(graph
.getNodes().size(), new Comparator<Node<T>>() {
@Override
public int compare(Node<T> o1, Node<T> o2) {
return distances.get(o1).compareTo(distances.get(o2));
}
});
Later in my code, I modify the distances of the nodes in the map with
distances.put(...). How can I ensure that the priority queue is updated
correctly to reflect the new sort order?
I've looked at the source for PriorityQueue and see that its peek, poll,
and element methods all just get queue[0], but I don't know how to update
the order of the queue, as the internal method heapify is private.
I'm using the following code for a PriorityQueue<Node<T>>, where Node<T>
is not Comparable:
final Map<Node<T>, Double> distances = new HashMap<>();
PriorityQueue<Node<T>> queue = new PriorityQueue<Node<T>>(graph
.getNodes().size(), new Comparator<Node<T>>() {
@Override
public int compare(Node<T> o1, Node<T> o2) {
return distances.get(o1).compareTo(distances.get(o2));
}
});
Later in my code, I modify the distances of the nodes in the map with
distances.put(...). How can I ensure that the priority queue is updated
correctly to reflect the new sort order?
I've looked at the source for PriorityQueue and see that its peek, poll,
and element methods all just get queue[0], but I don't know how to update
the order of the queue, as the internal method heapify is private.
Sort filename like abc 1.1, abc 1.1.1, abc 1.0 in PHP
Sort filename like abc 1.1, abc 1.1.1, abc 1.0 in PHP
I have used natsort(), but it didn't work as I want to have.
It display sorted array like this:
1) abc 1.0
2) abc 1.1.1
3) abc 1.1
But I want:
1) abc 1.0
2) abc 1.1
3) abc 1.1.1
So, please tell what is the possible solution of this in php
I have used natsort(), but it didn't work as I want to have.
It display sorted array like this:
1) abc 1.0
2) abc 1.1.1
3) abc 1.1
But I want:
1) abc 1.0
2) abc 1.1
3) abc 1.1.1
So, please tell what is the possible solution of this in php
Friday, 27 September 2013
Compressing audio files simlar to transfer from server to client
Compressing audio files simlar to transfer from server to client
In my project, I need to be able to compress small audio files so that it
can be transferred easily from server to the client. I found We Chat uses
audio compression closest to my requirement. But I couldn't find ways of
doing it
I'm able to write code for image compression by reducing resolution and
clarity. What should I try here ? combine two frames into one etc.
Streaming is definitely possible if two frames are mixed into one. I want
to know if there are any well developed libraries to do the same. I'm easy
on the format until client side is able to read it. I also want to know if
streaming is possible in compressed format.
In my project, I need to be able to compress small audio files so that it
can be transferred easily from server to the client. I found We Chat uses
audio compression closest to my requirement. But I couldn't find ways of
doing it
I'm able to write code for image compression by reducing resolution and
clarity. What should I try here ? combine two frames into one etc.
Streaming is definitely possible if two frames are mixed into one. I want
to know if there are any well developed libraries to do the same. I'm easy
on the format until client side is able to read it. I also want to know if
streaming is possible in compressed format.
Change WordPress theme layout
Change WordPress theme layout
I started a new website on wordpress and I want to modify the theme that I
use.
My current site:
http://www.abyssalcoding.com/pictr1.png
http://www.abyssalcoding.com/pictr2.png
How I want it: http://www.abyssalcoding.com/pictr3.png
So the 3rd picture shows that I want to move the main content box a little
to the left. I tried it by using positioning and I broke my site. Can you
guide me through the process of doing this?
I started a new website on wordpress and I want to modify the theme that I
use.
My current site:
http://www.abyssalcoding.com/pictr1.png
http://www.abyssalcoding.com/pictr2.png
How I want it: http://www.abyssalcoding.com/pictr3.png
So the 3rd picture shows that I want to move the main content box a little
to the left. I tried it by using positioning and I broke my site. Can you
guide me through the process of doing this?
d3 dendogram, is there a way to make a single node standout?
d3 dendogram, is there a way to make a single node standout?
I am using this exact code into our website (code is at the bottom of the
webpage)
http://bl.ocks.org/mbostock/4063570
I am wondering if there is a way to add a json attribute to send back and
modify the javascript such that one node is much much more bold than all
the other nodes(perhaps a bigger circle or bigger bold font) such that it
is obvious that this is the selected node.
thanks, Dean
I am using this exact code into our website (code is at the bottom of the
webpage)
http://bl.ocks.org/mbostock/4063570
I am wondering if there is a way to add a json attribute to send back and
modify the javascript such that one node is much much more bold than all
the other nodes(perhaps a bigger circle or bigger bold font) such that it
is obvious that this is the selected node.
thanks, Dean
Django 1.5.4 moving from Dev to Production (APACHE)
Django 1.5.4 moving from Dev to Production (APACHE)
i have followed this link http://www.youtube.com/watch?v=hBMVVruB9Vs but
it does not work ok. if i go for firstweb.com, it take me to APACHE's
welcome page not DJANGO's welcome page.
i am using it code Need a minimal Django file upload example.
please help with a proper deployment of apache.
i have followed this link http://www.youtube.com/watch?v=hBMVVruB9Vs but
it does not work ok. if i go for firstweb.com, it take me to APACHE's
welcome page not DJANGO's welcome page.
i am using it code Need a minimal Django file upload example.
please help with a proper deployment of apache.
socket connection fails in php script while it works in terminal
socket connection fails in php script while it works in terminal
That is the script I have
<?php
$timeout =- 10;
$target = "tls://testbed-epp.nominet.org.uk:700";
$result = stream_socket_client($target, $errno, $errstr, 30,
STREAM_CLIENT_CONNECT);
if ($result === False) {
throw new Exception("Error connecting to $target: $errstr (code
$errno)");
}
echo "Connected";
And it throws an exception
Error connecting to tls://testbed-epp.nominet.org.uk:700: (code 0)
At the same time running
openssl s_client -connect testbed-epp.nominet.org.uk:700
in a terminal connects flawlessly.
Any ideas will be appreciated
That is the script I have
<?php
$timeout =- 10;
$target = "tls://testbed-epp.nominet.org.uk:700";
$result = stream_socket_client($target, $errno, $errstr, 30,
STREAM_CLIENT_CONNECT);
if ($result === False) {
throw new Exception("Error connecting to $target: $errstr (code
$errno)");
}
echo "Connected";
And it throws an exception
Error connecting to tls://testbed-epp.nominet.org.uk:700: (code 0)
At the same time running
openssl s_client -connect testbed-epp.nominet.org.uk:700
in a terminal connects flawlessly.
Any ideas will be appreciated
jQuery UI DatePicker From and To
jQuery UI DatePicker From and To
I have somethinng like below, and wanted to make sure from date shall not
overpass to date which is not selectable(even after changing the date) and
vice versa.
From: <input type="text" id="xx_from" value="<?php echo $date_from; ?>" />
To: <input type="text" id="xx_to" value="<?php echo $date_to; ?>" />
$j("#xx_from").datepicker({
dateFormat: 'yy-mm-dd',
maxDate: $j("#xx_to").val(),
onSelect: function(){
$j("#xx_to").datepicker( "refresh" );
}
});
$j("#xx_to").datepicker({
dateFormat: 'yy-mm-dd',
minDate: $j("#xx_from").val(),
onSelect: function(){
$j("#xx_from").datepicker( "refresh" );
}
});
I have somethinng like below, and wanted to make sure from date shall not
overpass to date which is not selectable(even after changing the date) and
vice versa.
From: <input type="text" id="xx_from" value="<?php echo $date_from; ?>" />
To: <input type="text" id="xx_to" value="<?php echo $date_to; ?>" />
$j("#xx_from").datepicker({
dateFormat: 'yy-mm-dd',
maxDate: $j("#xx_to").val(),
onSelect: function(){
$j("#xx_to").datepicker( "refresh" );
}
});
$j("#xx_to").datepicker({
dateFormat: 'yy-mm-dd',
minDate: $j("#xx_from").val(),
onSelect: function(){
$j("#xx_from").datepicker( "refresh" );
}
});
Thursday, 26 September 2013
Is there any ANTLR4 vim syntax file?
Is there any ANTLR4 vim syntax file?
I was only able to find this one (https://github.com/rollxx/vim-antlr),
but it was made for version 3. Does anyone knows where I can find proper
syntax for version 4?
I was only able to find this one (https://github.com/rollxx/vim-antlr),
but it was made for version 3. Does anyone knows where I can find proper
syntax for version 4?
Wednesday, 25 September 2013
Vim: Can't exit Visual Mode using jk (Arpeggio Chord)
Vim: Can't exit Visual Mode using jk (Arpeggio Chord)
I use Arpeggio to map jk to ESC So when I press jk simultaneously I can
exit to normal mode very quickly.
I found this trick from Arpeggio plugin page
This is what I put in .vimrc
Arpeggio inoremap jk <ESC>
Exiting from Insert mode works perfectly, But I can not exit from Visual
Mode. It would be nice if I can exit both mode so I can stick with this
key, It save my time a lot.
Any idea?
I use Arpeggio to map jk to ESC So when I press jk simultaneously I can
exit to normal mode very quickly.
I found this trick from Arpeggio plugin page
This is what I put in .vimrc
Arpeggio inoremap jk <ESC>
Exiting from Insert mode works perfectly, But I can not exit from Visual
Mode. It would be nice if I can exit both mode so I can stick with this
key, It save my time a lot.
Any idea?
Thursday, 19 September 2013
ListCellRenderer - JLabel - String - n rows
ListCellRenderer - JLabel - String - n rows
So I have this situation:
I have a JList that displays a bunch of Strings.
However, these strings are really long and JList is really narrow. Meaning
the strings won't fit.
What I want to do is make each entry to have two rows, like this:
|Word word word |
|word word wor...|
It would do wordWrap for the first row, and then finish the secon't row by
cutting the rest of the string and appeinging the three dots to what is
left in a way maximum space is filled.
It doesn't really matter what I do, the important thing is that I have to
use FontMetrics to measure all this stuff so I can make it work. And
that's the catch.
Until whole getListCellRendererComponent(...) method is executed, the
component will not be painted, thus having no graphics, thus making any
font measurement impossible.
How do I get around it?
P.S. I need to use the JLabel for the visuals.
So I have this situation:
I have a JList that displays a bunch of Strings.
However, these strings are really long and JList is really narrow. Meaning
the strings won't fit.
What I want to do is make each entry to have two rows, like this:
|Word word word |
|word word wor...|
It would do wordWrap for the first row, and then finish the secon't row by
cutting the rest of the string and appeinging the three dots to what is
left in a way maximum space is filled.
It doesn't really matter what I do, the important thing is that I have to
use FontMetrics to measure all this stuff so I can make it work. And
that's the catch.
Until whole getListCellRendererComponent(...) method is executed, the
component will not be painted, thus having no graphics, thus making any
font measurement impossible.
How do I get around it?
P.S. I need to use the JLabel for the visuals.
is that possible to simulate keypress on a virtual keyboard on ios? Using UIKeyboardLayoutStar.h
is that possible to simulate keypress on a virtual keyboard on ios? Using
UIKeyboardLayoutStar.h
is that possible to simulate keypress on a virtual keyboard on ios? Using
UIKeyboardLayoutStar.h
I have found these methods
-keyHitTestContainingPoint CGPoint
I believe if I specify coordinates I can use these methods but I'm not
sure if it is correct and how to get those coordinates for each button
from the keyboard (IF THAT IS THE CASE) . Any suggestion? I need to
simulate keyboard key press, How would you do that?
UIKeyboardLayoutStar.h
is that possible to simulate keypress on a virtual keyboard on ios? Using
UIKeyboardLayoutStar.h
I have found these methods
-keyHitTestContainingPoint CGPoint
I believe if I specify coordinates I can use these methods but I'm not
sure if it is correct and how to get those coordinates for each button
from the keyboard (IF THAT IS THE CASE) . Any suggestion? I need to
simulate keyboard key press, How would you do that?
Amazon ec2 and cyberduck pem file
Amazon ec2 and cyberduck pem file
I am so close to figuring this out.
I've set up an ec2 instance and can get in via ssh through terminal (Im on
a mac).
I want to be able to get in via cyberduck and sftp, and can with the
ec2-user@mydomain.com login but then I don't have sufficient privileges to
actually do anything.
When I try to login via cyberduck with root@mydomain.com it won't let me,
says
Illegal sftp packet len: 1349281121.
I created a new user but don't know how to get a .pem file uploaded for them.
Thanks for helping a first time linux user.
I am so close to figuring this out.
I've set up an ec2 instance and can get in via ssh through terminal (Im on
a mac).
I want to be able to get in via cyberduck and sftp, and can with the
ec2-user@mydomain.com login but then I don't have sufficient privileges to
actually do anything.
When I try to login via cyberduck with root@mydomain.com it won't let me,
says
Illegal sftp packet len: 1349281121.
I created a new user but don't know how to get a .pem file uploaded for them.
Thanks for helping a first time linux user.
Get JSON Object Array
Get JSON Object Array
I am building my application based on another similar application. I am
using firebug to attempt to get the same Response / JSON.
In the working application the "Response" tab says:
and the "JSON" tab shows several JSON objects with associated properties:
In the broken application the "Response" tab says:
(It put a "d" key around the data and escaped all the double quotes)
and the "JSON" tab just shows a single object d that contains a string of
the data:
The method that is called to return the "broken" JSON response is:
public static string GetMembers()
{
Member member1 = new Member();
member1.Id = 1;
member1.FirstName = "John";
member1.LastName = "Smith";
Member member2 = new Member();
member2.Id = 2;
member2.FirstName = "Bruce";
member2.LastName = "Banner";
List<Member> members = new List<Member>();
members.Add(member1);
members.Add(member2);
return new JavaScriptSerializer().Serialize(members);
}
What can I do to my method to make it return / display the JSON data the
same way as the first application?
Note I don't have the source of the first application, I am just looking
at the page it loads in firebug.
I am building my application based on another similar application. I am
using firebug to attempt to get the same Response / JSON.
In the working application the "Response" tab says:
and the "JSON" tab shows several JSON objects with associated properties:
In the broken application the "Response" tab says:
(It put a "d" key around the data and escaped all the double quotes)
and the "JSON" tab just shows a single object d that contains a string of
the data:
The method that is called to return the "broken" JSON response is:
public static string GetMembers()
{
Member member1 = new Member();
member1.Id = 1;
member1.FirstName = "John";
member1.LastName = "Smith";
Member member2 = new Member();
member2.Id = 2;
member2.FirstName = "Bruce";
member2.LastName = "Banner";
List<Member> members = new List<Member>();
members.Add(member1);
members.Add(member2);
return new JavaScriptSerializer().Serialize(members);
}
What can I do to my method to make it return / display the JSON data the
same way as the first application?
Note I don't have the source of the first application, I am just looking
at the page it loads in firebug.
trying to get onclick to call a Java script more than once
trying to get onclick to call a Java script more than once
First of all my apologies if there is a very obvious answer to this but I
have searched extensively to try and find an answer. I am very new to Java
script and am really struggling with this problem. I have a form which
asks if you stay at another address if you click yes an address block open
and you can fill in an other address. under that block you are asked if
you want to add a further address if you click yes then I would like
another address block to open exactly the same as the first but I get
nothing. I am assuming the reason for this is because the JS function has
already activated once and will not do so again unless I can give it some
means of counting the number of times it has opened or needs to open. I
have copied the functioning part of my code below can anyone point out
clearly and concisely where I have gone wrong, please bear in mind that my
understanding of JS is very limited so an idiot guide would be
appreciated. my code:
<div id=content>
<!-- QUESTION TEXT GOES HERE -->
<h3><span class="QID">8</span>Do you stay at another address, other than
your current address, for more than 30 days a year?</h3>
<form>
<p></p>
<input type="radio" name="Text">No <a href="PCS_p10.htm">Go to Question 10
</a><br>
<p></br></p>
</form>
<form>
<p></p>
<script type="text/javascript">
function checkIt(el) {
var elArr = ['mtext',];
for (var i=0; i<elArr.length; i++) {
sel = document.getElementById(elArr[i]);
if (el.value == elArr[i]) { sel.style.display = 'block'; }
else { sel.style.display = 'none'; }
}
}
</script>
</head>
<body>
<input type="radio" name="radioBtn" value="mtext"
onclick="checkIt(this)">Yes
<div id="mtext" style="display:none;width" />
<input type="text" id="multiple1" size="60" name="text"><br>
<input type="text" id="multiple2" size="60" name="text"><br>
<input type="text" id="multiple3" size="60" name="text"><br>
<input type="text" id="multiple4" size="60" name="text"><br>
<pre><font face="arial,helvetica" size"+1">
Postcode <input type="text"
id="multiple5" name="postc1" style="width: 40px;" maxlength="4">
<input type="text" name="postc2" style="width: 40px;"
maxlength="4"></pre><br>
Add another address
<input type="radio" name="radioBtn" value="mtext"
onclick="checkIt(this)">Yes
<input type="radio" name="Text">No <a href="PCS_p10.htm">Go to
Question 10 </a><br>
</div>
</body>
</html>
<p></br></p>
</form>
First of all my apologies if there is a very obvious answer to this but I
have searched extensively to try and find an answer. I am very new to Java
script and am really struggling with this problem. I have a form which
asks if you stay at another address if you click yes an address block open
and you can fill in an other address. under that block you are asked if
you want to add a further address if you click yes then I would like
another address block to open exactly the same as the first but I get
nothing. I am assuming the reason for this is because the JS function has
already activated once and will not do so again unless I can give it some
means of counting the number of times it has opened or needs to open. I
have copied the functioning part of my code below can anyone point out
clearly and concisely where I have gone wrong, please bear in mind that my
understanding of JS is very limited so an idiot guide would be
appreciated. my code:
<div id=content>
<!-- QUESTION TEXT GOES HERE -->
<h3><span class="QID">8</span>Do you stay at another address, other than
your current address, for more than 30 days a year?</h3>
<form>
<p></p>
<input type="radio" name="Text">No <a href="PCS_p10.htm">Go to Question 10
</a><br>
<p></br></p>
</form>
<form>
<p></p>
<script type="text/javascript">
function checkIt(el) {
var elArr = ['mtext',];
for (var i=0; i<elArr.length; i++) {
sel = document.getElementById(elArr[i]);
if (el.value == elArr[i]) { sel.style.display = 'block'; }
else { sel.style.display = 'none'; }
}
}
</script>
</head>
<body>
<input type="radio" name="radioBtn" value="mtext"
onclick="checkIt(this)">Yes
<div id="mtext" style="display:none;width" />
<input type="text" id="multiple1" size="60" name="text"><br>
<input type="text" id="multiple2" size="60" name="text"><br>
<input type="text" id="multiple3" size="60" name="text"><br>
<input type="text" id="multiple4" size="60" name="text"><br>
<pre><font face="arial,helvetica" size"+1">
Postcode <input type="text"
id="multiple5" name="postc1" style="width: 40px;" maxlength="4">
<input type="text" name="postc2" style="width: 40px;"
maxlength="4"></pre><br>
Add another address
<input type="radio" name="radioBtn" value="mtext"
onclick="checkIt(this)">Yes
<input type="radio" name="Text">No <a href="PCS_p10.htm">Go to
Question 10 </a><br>
</div>
</body>
</html>
<p></br></p>
</form>
How to view wmv subtitles in vlc player using Expression encoder
How to view wmv subtitles in vlc player using Expression encoder
I am using Expression encoder to add subtitles in an video in windows
forms application.
TimeSpan midpoint = new TimeSpan(0, 0, 0, temp);
mergedVideo.ScriptCommands.Add(new
Microsoft.Expression.Encoder.ScriptCommand(midpoint, "caption",
DataLogFiles[j]));
The captions I am adding here are seen fine on Windows Media Player. But I
cannot see these captions on the video in VLC player. Do I need to do
something else for this ? If the question is not clear please comment, I
will add some more code or explanation
I am using Expression encoder to add subtitles in an video in windows
forms application.
TimeSpan midpoint = new TimeSpan(0, 0, 0, temp);
mergedVideo.ScriptCommands.Add(new
Microsoft.Expression.Encoder.ScriptCommand(midpoint, "caption",
DataLogFiles[j]));
The captions I am adding here are seen fine on Windows Media Player. But I
cannot see these captions on the video in VLC player. Do I need to do
something else for this ? If the question is not clear please comment, I
will add some more code or explanation
Select option width
Select option width
Im not really experienced in CSS and i have no tools that are best used in
designing webpages such as microsoft expression.
My problem is simple, its somehow vain.. neways,
i want my page to look symmetrical as possible so i want my select options
to be of same width. I've searched and the best solution is to use
width="" option on css. so how do i go about this?
have this example:
<tr>
<td><label for="meal">Meal:</label></td>
<td>
<select name="meal">
<option selected="selected"
value="0">Any</option>
<option
value="Breakfast">Breakfast</option>
<option
value="Brunch">Brunch</option>
<option value="Lunch">Lunch</option>
<option value="Snack">Snack</option>
<option
value="Dinner">Dinner</option>
</select>
</td>
<td><label for="cooking">Cooking:</label></td>
<td>
<select name="cooking">
<option selected="selected"
value="0">Any</option>
<option value="Baked">Baked</option>
<option
value="BBQ">Barbecque</option>
<option
value="Boiled">Boiled</option>
<option value="Dfried">Deep
Fried</option>
<option
value="Grilled">Grilled</option>
<option
value="Steamed">Steamed</option>
</select>
</td>
Im not really experienced in CSS and i have no tools that are best used in
designing webpages such as microsoft expression.
My problem is simple, its somehow vain.. neways,
i want my page to look symmetrical as possible so i want my select options
to be of same width. I've searched and the best solution is to use
width="" option on css. so how do i go about this?
have this example:
<tr>
<td><label for="meal">Meal:</label></td>
<td>
<select name="meal">
<option selected="selected"
value="0">Any</option>
<option
value="Breakfast">Breakfast</option>
<option
value="Brunch">Brunch</option>
<option value="Lunch">Lunch</option>
<option value="Snack">Snack</option>
<option
value="Dinner">Dinner</option>
</select>
</td>
<td><label for="cooking">Cooking:</label></td>
<td>
<select name="cooking">
<option selected="selected"
value="0">Any</option>
<option value="Baked">Baked</option>
<option
value="BBQ">Barbecque</option>
<option
value="Boiled">Boiled</option>
<option value="Dfried">Deep
Fried</option>
<option
value="Grilled">Grilled</option>
<option
value="Steamed">Steamed</option>
</select>
</td>
Wednesday, 18 September 2013
Can anyone explain this snippet of `ruby`?
Can anyone explain this snippet of `ruby`?
Can any one explain this snippet of ruby ?
def request_phase
service_url = append_params( callback_url, return_url )
[
302,
{
'Location' => login_url( service_url ),
'Content-Type' => 'text/plain'
},
["You are being redirected to CAS for sign-in."]
]
end
Can any one explain this snippet of ruby ?
def request_phase
service_url = append_params( callback_url, return_url )
[
302,
{
'Location' => login_url( service_url ),
'Content-Type' => 'text/plain'
},
["You are being redirected to CAS for sign-in."]
]
end
Django compatible web hosting services
Django compatible web hosting services
What is your favorite (free or not) web hosting services that is
compatible with django( and python in general) ?
PS: is OVH compatible?
What is your favorite (free or not) web hosting services that is
compatible with django( and python in general) ?
PS: is OVH compatible?
How to make a border colorful using CSS?
How to make a border colorful using CSS?
I have defined a border class in a div:
<div class="border"></div>
.border {
border: 4px solid;
color: #E72665;
}
It gives pink color to the border. But instead of pink only. I can 4
colors in borders each covering 25% how can I do that?
I have defined a border class in a div:
<div class="border"></div>
.border {
border: 4px solid;
color: #E72665;
}
It gives pink color to the border. But instead of pink only. I can 4
colors in borders each covering 25% how can I do that?
How to create an empty anonymous table in Postgres?
How to create an empty anonymous table in Postgres?
In Postgres if I want to create an anonymous table I can use VALUES, for
example:
select * from (values (1, 'Hello world'), (100, 'Another row')) as foo
(mycol1, mycol2);
But how can I create an anonymous table with no rows? (This is for a code
generator, so the question isn't quite as odd as it sounds!). The
following does not work
select * from (values ) as foo (mycol1, mycol2);
because I get
ERROR: syntax error at or near ")"
LINE 1: select * from (values ) as foo (mycol1, mycol2);
^
I know a work around
select * from (values (NULL, NULL)) as foo (mycol1, mycol2) where mycol1
is not NULL;
but is there a better or "more official" way?
(I would also be interested to know if it is possible to create a table
with no columns!)
In Postgres if I want to create an anonymous table I can use VALUES, for
example:
select * from (values (1, 'Hello world'), (100, 'Another row')) as foo
(mycol1, mycol2);
But how can I create an anonymous table with no rows? (This is for a code
generator, so the question isn't quite as odd as it sounds!). The
following does not work
select * from (values ) as foo (mycol1, mycol2);
because I get
ERROR: syntax error at or near ")"
LINE 1: select * from (values ) as foo (mycol1, mycol2);
^
I know a work around
select * from (values (NULL, NULL)) as foo (mycol1, mycol2) where mycol1
is not NULL;
but is there a better or "more official" way?
(I would also be interested to know if it is possible to create a table
with no columns!)
Is it OK to use exceptions to check for array boundaries?
Is it OK to use exceptions to check for array boundaries?
I want to check whether the given coordinates are withing an array or not.
Can I do it like that?
public boolean checkBounds(int x, int y) {
try {
Object val = array[x][y];
return true;
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}
}
I want to check whether the given coordinates are withing an array or not.
Can I do it like that?
public boolean checkBounds(int x, int y) {
try {
Object val = array[x][y];
return true;
} catch (ArrayIndexOutOfBoundsException e) {
return false;
}
}
How to convert a string to DOM and selecting within it
How to convert a string to DOM and selecting within it
I have a string containing HTML.
I need
part one: convert the string to DOM element and using jquery to selecting
all images
part two: update all image src adding "xxxx/" before the current src value
Any idea how to do it?
var resp = '<div><img src="smiley.gif"></div><div><img
src="smiley.gif"></div><div><img src="smiley.gif"></div>';
var dom = $(resp).html();
the result rendered as html should be:
<div><img src="xxxx/smiley.gif"></div><div><img
src="xxxx/smiley.gif"></div><div><img src="xxxx/smiley.gif"></div>;
I have a string containing HTML.
I need
part one: convert the string to DOM element and using jquery to selecting
all images
part two: update all image src adding "xxxx/" before the current src value
Any idea how to do it?
var resp = '<div><img src="smiley.gif"></div><div><img
src="smiley.gif"></div><div><img src="smiley.gif"></div>';
var dom = $(resp).html();
the result rendered as html should be:
<div><img src="xxxx/smiley.gif"></div><div><img
src="xxxx/smiley.gif"></div><div><img src="xxxx/smiley.gif"></div>;
Tuesday, 17 September 2013
What is the best practice? use different database for every users or use same database with userid coloumn
What is the best practice? use different database for every users or use
same database with userid coloumn
What is the best practice? use different database for every users or use
same database with userid coloumn.
I am working on mysql database and php. I having a little bit confusion
about my project.
My project is user based. If a user has been registered then he can store
data on a many tables. I have created all tables with userid column to
find data for particular user. But now I am thinking about it if tables
having huge amount of rows then my project will getting slow to fetch
records.
Now the confusion is "what is the best practice use different database for
every users or use same database with userid coloumn."
same database with userid coloumn
What is the best practice? use different database for every users or use
same database with userid coloumn.
I am working on mysql database and php. I having a little bit confusion
about my project.
My project is user based. If a user has been registered then he can store
data on a many tables. I have created all tables with userid column to
find data for particular user. But now I am thinking about it if tables
having huge amount of rows then my project will getting slow to fetch
records.
Now the confusion is "what is the best practice use different database for
every users or use same database with userid coloumn."
My html file is :
My html file is :
My html file is :
<!Doctype >
<html>
<head>
<script type="text/javascript" src="my-slide.js"></script>
<!--- name of javascript file is my-slide.js-->„³
</head>
<body>
<img src="map-image1.gif" name="slide" width="100%" height="368" />
<!--- The image above is in same folder as the html and javascript
file are.-„³
</body>
</html>
The javascript file is here:
var numImages = 3;
var images = [];
for (var i = 0; i < numImages; ++i) {
var image = new Image();
image.src = 'map-image1' + (i + 1) + '.gif';
images.push(image);
}
var step = 0;
function slideit() {
if (! document.images) {
return;
}
document.images.slide.src = images[step].src;
step = (step + 1) % numImages;
}
setInterval(slideit, 2500);
I have 3 images in that folder which are
called(map-image1.gif,map-image2.gif, map-image3.gif) why my slide show
doesn¡¦t work and show just one of them and nothing else .I am
frustrated,please help me. Thanks in advance
My html file is :
<!Doctype >
<html>
<head>
<script type="text/javascript" src="my-slide.js"></script>
<!--- name of javascript file is my-slide.js-->„³
</head>
<body>
<img src="map-image1.gif" name="slide" width="100%" height="368" />
<!--- The image above is in same folder as the html and javascript
file are.-„³
</body>
</html>
The javascript file is here:
var numImages = 3;
var images = [];
for (var i = 0; i < numImages; ++i) {
var image = new Image();
image.src = 'map-image1' + (i + 1) + '.gif';
images.push(image);
}
var step = 0;
function slideit() {
if (! document.images) {
return;
}
document.images.slide.src = images[step].src;
step = (step + 1) % numImages;
}
setInterval(slideit, 2500);
I have 3 images in that folder which are
called(map-image1.gif,map-image2.gif, map-image3.gif) why my slide show
doesn¡¦t work and show just one of them and nothing else .I am
frustrated,please help me. Thanks in advance
prevent a user of mcimagemanager from viewing others images
prevent a user of mcimagemanager from viewing others images
i am using MCImageManager plugin of TinyMCE editor, the problem is that
any user can view all images reside in the upload path,
i can't understand the authentication idea explained in docs, so is there
anyway to make a user able to only view and edit his own images ?
I am using it with PHP
i am using MCImageManager plugin of TinyMCE editor, the problem is that
any user can view all images reside in the upload path,
i can't understand the authentication idea explained in docs, so is there
anyway to make a user able to only view and edit his own images ?
I am using it with PHP
eclipse is not starting though suitable already installed
eclipse is not starting though suitable already installed
when I am trying to open eclipse this message is coming "version 1.4.2_06
of the JVM is not suitable for this product. Version 1.5 or greater is
required" . But I have already installed jdk6 in my laptop.
when I am trying to open eclipse this message is coming "version 1.4.2_06
of the JVM is not suitable for this product. Version 1.5 or greater is
required" . But I have already installed jdk6 in my laptop.
Python subprocesss: call an instance method
Python subprocesss: call an instance method
I am using Python 2.7. I want to create an instance of an object, and call
a method within it in a separate process. Something like this:
import subprocesss
class A
def doAwork(self, text):
print text
class B
def doBWork
aInst = A()
subprocess(A.dowork("called from doBwork"))
Can this be done, or, do I need to turn around and call python as a
subprocesss?
Thanks
I am using Python 2.7. I want to create an instance of an object, and call
a method within it in a separate process. Something like this:
import subprocesss
class A
def doAwork(self, text):
print text
class B
def doBWork
aInst = A()
subprocess(A.dowork("called from doBwork"))
Can this be done, or, do I need to turn around and call python as a
subprocesss?
Thanks
what's the best associatice container for grouping data
what's the best associatice container for grouping data
I'm trying to store rows of data with parameters date, group1, group2,
group3, analytics1, analytics2, analytic 3 into some sort of associative
container. I will need to aggregate the analytics in 3 ways:
based on date(think of it like a group by in sql)
based on group1, group2, group3
based on date, group1, group2, group3
There will be some simple math done after the data has been grouped, what
would be the best data structure for something like this. I was thinking
of doing a multimap(vector, vector) with key and value both being vectors,
key is a vector of the form (data, group1, group2, group3) and value is a
vector of the form (analytics1, analytics2, analytics3). This way it will
be at its most granular level but I'm pretty sure I'll still end up having
to do 3 separate iteratings to take care of the groupings. Is there a
faster alternative approach. Thanks
I'm trying to store rows of data with parameters date, group1, group2,
group3, analytics1, analytics2, analytic 3 into some sort of associative
container. I will need to aggregate the analytics in 3 ways:
based on date(think of it like a group by in sql)
based on group1, group2, group3
based on date, group1, group2, group3
There will be some simple math done after the data has been grouped, what
would be the best data structure for something like this. I was thinking
of doing a multimap(vector, vector) with key and value both being vectors,
key is a vector of the form (data, group1, group2, group3) and value is a
vector of the form (analytics1, analytics2, analytics3). This way it will
be at its most granular level but I'm pretty sure I'll still end up having
to do 3 separate iteratings to take care of the groupings. Is there a
faster alternative approach. Thanks
Sunday, 15 September 2013
Debug.Print shows me a value, but 'If not' wouldn't work with this value
Debug.Print shows me a value, but 'If not' wouldn't work with this value
I am totally baffled. Can't find a solution. I ask for the value of a shape:
? ActiveWindow.Selection.ShapeRange.TextFrame.MarginBottom
Answer: 11.29354
I write a routine:
If Not oshp.TextFrame.MarginBottom = 11.29354 Then
TellMe = "MarginBottom =" & oshp.TextFrame.MarginBottom & " but not
11.29354"
End If
The routine won't work. I claims the shape's MarginBottom has not the
value, but in the same moment it gives me the value as a result.
That would mean the value is not the value. Any experienced guy has
background info on this?
I am totally baffled. Can't find a solution. I ask for the value of a shape:
? ActiveWindow.Selection.ShapeRange.TextFrame.MarginBottom
Answer: 11.29354
I write a routine:
If Not oshp.TextFrame.MarginBottom = 11.29354 Then
TellMe = "MarginBottom =" & oshp.TextFrame.MarginBottom & " but not
11.29354"
End If
The routine won't work. I claims the shape's MarginBottom has not the
value, but in the same moment it gives me the value as a result.
That would mean the value is not the value. Any experienced guy has
background info on this?
datetime difference in python
datetime difference in python
for proc in psutil.process_iter():
if proc.name == "monit":
today = datetime.datetime.now()
current_time = today.strftime('%Y-%m-%d %H:%M:%S')
proc_start_time = time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime(proc.create_time))
print current_time
print proc_start_time
print (current_time - proc_start_time).seconds
I am not able to find difference between two datetimes. Can't subtract
them give Error -
TypeError: unsupported operand type(s) for -: 'str' and 'str'
for proc in psutil.process_iter():
if proc.name == "monit":
today = datetime.datetime.now()
current_time = today.strftime('%Y-%m-%d %H:%M:%S')
proc_start_time = time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime(proc.create_time))
print current_time
print proc_start_time
print (current_time - proc_start_time).seconds
I am not able to find difference between two datetimes. Can't subtract
them give Error -
TypeError: unsupported operand type(s) for -: 'str' and 'str'
Time complexity
Time complexity
Which structure takes more time to execute- No of items in the store are
10,000+
Structure1
if(condition1)
{
executing for 20% of items
if(condition2)
{
executing for 20% of items
if(condition3)
{
executing for 20% of items
}
}
else
{
executing for 20% of items
}
}
else
{
executing for 80% of items
}
Structure2
if(condition2)
{
executing 80% of the items
}
if(condition3)
{
executing 80% of the items
}
if(condition1)
{
executing 20% of items
}
else
{
executing for 80% of items
}
Which structure takes more time to execute- No of items in the store are
10,000+
Structure1
if(condition1)
{
executing for 20% of items
if(condition2)
{
executing for 20% of items
if(condition3)
{
executing for 20% of items
}
}
else
{
executing for 20% of items
}
}
else
{
executing for 80% of items
}
Structure2
if(condition2)
{
executing 80% of the items
}
if(condition3)
{
executing 80% of the items
}
if(condition1)
{
executing 20% of items
}
else
{
executing for 80% of items
}
I want that onCreate of my activity will be called every time that my broadcast receiver launches it
I want that onCreate of my activity will be called every time that my
broadcast receiver launches it
I have a broadcast receiver which start an activity on its onReceive with
the following flag :Intent.FLAG_ACTIVITY_NEW_TASK.
Now, the onCreate method of my activity gets called. When I click on the
HOME button, my activity moves back to background but now when the
onReceive function will be called again, the onRestart method will be
called instead of the onCreate.
I want that onCreate will be called on every onReceive (I need the same
behavior for every event that my broadcast receiver received).
Another thing, my activity (the one that gets launched by the broadcast
receiver have this flag in the AndroidManifest.xml file:
android:launchMode="singleInstance".
I done this to prevent a way that clicking on my app icon will launch my
activity (its not the main activity).
Any ideas are more than welcome.
Thanks
broadcast receiver launches it
I have a broadcast receiver which start an activity on its onReceive with
the following flag :Intent.FLAG_ACTIVITY_NEW_TASK.
Now, the onCreate method of my activity gets called. When I click on the
HOME button, my activity moves back to background but now when the
onReceive function will be called again, the onRestart method will be
called instead of the onCreate.
I want that onCreate will be called on every onReceive (I need the same
behavior for every event that my broadcast receiver received).
Another thing, my activity (the one that gets launched by the broadcast
receiver have this flag in the AndroidManifest.xml file:
android:launchMode="singleInstance".
I done this to prevent a way that clicking on my app icon will launch my
activity (its not the main activity).
Any ideas are more than welcome.
Thanks
Treat escape key as an action instead of a character in Python input
Treat escape key as an action instead of a character in Python input
In a command-line application, I'm using the following code to ask the
user a yes/no question (it just uses the standard input):
# Taken from http://code.activestate.com/recipes/577058-query-yesno/
# with some personal modifications
def yes_no(question, default=True):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is one of "yes" or "no".
"""
valid = {"yes":True, "y":True, "ye":True,
"no":False, "n":False }
if default == None:
prompt = " [y/n] "
elif default == True:
prompt = " [Y/n] "
elif default == False:
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while 1:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return default
elif choice in valid.keys():
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "\
"(or 'y' or 'n').\n")
If the user types yes (or an equivalent) the function returns True, and no
returns False. If they just press Enter, the default value is chosen.
However, if user presses ESC on their keyboard, it gets treated as a
character. Is there instead a way to cause the function to return False if
that key is pressed? The few results I have found in my own searches seem
overly complicated or only work on some operating systems.
In a command-line application, I'm using the following code to ask the
user a yes/no question (it just uses the standard input):
# Taken from http://code.activestate.com/recipes/577058-query-yesno/
# with some personal modifications
def yes_no(question, default=True):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is one of "yes" or "no".
"""
valid = {"yes":True, "y":True, "ye":True,
"no":False, "n":False }
if default == None:
prompt = " [y/n] "
elif default == True:
prompt = " [Y/n] "
elif default == False:
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while 1:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return default
elif choice in valid.keys():
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "\
"(or 'y' or 'n').\n")
If the user types yes (or an equivalent) the function returns True, and no
returns False. If they just press Enter, the default value is chosen.
However, if user presses ESC on their keyboard, it gets treated as a
character. Is there instead a way to cause the function to return False if
that key is pressed? The few results I have found in my own searches seem
overly complicated or only work on some operating systems.
Getting error whle traversing JSON with backbone
Getting error whle traversing JSON with backbone
I am trying to traverse a JSON response using jquery in backbone, however,
it is giving me error
TypeError: e is undefined @ http://localhost/ scripts/ jquery.js
JSON Data:
{"tweets":[{"url":"http:\/\/twitter.com\/SrBachchan\/status\/378975107009368064","text":"T
1155 -Football the compulsion ... football the meal at meal times ...
despite the Chelsea loss .. but Villa v Madrid on now and great
game","date":"1379189681","user":"\/SrBachchan","id":"145125358"},{"url":"http:\/\/twitter.com\/Mousumimukher13\/status\/378907332711038976","text":"Now
is the #KBC time @SonyTV With Amitabh Bachchan @SrBachchan Just Enjoy
,Watch and Learn
..","date":"1379173522","user":"\/Mousumimukher13","id":"1407612847"},{"url":"http:\/\/twitter.com\/brisha_15\/status\/378907467888873472","text":"@SrBachchan
God do u still watch #KBC alone like frst season or wid
family","date":"1379173554","user":"\/brisha_15","id":"67258128"},{"url":"http:\/\/twitter.com\/NiTiSHmurthy\/status\/378907588978434048","text":"Aww..
This man, very sportive. #KBC
@SrBachchan","date":"1379173583","user":"\/NiTiSHmurthy","id":"18354369"},{"url":"http:\/\/twitter.com\/punkrochelle\/status\/378907593160138753","text":"@SrBachchan
#KBC = Kind Beloved
Contestants.","date":"1379173584","user":"\/punkrochelle","id":"89637264"}]}
My JS file:
$(function() {
FriendList = Backbone.Collection.extend({
initialize: function(){
this.bind("add", function( model ){
view.render( model );
})
}
});
FriendView = Backbone.View.extend({
tagName: 'li',
events: {
'click #btnSearch': 'getFriend',
},
initialize: function() {
this.friendslist = new FriendList;
_.bindAll(this, 'render');
//window.setInterval(this.getFriend, 5000);
},
getFriend: function() {
var hashtag = $('#txtHashTag').val();
if(hashtag.length>0)
{
$.ajax({
type: "GET",
url: "index.php",
dataType:"json",
data: {
name: hashtag
},
success: function(msg){
$.each(msg[0], function(i,item){
alert(i);
// your code ..
});
}
});
}
if(hashtag!=$('#tags').val())
{
$('#tags').append(hashtag);
}
//this.friendslist.add( {name: friend_name} );
},
render: function( model ) {
},
});
var view = new FriendView({el: 'body'});
});
Any idea, what is happening ?
Thanks
I am trying to traverse a JSON response using jquery in backbone, however,
it is giving me error
TypeError: e is undefined @ http://localhost/ scripts/ jquery.js
JSON Data:
{"tweets":[{"url":"http:\/\/twitter.com\/SrBachchan\/status\/378975107009368064","text":"T
1155 -Football the compulsion ... football the meal at meal times ...
despite the Chelsea loss .. but Villa v Madrid on now and great
game","date":"1379189681","user":"\/SrBachchan","id":"145125358"},{"url":"http:\/\/twitter.com\/Mousumimukher13\/status\/378907332711038976","text":"Now
is the #KBC time @SonyTV With Amitabh Bachchan @SrBachchan Just Enjoy
,Watch and Learn
..","date":"1379173522","user":"\/Mousumimukher13","id":"1407612847"},{"url":"http:\/\/twitter.com\/brisha_15\/status\/378907467888873472","text":"@SrBachchan
God do u still watch #KBC alone like frst season or wid
family","date":"1379173554","user":"\/brisha_15","id":"67258128"},{"url":"http:\/\/twitter.com\/NiTiSHmurthy\/status\/378907588978434048","text":"Aww..
This man, very sportive. #KBC
@SrBachchan","date":"1379173583","user":"\/NiTiSHmurthy","id":"18354369"},{"url":"http:\/\/twitter.com\/punkrochelle\/status\/378907593160138753","text":"@SrBachchan
#KBC = Kind Beloved
Contestants.","date":"1379173584","user":"\/punkrochelle","id":"89637264"}]}
My JS file:
$(function() {
FriendList = Backbone.Collection.extend({
initialize: function(){
this.bind("add", function( model ){
view.render( model );
})
}
});
FriendView = Backbone.View.extend({
tagName: 'li',
events: {
'click #btnSearch': 'getFriend',
},
initialize: function() {
this.friendslist = new FriendList;
_.bindAll(this, 'render');
//window.setInterval(this.getFriend, 5000);
},
getFriend: function() {
var hashtag = $('#txtHashTag').val();
if(hashtag.length>0)
{
$.ajax({
type: "GET",
url: "index.php",
dataType:"json",
data: {
name: hashtag
},
success: function(msg){
$.each(msg[0], function(i,item){
alert(i);
// your code ..
});
}
});
}
if(hashtag!=$('#tags').val())
{
$('#tags').append(hashtag);
}
//this.friendslist.add( {name: friend_name} );
},
render: function( model ) {
},
});
var view = new FriendView({el: 'body'});
});
Any idea, what is happening ?
Thanks
Magento - moodle connection
Magento - moodle connection
I want to sell my moodle courses via magento.
The process flow is as under
1) User creates an account in magento(shopping cart). 2) User purchaces a
curse. 3) After purchacing the chourse the user can login to moodle with
the same login details with which the user retistered to magento. 4) User
should get enrolled to purchased course.
please help
I want to sell my moodle courses via magento.
The process flow is as under
1) User creates an account in magento(shopping cart). 2) User purchaces a
curse. 3) After purchacing the chourse the user can login to moodle with
the same login details with which the user retistered to magento. 4) User
should get enrolled to purchased course.
please help
Saturday, 14 September 2013
Objective-C iPhone check location periodically
Objective-C iPhone check location periodically
My iOS application relies heavily on GPS and I tried writing a method that
helps conserve battery but I am having little success.
I created an NSTimer that fired every 15 seconds. Every time the method
was called, it would increment an int time up by 1. If int time reached
20(5 minutes) it would turn off the location updates and set a bool
isStopped to true. Every time the method ran and int time was above 20, it
would increment another int, int time2, up by 1. If the method was ran and
int time2 was equal to 4, it would start the location updates again and
set time2 to 0.
Then in the didUpdateLocation: method for the location manager, I have an
algorithm that would first check if the bool isStopped was true, if it was
true then it would check the new location's horizontal accuracy and make
sure it was under 10. Then it would check the newLocation with a location
object named coords and check to see if they were greater than 9 meters
apart. If they were not, it would stop location updates again and return.
If they were, it would continue to another algorithm where it would check
the new location object against some arguments. If it passed the coords
location object would be set with the new location object, the time and
time2 ints would be set to 0, the isStopped would be set to false, and the
whole process would start all over again.
In short, after 5 minutes of no location changes, the location updates
would be stopped and periodically checked every 1 minute to see if the
user had moved at least 10 meters from the previous location that passed
all requirements. When the user does move far enough, it starts the
process all over again and the user has to not move 10 or more meters for
5 minutes before it starts the periodic checks. The thought behind this is
to do only few second checks every minute when the user isn't moving much
instead of constantly having the location services running.
Now here's the problem I run into, when the location updates stop. The
NSTimer stops running while the app is in the background.
Could I somehow schedule a background task to run the loop between the 1
minute checks? Does anyone have any better ideas? Or any ideas on
solutions to this?
My iOS application relies heavily on GPS and I tried writing a method that
helps conserve battery but I am having little success.
I created an NSTimer that fired every 15 seconds. Every time the method
was called, it would increment an int time up by 1. If int time reached
20(5 minutes) it would turn off the location updates and set a bool
isStopped to true. Every time the method ran and int time was above 20, it
would increment another int, int time2, up by 1. If the method was ran and
int time2 was equal to 4, it would start the location updates again and
set time2 to 0.
Then in the didUpdateLocation: method for the location manager, I have an
algorithm that would first check if the bool isStopped was true, if it was
true then it would check the new location's horizontal accuracy and make
sure it was under 10. Then it would check the newLocation with a location
object named coords and check to see if they were greater than 9 meters
apart. If they were not, it would stop location updates again and return.
If they were, it would continue to another algorithm where it would check
the new location object against some arguments. If it passed the coords
location object would be set with the new location object, the time and
time2 ints would be set to 0, the isStopped would be set to false, and the
whole process would start all over again.
In short, after 5 minutes of no location changes, the location updates
would be stopped and periodically checked every 1 minute to see if the
user had moved at least 10 meters from the previous location that passed
all requirements. When the user does move far enough, it starts the
process all over again and the user has to not move 10 or more meters for
5 minutes before it starts the periodic checks. The thought behind this is
to do only few second checks every minute when the user isn't moving much
instead of constantly having the location services running.
Now here's the problem I run into, when the location updates stop. The
NSTimer stops running while the app is in the background.
Could I somehow schedule a background task to run the loop between the 1
minute checks? Does anyone have any better ideas? Or any ideas on
solutions to this?
Strange CSS behavior with box and multi-column list
Strange CSS behavior with box and multi-column list
I'd like a three-column list inside a grey box:
<div style="width:500px;font-size:21px;background:#f5f5f5;margin:0 0 40px
100px;padding:1px;border:3px solid black;">
<div style="text-align:center;margin:10px 0px 0px 0px;"><strong>Table of
Contents</strong></div>
<ul style="float:left;width:33%;list-style-type:none;">
<li>Book 1.</li>
<li>Part 1.</li>
<li><a href="#S1">Section 1.</a></li>
<li><a href="#S2">Section 2.</a></li>
<li><a href="#S3">Section 3.</a></li>
</ul>
<ul style="float:left;width:33%;list-style-type:none;">
<li>Book 2.</li>
<li>Part 1.</li>
<li><a href="#S4">Section 1.</a></li>
<li><a href="#S5">Section 2.</a></li>
<li><a href="#S6">Section 3.</a></li>
</ul>
<ul style="float:left;width:33%;list-style-type:none;">
<li>Book 3.</li>
<li>Part 1.</li>
<li><a href="#S7">Section 1.</a></li>
<li><a href="#S8">Section 2.</a></li>
<li><a href="#S9">Section 3.</a></li>
</ul>
</div>
But the results are not pretty: http://jsfiddle.net/gq2gh/
Can anyone explain what's going on, and/or fix it? Thanks.
I'd like a three-column list inside a grey box:
<div style="width:500px;font-size:21px;background:#f5f5f5;margin:0 0 40px
100px;padding:1px;border:3px solid black;">
<div style="text-align:center;margin:10px 0px 0px 0px;"><strong>Table of
Contents</strong></div>
<ul style="float:left;width:33%;list-style-type:none;">
<li>Book 1.</li>
<li>Part 1.</li>
<li><a href="#S1">Section 1.</a></li>
<li><a href="#S2">Section 2.</a></li>
<li><a href="#S3">Section 3.</a></li>
</ul>
<ul style="float:left;width:33%;list-style-type:none;">
<li>Book 2.</li>
<li>Part 1.</li>
<li><a href="#S4">Section 1.</a></li>
<li><a href="#S5">Section 2.</a></li>
<li><a href="#S6">Section 3.</a></li>
</ul>
<ul style="float:left;width:33%;list-style-type:none;">
<li>Book 3.</li>
<li>Part 1.</li>
<li><a href="#S7">Section 1.</a></li>
<li><a href="#S8">Section 2.</a></li>
<li><a href="#S9">Section 3.</a></li>
</ul>
</div>
But the results are not pretty: http://jsfiddle.net/gq2gh/
Can anyone explain what's going on, and/or fix it? Thanks.
XML parser for storing the element content of a xml file in individual java object states
XML parser for storing the element content of a xml file in individual
java object states
Can you please help me how to parse a xml and store the elements of the
XML file in a java class object (XML elements as Java object states? I
tried to search in the forum, but could not find an answer. I am
implementing the logic using SAX parser with implementing XMLReader.
Thanks
java object states
Can you please help me how to parse a xml and store the elements of the
XML file in a java class object (XML elements as Java object states? I
tried to search in the forum, but could not find an answer. I am
implementing the logic using SAX parser with implementing XMLReader.
Thanks
background image AND navigation bar border problems
background image AND navigation bar border problems
I'm VERY new to programming and am probably using a totally old way to
program my site, but so far it's been frustrating at times, but has worked
for me. Now I have 2 problems that I can't seem to fix First: background
images. I've been checking it using Chrome, but when I open the page in
IE, my background is not showing up. I've checked the syntax (some sites
seem to indicate that I needed to add spaces) and I don't see where I've
got a problem. I also tried saving the image as a png instead of jpg and
that didn't work.
Here's what my code looks like:
body {
background-image: url('images/backrings.jpg'),
url('images/backrings2.jpg');
background-position: left top, right top;
background-repeat: no-repeat;
}
Second: I'm getting a blue border around my footer navigation bar - I
don't know why and have tried everything that I can think of to get rid of
it.
Here's what the code for that looks like:
<div id="footermenu">
<ul>
<li class="first"><a href="index.html">home</a></li>
<li><a href="about.html">about</a></li>
<li><a href="gallery.html">gallery</a></li>
<li><a href="contact.html">contact</a></li>
</ul>
</div>
Any help would be GREATLY appreciated - thanks!
I'm VERY new to programming and am probably using a totally old way to
program my site, but so far it's been frustrating at times, but has worked
for me. Now I have 2 problems that I can't seem to fix First: background
images. I've been checking it using Chrome, but when I open the page in
IE, my background is not showing up. I've checked the syntax (some sites
seem to indicate that I needed to add spaces) and I don't see where I've
got a problem. I also tried saving the image as a png instead of jpg and
that didn't work.
Here's what my code looks like:
body {
background-image: url('images/backrings.jpg'),
url('images/backrings2.jpg');
background-position: left top, right top;
background-repeat: no-repeat;
}
Second: I'm getting a blue border around my footer navigation bar - I
don't know why and have tried everything that I can think of to get rid of
it.
Here's what the code for that looks like:
<div id="footermenu">
<ul>
<li class="first"><a href="index.html">home</a></li>
<li><a href="about.html">about</a></li>
<li><a href="gallery.html">gallery</a></li>
<li><a href="contact.html">contact</a></li>
</ul>
</div>
Any help would be GREATLY appreciated - thanks!
Which version of jQuery ui and jQuery work together?
Which version of jQuery ui and jQuery work together?
I am trying to use jquery mobile 1.3.2 with jquery ui 1.8 and 1.9. But
none of them work together. Please help me.
Thanks in advance.
I am trying to use jquery mobile 1.3.2 with jquery ui 1.8 and 1.9. But
none of them work together. Please help me.
Thanks in advance.
Custom exceptions- String Comparision
Custom exceptions- String Comparision
there is a string array having some names. We take an input using buffer
or scanner and compare the input from the user with the string array and
display the corresponding details. how do i do it ?
there is a string array having some names. We take an input using buffer
or scanner and compare the input from the user with the string array and
display the corresponding details. how do i do it ?
Friday, 13 September 2013
Import Error when run django with wsgi (apache)
Import Error when run django with wsgi (apache)
I found the problem when I run django from apache. When I run my program
in debug mode ( manage.py runserver in cmd ) , everything is work. But
when I run with apache, It show error:
ImportError at /systeminformation/ DLL load failed:
The specified module could not be found.
The error is occur when I import win32file. I use django 1.5.2 with apache
2.2 and run with mod_wsgi.
Anyone can solve this problem?
thank you very much
I found the problem when I run django from apache. When I run my program
in debug mode ( manage.py runserver in cmd ) , everything is work. But
when I run with apache, It show error:
ImportError at /systeminformation/ DLL load failed:
The specified module could not be found.
The error is occur when I import win32file. I use django 1.5.2 with apache
2.2 and run with mod_wsgi.
Anyone can solve this problem?
thank you very much
(Unix) piping tail -f to festival
(Unix) piping tail -f to festival
I'm trying to send a stream of the end of a file (via tail -f) to
festival, which is a text to speech program. tail -f ./filename | festival
--tts works fine for this.
Here's my problem: I'd like change the stream coming out of tail -f so
that festival can better synthesize it, and to avoid it speaking entire
timestamps. I know that programs like sed and grep can do this.
unfortunately tail -f ./filename | sed 's/:/ says/' | festival --tts does
not output any sound.
yes, I have check to see if tail -f ./filename | sed 's/:/ says/' outputs
anything, and it does that just fine.
I've also tried this with grep and I can not get festival --tts to say
anything after I've edited my stream.
Anything that allows my stream to be edited, then spoken would be
welcomed, I'm not tied down to sed and grep.
I'm trying to send a stream of the end of a file (via tail -f) to
festival, which is a text to speech program. tail -f ./filename | festival
--tts works fine for this.
Here's my problem: I'd like change the stream coming out of tail -f so
that festival can better synthesize it, and to avoid it speaking entire
timestamps. I know that programs like sed and grep can do this.
unfortunately tail -f ./filename | sed 's/:/ says/' | festival --tts does
not output any sound.
yes, I have check to see if tail -f ./filename | sed 's/:/ says/' outputs
anything, and it does that just fine.
I've also tried this with grep and I can not get festival --tts to say
anything after I've edited my stream.
Anything that allows my stream to be edited, then spoken would be
welcomed, I'm not tied down to sed and grep.
pg:psql select shows blank space for rows even though count is one; aka stuck Queue Classic job?
pg:psql select shows blank space for rows even though count is one; aka
stuck Queue Classic job?
I am trying to track down what is happening with a stuck background
process in my app and need a push in the right direction.
I have a rails app on heroku that is processing some xml. This is done in
a background job using Queue Classic. I also have HireFire setup to turn
the workers on and off when they are not needed.
This seems to be working for the most part. However, every now and then it
seems like a job is getting stuck and causing all manner of havoc: Workers
are not turned off but new jobs are not being processed.
I guess this is a two part question.
Part 1 (Specific noob-like question): When I run heroku pg:psql to look at
the queue_classic_jobs table I can get the count, but when I try a select
on the table all I get is a giant black space where the rows should be.
Any idea why its not showing the rows? Is this normal? Is it due to the
lock on the table? or is something really not right here?
Part 2 (Bigger vague question): So asides from the psql output not being
helpful there is a bigger issue. A job is getting stuck and I need to
track down the culprit.
When processing some of the xml there have been some validation errors
that have caused the job to get stopped in its tracks. Is it possible that
these errors are stopping QC from closing off the job properly? Do I need
to / How do I handle this?
Or is it possible that this is something crazy silly like a job comes in
at the same time that HireFire tries to turn off the worker and it never
gets sent through to the background job properly or ... something ... ?!
Thoughts?
stuck Queue Classic job?
I am trying to track down what is happening with a stuck background
process in my app and need a push in the right direction.
I have a rails app on heroku that is processing some xml. This is done in
a background job using Queue Classic. I also have HireFire setup to turn
the workers on and off when they are not needed.
This seems to be working for the most part. However, every now and then it
seems like a job is getting stuck and causing all manner of havoc: Workers
are not turned off but new jobs are not being processed.
I guess this is a two part question.
Part 1 (Specific noob-like question): When I run heroku pg:psql to look at
the queue_classic_jobs table I can get the count, but when I try a select
on the table all I get is a giant black space where the rows should be.
Any idea why its not showing the rows? Is this normal? Is it due to the
lock on the table? or is something really not right here?
Part 2 (Bigger vague question): So asides from the psql output not being
helpful there is a bigger issue. A job is getting stuck and I need to
track down the culprit.
When processing some of the xml there have been some validation errors
that have caused the job to get stopped in its tracks. Is it possible that
these errors are stopping QC from closing off the job properly? Do I need
to / How do I handle this?
Or is it possible that this is something crazy silly like a job comes in
at the same time that HireFire tries to turn off the worker and it never
gets sent through to the background job properly or ... something ... ?!
Thoughts?
'undefined' is not a function (evaluating '$(document).on')
'undefined' is not a function (evaluating '$(document).on')
I am trying to use this script:
<script>
var original_value =
Number($('#ProductPrice').text().replace(/[^0-9.]+/g,""));
$(document).on('keyup', '#ProductPrice', function() {
if (Number($('#ProductPrice').text().replace(/[^0-9.]+/g,"")) >
original_value) {
$("#ProductPrice").css("color","red");
} else {
$("#ProductPrice").css("color", "black");
}
});
</script>
I keep getting an error:'undefined' is not a function (evaluating
'$(document).on')
Help?
I am trying to use this script:
<script>
var original_value =
Number($('#ProductPrice').text().replace(/[^0-9.]+/g,""));
$(document).on('keyup', '#ProductPrice', function() {
if (Number($('#ProductPrice').text().replace(/[^0-9.]+/g,"")) >
original_value) {
$("#ProductPrice").css("color","red");
} else {
$("#ProductPrice").css("color", "black");
}
});
</script>
I keep getting an error:'undefined' is not a function (evaluating
'$(document).on')
Help?
Polymorphic Association in Active Admin Not Passing All Parameters
Polymorphic Association in Active Admin Not Passing All Parameters
I created a Polymorphic Association in Active Admin for the creation of
Keyword associated with Industry. I can display the association fine in
Active Admin (the association was created in the console) but when I
Update and create New, only the keyword parameters gets passed. If I go
back to the console and update, the updated data is properly displayed in
Active Admin.
I never get an error.
I have:
class Industry < ActiveRecord::Base
attr_accessible :name, :keywords, :keywords_attributes
# Associations
has_many :profiles
has_many :companies
has_many :users
has_many :keywords, as: :keyable
accepts_nested_attributes_for :keywords
end
class Keyword < ActiveRecord::Base
attr_accessible :name, :profile_id, :active,
:keyable_attributes, :rating,
:keyable_id, :keyable_industry
# Associations
belongs_to :profile # FK
belongs_to :keyable, polymorphic: true
accepts_nested_attributes_for :keyable
attr_accessor :keyable_industry
def keyable_industry
self.keyable.id if self.keyable.is_a? Industry
end
end
ActiveAdmin.register Keyword do
index do
column :name
column :active
column :rating
column "Keyword Group", :keyable
column :keyable_type
default_actions
end
form do |f|
f.inputs "Conference Detail" do
f.input :name
f.input :active
f.input :rating
f.input :keyable_industry
end
f.inputs "Industry" do
f.input :keyable_industry, label: "Industry",
:as => :select,
:collection => Industry.all.map {|i| [i.name]},
:include_blank => false
end
f.actions
end
end
Development Log Output
Started PUT "/admin/keywords/2" for 127.0.0.1 at 2013-09-13 11:41:32 -0400
Processing by Admin::KeywordsController#update as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"nnbMIHy1YndWNOKyF+LSABYyeQMpKQAiTyqGbL2sq3g=",
"keyword"=> {"name"=>"test", "active"=>"1", "rating"=>"1",
"keyable_industry"=>"Agriculture & Forestry"}, "commit"=>"Update
Keyword", "id"=>"2"}
User Load (1.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1
LIMIT 1
Keyword Load (0.7ms) SELECT "keywords".* FROM "keywords" WHERE
"keywords"."id" = $1 LIMIT 1 [["id", "2"]]
(0.7ms) BEGIN
(1.1ms) UPDATE "keywords" SET "name" = 'test', "updated_at" =
'2013-09-13 15:41:32.287147' WHERE "keywords"."id" = 2
(2.9ms) COMMIT
Redirected to http://blog.dev/admin/keywords/2
Completed 302 Found in 14ms (ActiveRecord: 0.0ms)
I created a Polymorphic Association in Active Admin for the creation of
Keyword associated with Industry. I can display the association fine in
Active Admin (the association was created in the console) but when I
Update and create New, only the keyword parameters gets passed. If I go
back to the console and update, the updated data is properly displayed in
Active Admin.
I never get an error.
I have:
class Industry < ActiveRecord::Base
attr_accessible :name, :keywords, :keywords_attributes
# Associations
has_many :profiles
has_many :companies
has_many :users
has_many :keywords, as: :keyable
accepts_nested_attributes_for :keywords
end
class Keyword < ActiveRecord::Base
attr_accessible :name, :profile_id, :active,
:keyable_attributes, :rating,
:keyable_id, :keyable_industry
# Associations
belongs_to :profile # FK
belongs_to :keyable, polymorphic: true
accepts_nested_attributes_for :keyable
attr_accessor :keyable_industry
def keyable_industry
self.keyable.id if self.keyable.is_a? Industry
end
end
ActiveAdmin.register Keyword do
index do
column :name
column :active
column :rating
column "Keyword Group", :keyable
column :keyable_type
default_actions
end
form do |f|
f.inputs "Conference Detail" do
f.input :name
f.input :active
f.input :rating
f.input :keyable_industry
end
f.inputs "Industry" do
f.input :keyable_industry, label: "Industry",
:as => :select,
:collection => Industry.all.map {|i| [i.name]},
:include_blank => false
end
f.actions
end
end
Development Log Output
Started PUT "/admin/keywords/2" for 127.0.0.1 at 2013-09-13 11:41:32 -0400
Processing by Admin::KeywordsController#update as HTML
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"nnbMIHy1YndWNOKyF+LSABYyeQMpKQAiTyqGbL2sq3g=",
"keyword"=> {"name"=>"test", "active"=>"1", "rating"=>"1",
"keyable_industry"=>"Agriculture & Forestry"}, "commit"=>"Update
Keyword", "id"=>"2"}
User Load (1.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1
LIMIT 1
Keyword Load (0.7ms) SELECT "keywords".* FROM "keywords" WHERE
"keywords"."id" = $1 LIMIT 1 [["id", "2"]]
(0.7ms) BEGIN
(1.1ms) UPDATE "keywords" SET "name" = 'test', "updated_at" =
'2013-09-13 15:41:32.287147' WHERE "keywords"."id" = 2
(2.9ms) COMMIT
Redirected to http://blog.dev/admin/keywords/2
Completed 302 Found in 14ms (ActiveRecord: 0.0ms)
Thursday, 12 September 2013
LZMA and TAR or TARBALL, 7zip for multiple files
LZMA and TAR or TARBALL, 7zip for multiple files
I have read through that ZIP or TAR is file archiver, while LZMA is a
compression algorithm. However, to use LZMA for multiple files in command
line, any idea how to decompress it via LZMA decompress? Should it be
integrated with TAR or ZIP?
Thanks
I have read through that ZIP or TAR is file archiver, while LZMA is a
compression algorithm. However, to use LZMA for multiple files in command
line, any idea how to decompress it via LZMA decompress? Should it be
integrated with TAR or ZIP?
Thanks
how to show data store grid on ext.window.window.modal
how to show data store grid on ext.window.window.modal
I have a problem rendering data store grid on window modal.
here's the code on data.store :
var list_pp = Ext.create('Ext.data.Store', {
pageSize: itemsPerPage,
model: 'list_pp',
proxy: {
type: 'ajax',
api: {
read: pp_get_url,
create: pp_set_url,
update: pp_up_url,
destroy: pp_del_url
},
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
},
writer: {
type: 'json',
writeAllFields: true,
root: 'data'
}
},
//autoLoad: false,
listeners: {
write: function(store, operation){
var record = operation.getRecords()[0],
name = Ext.String.capitalize(operation.action),
verb;
}
}
});
here's the code that render on some page :
var grid_pp_list = Ext.create('Ext.grid.Panel',
{
width: '100%',
frame: false,
loadMask: true,
collapsible: false,
title: 'Detail PP',
store: list_pp,
columns: [
{
header: 'No PP',
width: 130,
sortable: true,
dataIndex: 'doc_no',
xtype: 'templatecolumn',
tpl: '<a
href="./pp/detail/{pp_id}">{doc_no}</a><br/>{pp_id}/{sifat}<br/>'
}, {
header: 'Tgl.',
width: 100,
sortable: true,
dataIndex: 'pp_date',
xtype: 'datecolumn',
format:'y-m-d'
}, {
header: 'SBU Pemesan',
width: 160,
sortable: true,
dataIndex: 'org_order',
xtype: 'templatecolumn',
tpl: '<a href="/org/{org_id}">{org_order}</a>'
},{
header: 'Validasi',
width: 160,
sortable: true,
dataIndex: 'org_order',
xtype: 'templatecolumn',
tpl: '<a href="/org/{org_id}">{org_order}</a>'
},{
header: 'Action',
xtype: 'actioncolumn',
width: 60,
sortable: false,
menuDisabled: true,
xtype: 'templatecolumn',
tpl: '<a href="./pp/detail/{pp_id}" class="btn btn-small
btn-primary">Detail</a>'
},{
header: 'Modified by',
width: 120,
dataIndex: 'modified_by',
sortable: true,
xtype: 'templatecolumn',
tpl: '<a href="/user/{modified_by}"><i
class="icon-user"></i>{modified_by}</a>'
},{
header: 'Modified Date',
width: 120,
sortable: true,
dataIndex: 'modified_date',
xtype: 'datecolumn',
format:'y-m-d H:m:s'
}]
here's the code on window modal :
var modal_pp = Ext.create('Ext.grid.Panel',
{
width: '100%',
frame: false,
loadMask: true,
collapsible: false,
title: 'Modal PP',
store: list_pp,
columns: [
{
header: 'No PP',
width: 130,
sortable: true,
dataIndex: 'doc_no',
xtype: 'templatecolumn',
tpl: '<a
href="./pp/detail/{pp_id}">{doc_no}</a><br/>{pp_id}/{sifat}<br/>'
}, {
header: 'Tgl.',
width: 100,
sortable: true,
dataIndex: 'pp_date',
xtype: 'datecolumn',
format:'y-m-d'
}, {
header: 'SBU Pemesan',
width: 160,
sortable: true,
dataIndex: 'org_order',
xtype: 'templatecolumn',
tpl: '<a href="/org/{org_id}">{org_order}</a>'
}],
dockedItems:
[{
xtype: 'pagingtoolbar',
store: list_pp, // same store GridPanel
dock: 'bottom',
displayInfo: true
}]
});
here's generate trigger button trigger for modal window:
text: 'Generate',
iconCls: 'icon-add',
handler: function(){
if (!win) {
win = Ext.widget('window', {
closeAction: 'hide',
width: 1000,
height: 620,
minWidth: 300,
minHeight: 300,
layout: 'fit',
resizable: true,
modal: true,
items: modal_pp
});
}
win.show();
}
in rendering page everything is fine, but in window modal i can't render
data store. please if anyone can give a guide or help i will be really
appreciate it.
I have a problem rendering data store grid on window modal.
here's the code on data.store :
var list_pp = Ext.create('Ext.data.Store', {
pageSize: itemsPerPage,
model: 'list_pp',
proxy: {
type: 'ajax',
api: {
read: pp_get_url,
create: pp_set_url,
update: pp_up_url,
destroy: pp_del_url
},
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
},
writer: {
type: 'json',
writeAllFields: true,
root: 'data'
}
},
//autoLoad: false,
listeners: {
write: function(store, operation){
var record = operation.getRecords()[0],
name = Ext.String.capitalize(operation.action),
verb;
}
}
});
here's the code that render on some page :
var grid_pp_list = Ext.create('Ext.grid.Panel',
{
width: '100%',
frame: false,
loadMask: true,
collapsible: false,
title: 'Detail PP',
store: list_pp,
columns: [
{
header: 'No PP',
width: 130,
sortable: true,
dataIndex: 'doc_no',
xtype: 'templatecolumn',
tpl: '<a
href="./pp/detail/{pp_id}">{doc_no}</a><br/>{pp_id}/{sifat}<br/>'
}, {
header: 'Tgl.',
width: 100,
sortable: true,
dataIndex: 'pp_date',
xtype: 'datecolumn',
format:'y-m-d'
}, {
header: 'SBU Pemesan',
width: 160,
sortable: true,
dataIndex: 'org_order',
xtype: 'templatecolumn',
tpl: '<a href="/org/{org_id}">{org_order}</a>'
},{
header: 'Validasi',
width: 160,
sortable: true,
dataIndex: 'org_order',
xtype: 'templatecolumn',
tpl: '<a href="/org/{org_id}">{org_order}</a>'
},{
header: 'Action',
xtype: 'actioncolumn',
width: 60,
sortable: false,
menuDisabled: true,
xtype: 'templatecolumn',
tpl: '<a href="./pp/detail/{pp_id}" class="btn btn-small
btn-primary">Detail</a>'
},{
header: 'Modified by',
width: 120,
dataIndex: 'modified_by',
sortable: true,
xtype: 'templatecolumn',
tpl: '<a href="/user/{modified_by}"><i
class="icon-user"></i>{modified_by}</a>'
},{
header: 'Modified Date',
width: 120,
sortable: true,
dataIndex: 'modified_date',
xtype: 'datecolumn',
format:'y-m-d H:m:s'
}]
here's the code on window modal :
var modal_pp = Ext.create('Ext.grid.Panel',
{
width: '100%',
frame: false,
loadMask: true,
collapsible: false,
title: 'Modal PP',
store: list_pp,
columns: [
{
header: 'No PP',
width: 130,
sortable: true,
dataIndex: 'doc_no',
xtype: 'templatecolumn',
tpl: '<a
href="./pp/detail/{pp_id}">{doc_no}</a><br/>{pp_id}/{sifat}<br/>'
}, {
header: 'Tgl.',
width: 100,
sortable: true,
dataIndex: 'pp_date',
xtype: 'datecolumn',
format:'y-m-d'
}, {
header: 'SBU Pemesan',
width: 160,
sortable: true,
dataIndex: 'org_order',
xtype: 'templatecolumn',
tpl: '<a href="/org/{org_id}">{org_order}</a>'
}],
dockedItems:
[{
xtype: 'pagingtoolbar',
store: list_pp, // same store GridPanel
dock: 'bottom',
displayInfo: true
}]
});
here's generate trigger button trigger for modal window:
text: 'Generate',
iconCls: 'icon-add',
handler: function(){
if (!win) {
win = Ext.widget('window', {
closeAction: 'hide',
width: 1000,
height: 620,
minWidth: 300,
minHeight: 300,
layout: 'fit',
resizable: true,
modal: true,
items: modal_pp
});
}
win.show();
}
in rendering page everything is fine, but in window modal i can't render
data store. please if anyone can give a guide or help i will be really
appreciate it.
MapFragment manager error in sub class of app
MapFragment manager error in sub class of app
I am trying to make a class that deals with the various googleMap realated
functions and tasks.
This includes setting up the map itself, handling markers etc.
My problem is... the code I have works fine if its all in the same file as
my main activity, however the following does not work when I move it into
a separate class.
UPDATE
public class Mapper extends Activity {
GoogleMap googleMap;
public Mapper(Context context) {
this.context = context;
getMap();
}
private void getMap() {
googleMap =
((MapFragment)getFragmentManager().findFragmentById(R.id.googleMap)).getMap();
}
}
I get the following error:
http://puu.sh/4pLxT.png
I am really unsure as to why it works in the main class but not this one.
Any help would be amazing!
I am trying to make a class that deals with the various googleMap realated
functions and tasks.
This includes setting up the map itself, handling markers etc.
My problem is... the code I have works fine if its all in the same file as
my main activity, however the following does not work when I move it into
a separate class.
UPDATE
public class Mapper extends Activity {
GoogleMap googleMap;
public Mapper(Context context) {
this.context = context;
getMap();
}
private void getMap() {
googleMap =
((MapFragment)getFragmentManager().findFragmentById(R.id.googleMap)).getMap();
}
}
I get the following error:
http://puu.sh/4pLxT.png
I am really unsure as to why it works in the main class but not this one.
Any help would be amazing!
What DLL do I need to place at system32 to connect to remote MSSQL using VB6
What DLL do I need to place at system32 to connect to remote MSSQL using VB6
This is the error:
[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access
denied.
I'm using 32bit, the server is configured to accept remote access, I can
even open it using management studio remotely.
My app is working perfectly in local but not in remote.
this is my connection string:
Provider=SQLOLEDB;Password=1234;Persist Security Info=True;User
ID=sa;Initial Catalog=test;Data Source=127.0.0.1
I just change the ip to the ip of remote server, but what dll will I need
w/o using ODBC and installing mssql to client unit?
This is the error:
[DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access
denied.
I'm using 32bit, the server is configured to accept remote access, I can
even open it using management studio remotely.
My app is working perfectly in local but not in remote.
this is my connection string:
Provider=SQLOLEDB;Password=1234;Persist Security Info=True;User
ID=sa;Initial Catalog=test;Data Source=127.0.0.1
I just change the ip to the ip of remote server, but what dll will I need
w/o using ODBC and installing mssql to client unit?
Creating specified UIColor in iOS
Creating specified UIColor in iOS
I have to create the text color as shown in the picture, can someone help
me with the RGB values for the specified colour.
I have to create the text color as shown in the picture, can someone help
me with the RGB values for the specified colour.
Wednesday, 11 September 2013
How to attach two sprites andengine
How to attach two sprites andengine
I am working on andengine and i have two sprite,sprite A and sprite B.Now
i want to attach sprite B to sprite A..but i already attach a body to
sprite A with the help of PhysicsConnector..then how to do it..please help
me.. Here is my code:
`final int centerX = (this.mspriteATextureRegion.getWidth()); final int
centerY = (CAMERA_HEIGHT - this.mSpriteATextureRegion.getHeight()) / 2;
final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(0,
0.5f, 0.5f);
spriteA= new Sprite(centerX, centerY, this.mSpriteATextureRegion);
body = PhysicsFactory.createBoxBody(mPhysicsWorld, spriteA,
BodyType.DynamicBody, objectFixtureDef);
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(spriteA,
body, true, true));
final PhysicsHandler physicsHandler = new PhysicsHandler(spriteA);
spriteA.registerUpdateHandler(physicsHandler);
spriteB= new Sprite(centerX, centerY, this.mSpriteBTextureRegion);
spriteA.attachChild(spriteB,2);
scene.attachChild(spriteA,1);`
i am moving the sprite A with help oh anolog control.its not properly work..
I am working on andengine and i have two sprite,sprite A and sprite B.Now
i want to attach sprite B to sprite A..but i already attach a body to
sprite A with the help of PhysicsConnector..then how to do it..please help
me.. Here is my code:
`final int centerX = (this.mspriteATextureRegion.getWidth()); final int
centerY = (CAMERA_HEIGHT - this.mSpriteATextureRegion.getHeight()) / 2;
final FixtureDef objectFixtureDef = PhysicsFactory.createFixtureDef(0,
0.5f, 0.5f);
spriteA= new Sprite(centerX, centerY, this.mSpriteATextureRegion);
body = PhysicsFactory.createBoxBody(mPhysicsWorld, spriteA,
BodyType.DynamicBody, objectFixtureDef);
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(spriteA,
body, true, true));
final PhysicsHandler physicsHandler = new PhysicsHandler(spriteA);
spriteA.registerUpdateHandler(physicsHandler);
spriteB= new Sprite(centerX, centerY, this.mSpriteBTextureRegion);
spriteA.attachChild(spriteB,2);
scene.attachChild(spriteA,1);`
i am moving the sprite A with help oh anolog control.its not properly work..
How to dismiss keyboard iOS programmatically
How to dismiss keyboard iOS programmatically
I created a UITextField programmatically making the UITextField a property
of the viewController. I need to dismiss the keyboard with the return and
the touch on the screen. I was able to get the screen touch to dismiss,
but pressing return is not working.
I've seen how to do it with storyboards and by allocating and initializing
the UITextField object directly without creating it as a property.
Possible to do? I am a noob - sorry!
.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextFieldDelegate>
@property (strong, atomic) UITextField *username;
@end
.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor blueColor];
self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25,
80, 20)];
self.username.placeholder = @"Enter your username";
self.username.backgroundColor = [UIColor whiteColor];
self.username.borderStyle = UITextBorderStyleRoundedRect;
if (self.username.placeholder != nil) {
self.username.clearsOnBeginEditing = NO;
}
_username.delegate = self;
[self.view addSubview:self.username];
[_username resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"touchesBegan:withEvent:");
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
@end
I created a UITextField programmatically making the UITextField a property
of the viewController. I need to dismiss the keyboard with the return and
the touch on the screen. I was able to get the screen touch to dismiss,
but pressing return is not working.
I've seen how to do it with storyboards and by allocating and initializing
the UITextField object directly without creating it as a property.
Possible to do? I am a noob - sorry!
.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextFieldDelegate>
@property (strong, atomic) UITextField *username;
@end
.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor blueColor];
self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25,
80, 20)];
self.username.placeholder = @"Enter your username";
self.username.backgroundColor = [UIColor whiteColor];
self.username.borderStyle = UITextBorderStyleRoundedRect;
if (self.username.placeholder != nil) {
self.username.clearsOnBeginEditing = NO;
}
_username.delegate = self;
[self.view addSubview:self.username];
[_username resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSLog(@"touchesBegan:withEvent:");
[self.view endEditing:YES];
[super touchesBegan:touches withEvent:event];
}
@end
How do I: ORDER BY COUNT(column1) from the result of: SELECT DISTINCT column1, column2
How do I: ORDER BY COUNT(column1) from the result of: SELECT DISTINCT
column1, column2
Because the title is probably bad, and I'm very weak with SQL, I'll try to
clarify my goal:
if:
SELECT DISTINCT host, author FROM t;
Looks like:
foo.com | John
bar.com | Bob
bar.com | Alice
How do I get results like:
foo.com | 1
bar.com | 2
Let me know if this isn't clear enough, and I will update, or respond to
comments.
column1, column2
Because the title is probably bad, and I'm very weak with SQL, I'll try to
clarify my goal:
if:
SELECT DISTINCT host, author FROM t;
Looks like:
foo.com | John
bar.com | Bob
bar.com | Alice
How do I get results like:
foo.com | 1
bar.com | 2
Let me know if this isn't clear enough, and I will update, or respond to
comments.
#EANF#
#EANF#
I'm trying to add another parameter using a hidden input:
$('#form1').submit(function(){ //listen for submit event
$('<input />').attr('type', 'hidden')
.attr('name', id)
.attr('value', id)
.appendTo('#form1');
return true;
});
My HTML form:
<form id="form1" method=POST runat="server" enctype='multipart/form-data'
action="/set_image">
<div class="fileButtons">
<input type='file' id="imgInp" name="imgInp" accept="image/*"/>
<input type='button' id='remove' name="remove" value='Remove' />
</div>
<br>
<div class="modal-footer">
<a type="button" class="btn pull-left"
data-dismiss="modal">Cancel</a>
<button type="submit" class="btn btn-primary pull-left">OK</button>
</div>
</form>
The function jumps to "return true" without doing anything.
I used the post in here:
http://stackoverflow.com/a/993897/2653179
I'm trying to add another parameter using a hidden input:
$('#form1').submit(function(){ //listen for submit event
$('<input />').attr('type', 'hidden')
.attr('name', id)
.attr('value', id)
.appendTo('#form1');
return true;
});
My HTML form:
<form id="form1" method=POST runat="server" enctype='multipart/form-data'
action="/set_image">
<div class="fileButtons">
<input type='file' id="imgInp" name="imgInp" accept="image/*"/>
<input type='button' id='remove' name="remove" value='Remove' />
</div>
<br>
<div class="modal-footer">
<a type="button" class="btn pull-left"
data-dismiss="modal">Cancel</a>
<button type="submit" class="btn btn-primary pull-left">OK</button>
</div>
</form>
The function jumps to "return true" without doing anything.
I used the post in here:
http://stackoverflow.com/a/993897/2653179
RAILS - tacking on a message when form is submitted
RAILS - tacking on a message when form is submitted
I can't seem to figure this out or find a solution to this
anywhere...which is crazy to me since i feel like its pretty common and
simple
I want to add a little message that my client will see when the user sends
them a request through the form and then it goes to an external API where
they can see created tickets.
so right now my client sees
John Doe
but i want them to see
Web inquiry from John Doe
So i need to send the "Web inquiry from" part through the form
i've tried to interpolate it in the form
= f.text_field "Web inquiry from #{:subject}"
that didnt work
i've tried to add a value (not the way i want to go but i tried it anyway)
= f.text_field :subject, value: "Web inquiry from #{f.object.subject}"
that did not work either
i've tried to place it in the model
def post_tickets(params)
client.subject = "Hello from, " + client.subject
end
I'm new to rails so if you could be specific as possible that would be
helpful...please dont say just do it in the controller.....thank you in
advanced
here is my form
= form_for(:contacts, url: contacts_path) do |f|
= f.error_messages
= f.label :subject, "Name"
%span{style: 'color: red'} *
= f.text_field :subject, class: "text_field width_100_percent"
%br
%br
= f.label "Email"
%span{style: 'color: red'} *
%br
= f.email_field :email, class: "text_field width_100_percent"
%br
%br
= f.label "Question(s), and/or feedback"
%span{style: 'color: red'} *
%br
= f.text_area :description, class: "text_field width_100_percent", style:
'height: 100px;'
%br
%br
= f.submit "Submit", class: 'btn btn-warning'
here is my controller
class Website::ContactsController < Website::WebsiteApplicationController
def new
@contacts = Form.new
end
def create
@contacts = Form.new(params[:contacts])
@contacts.post_tickets(params[:contacts])
if @contacts.valid?
flash[:success] = "Message sent! Thank you for conacting us."
redirect_to new_contact_path
else
flash[:alert] = "Please fill in the required fields"
render action: 'new'
end
end
end
here is my model
class Form
include ActiveModel::Validations
include ActiveModel::Conversion
include ActiveModel::Translation
extend ActiveModel::Naming
attr_accessor :config, :client, :subject, :email,
:custom_field_phone_number_28445,
:custom_field_name_28445, :custom_field_company_28445,
:description,
:custom_field
validates_presence_of :subject, :message => '^Please enter your name'
validates_presence_of :description, :message => '^Question(s), and/or
feedback can not be blank'
validates :email, presence: true
validates_format_of :email, :with =>
/^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
def initialize(attributes = {})
attributes.each do |name, value|
@attributes = attributes
end
self.config =
YAML.load_file("#{Rails.root}/config/fresh_desk.yml")[Rails.env]
self.client = Freshdesk.new(config[:url], config[:api_key],
config[:password])
end
def read_attribute_for_validation(key)
@attributes[key]
end
def post_tickets(params)
client.post_tickets(params)
end
def persisted?
false
end
end
I can't seem to figure this out or find a solution to this
anywhere...which is crazy to me since i feel like its pretty common and
simple
I want to add a little message that my client will see when the user sends
them a request through the form and then it goes to an external API where
they can see created tickets.
so right now my client sees
John Doe
but i want them to see
Web inquiry from John Doe
So i need to send the "Web inquiry from" part through the form
i've tried to interpolate it in the form
= f.text_field "Web inquiry from #{:subject}"
that didnt work
i've tried to add a value (not the way i want to go but i tried it anyway)
= f.text_field :subject, value: "Web inquiry from #{f.object.subject}"
that did not work either
i've tried to place it in the model
def post_tickets(params)
client.subject = "Hello from, " + client.subject
end
I'm new to rails so if you could be specific as possible that would be
helpful...please dont say just do it in the controller.....thank you in
advanced
here is my form
= form_for(:contacts, url: contacts_path) do |f|
= f.error_messages
= f.label :subject, "Name"
%span{style: 'color: red'} *
= f.text_field :subject, class: "text_field width_100_percent"
%br
%br
= f.label "Email"
%span{style: 'color: red'} *
%br
= f.email_field :email, class: "text_field width_100_percent"
%br
%br
= f.label "Question(s), and/or feedback"
%span{style: 'color: red'} *
%br
= f.text_area :description, class: "text_field width_100_percent", style:
'height: 100px;'
%br
%br
= f.submit "Submit", class: 'btn btn-warning'
here is my controller
class Website::ContactsController < Website::WebsiteApplicationController
def new
@contacts = Form.new
end
def create
@contacts = Form.new(params[:contacts])
@contacts.post_tickets(params[:contacts])
if @contacts.valid?
flash[:success] = "Message sent! Thank you for conacting us."
redirect_to new_contact_path
else
flash[:alert] = "Please fill in the required fields"
render action: 'new'
end
end
end
here is my model
class Form
include ActiveModel::Validations
include ActiveModel::Conversion
include ActiveModel::Translation
extend ActiveModel::Naming
attr_accessor :config, :client, :subject, :email,
:custom_field_phone_number_28445,
:custom_field_name_28445, :custom_field_company_28445,
:description,
:custom_field
validates_presence_of :subject, :message => '^Please enter your name'
validates_presence_of :description, :message => '^Question(s), and/or
feedback can not be blank'
validates :email, presence: true
validates_format_of :email, :with =>
/^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i
def initialize(attributes = {})
attributes.each do |name, value|
@attributes = attributes
end
self.config =
YAML.load_file("#{Rails.root}/config/fresh_desk.yml")[Rails.env]
self.client = Freshdesk.new(config[:url], config[:api_key],
config[:password])
end
def read_attribute_for_validation(key)
@attributes[key]
end
def post_tickets(params)
client.post_tickets(params)
end
def persisted?
false
end
end
Nesting a bunch of divs neatly inside one another with borders
Nesting a bunch of divs neatly inside one another with borders
I need your help,
The divs appear to be nested properly (left, top and right) borders line
up but at the bottom it seems that they are longer than that of the
container div.
See pic here:
Here is the HTML coding:
<!DOCTYPE html>
<html>
<head>
<title>Centered Div</title>
<style>
body { background: #000; }
#wrapper {
height: 100px;
width: 500px;
}
#wrapper {
bottom: 50%;
right: 50%;
position: absolute;
}
#container {
background: rgb(230,230,230);
left: 50%;
padding: 10px;
top: 50%;
margin: 0;
padding: 0;
height: 100%;
border: 1px solid red;
height: 100%;
position: relative;
}
#inner1 {
height: 100%;
border: 1px solid blue;
}
#inner2 {
height: 100%;
border: 1px solid green;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="container">
<div id="inner1">
<div id="inner2"></div>
</div>
</div>
</div>
</body>
</html>
I need your help,
The divs appear to be nested properly (left, top and right) borders line
up but at the bottom it seems that they are longer than that of the
container div.
See pic here:
Here is the HTML coding:
<!DOCTYPE html>
<html>
<head>
<title>Centered Div</title>
<style>
body { background: #000; }
#wrapper {
height: 100px;
width: 500px;
}
#wrapper {
bottom: 50%;
right: 50%;
position: absolute;
}
#container {
background: rgb(230,230,230);
left: 50%;
padding: 10px;
top: 50%;
margin: 0;
padding: 0;
height: 100%;
border: 1px solid red;
height: 100%;
position: relative;
}
#inner1 {
height: 100%;
border: 1px solid blue;
}
#inner2 {
height: 100%;
border: 1px solid green;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="container">
<div id="inner1">
<div id="inner2"></div>
</div>
</div>
</div>
</body>
</html>
Regular expression to match float number pattern
Regular expression to match float number pattern
Here is the pattern I am looking to match with. I have started something
like this ^\d{1,}.^\d{1,}$ not sure to complete this.
x
x.x
x cannot be zero (0 or 0.00 are not allowed but can be 1.02 or 0.123)
Length of all x including decimals(if any) should not exceed 11 digits
minimum 1 x is required
only 1 decimal is allowed
this is required field
Note: I am referring x as digit
I would like to use this RegEx both in HTML5 Pattern attribute and in
JavaScript string.match("")
clarity: I mean "1.02" is allowed, but "0" or "0.0" is not allowed
Here is the pattern I am looking to match with. I have started something
like this ^\d{1,}.^\d{1,}$ not sure to complete this.
x
x.x
x cannot be zero (0 or 0.00 are not allowed but can be 1.02 or 0.123)
Length of all x including decimals(if any) should not exceed 11 digits
minimum 1 x is required
only 1 decimal is allowed
this is required field
Note: I am referring x as digit
I would like to use this RegEx both in HTML5 Pattern attribute and in
JavaScript string.match("")
clarity: I mean "1.02" is allowed, but "0" or "0.0" is not allowed
Ajax AutoComplete Extender with ContextKeye not working
Ajax AutoComplete Extender with ContextKeye not working
ASPX CODE:
`
function setContextKey() {
$find('AutoCompExt2').set_contextKey($get("<%=TxtSyllabus.ClientID
%>").value)
alert(("<%=TxtSyllabus.ClientID %>").value)}
</script>
<asp:TextBox ID = "TxtSem" runat = "server" Width = "200px"
onkeyup="setContextKey()"></asp:TextBox>
<asp:AutoCompleteExtender ID = "AutoCompExt2" runat = "server"
MinimumPrefixLength="2" CompletionInterval="100" FirstRowSelected =
"false" TargetControlID= "TxtSem" EnableCaching = "false"
CompletionSetCount = "10" ServiceMethod = "SearchSem" UseContextKey=
"true" ></asp:AutoCompleteExtender>
VB CODE:
<System.Web.Script.Services.ScriptMethod(),
System.Web.Services.WebMethod()> _
Public Shared Function SearchSem(ByVal prefixText As String, ByVal count
As Integer, ByVal contextKey As String) As List(Of String)
Try
Dim cnn As New SqlConnection
Dim cmd As New SqlCommand`
Dim ds As New Data.DataSet
Dim SyllabusName = Mid(contextKey, 1, Len(contextKey) - 4)
Dim Year = Mid(contextKey, Len(contextKey) - 4, Len(contextKey))
cnn.ConnectionString =
ConfigurationManager.ConnectionStrings("excelconn").ToString()
cmd.CommandText = "Select Semester From MastLookup where
SyllabusName='" & SyllabusName & "' And SyllabusYear='" & Year &
"' And Semester=@SearchText + '%'"
cmd.Parameters.AddWithValue("SearchText", prefixText)
cmd.CommandType = Data.CommandType.Text
cmd.Connection = cnn
cnn.Open()
Dim Syllabus As List(Of String) = New List(Of String)
Dim sdr As SqlDataReader = cmd.ExecuteReader
While sdr.Read
Syllabus.Add(sdr("Semester").ToString)
End While
cnn.Close()
Return Syllabus
cnn.Close()
Catch ex As Exception
End Try
End Function
ERROR: I am getting contexKey value equal to null.
even my Javascript is not called when i run the project.
ASPX CODE:
`
function setContextKey() {
$find('AutoCompExt2').set_contextKey($get("<%=TxtSyllabus.ClientID
%>").value)
alert(("<%=TxtSyllabus.ClientID %>").value)}
</script>
<asp:TextBox ID = "TxtSem" runat = "server" Width = "200px"
onkeyup="setContextKey()"></asp:TextBox>
<asp:AutoCompleteExtender ID = "AutoCompExt2" runat = "server"
MinimumPrefixLength="2" CompletionInterval="100" FirstRowSelected =
"false" TargetControlID= "TxtSem" EnableCaching = "false"
CompletionSetCount = "10" ServiceMethod = "SearchSem" UseContextKey=
"true" ></asp:AutoCompleteExtender>
VB CODE:
<System.Web.Script.Services.ScriptMethod(),
System.Web.Services.WebMethod()> _
Public Shared Function SearchSem(ByVal prefixText As String, ByVal count
As Integer, ByVal contextKey As String) As List(Of String)
Try
Dim cnn As New SqlConnection
Dim cmd As New SqlCommand`
Dim ds As New Data.DataSet
Dim SyllabusName = Mid(contextKey, 1, Len(contextKey) - 4)
Dim Year = Mid(contextKey, Len(contextKey) - 4, Len(contextKey))
cnn.ConnectionString =
ConfigurationManager.ConnectionStrings("excelconn").ToString()
cmd.CommandText = "Select Semester From MastLookup where
SyllabusName='" & SyllabusName & "' And SyllabusYear='" & Year &
"' And Semester=@SearchText + '%'"
cmd.Parameters.AddWithValue("SearchText", prefixText)
cmd.CommandType = Data.CommandType.Text
cmd.Connection = cnn
cnn.Open()
Dim Syllabus As List(Of String) = New List(Of String)
Dim sdr As SqlDataReader = cmd.ExecuteReader
While sdr.Read
Syllabus.Add(sdr("Semester").ToString)
End While
cnn.Close()
Return Syllabus
cnn.Close()
Catch ex As Exception
End Try
End Function
ERROR: I am getting contexKey value equal to null.
even my Javascript is not called when i run the project.
Mail attachment download in WebView Windows8.1
Mail attachment download in WebView Windows8.1
I am trying to download attachment of my web email by opening it in
webview of windwos8.1. But whenever I click on download it, I am directed
to IE asking to login and after that download happens. And also download
link doesn't end with ".zip",".pdf" for example but is
*
https:/abcd.mail.com/xyz/attachment.ashx?`attach=1&id=RgAAAABad%2bfJqXwSQa2v%2b1otLJGzBwByBRTOAw%2fVTovnczC49w01AAAADlTIAAB11uY6DrbwRaG30brbaRZqAAAZC7D3AAAJ&attid0=BAAAAAAA&attcnt=1*`
Can anyone tell me how to do it in webview single Window application, so
that it is not directed to IE when download attachment is clicked?
I am trying to download attachment of my web email by opening it in
webview of windwos8.1. But whenever I click on download it, I am directed
to IE asking to login and after that download happens. And also download
link doesn't end with ".zip",".pdf" for example but is
*
https:/abcd.mail.com/xyz/attachment.ashx?`attach=1&id=RgAAAABad%2bfJqXwSQa2v%2b1otLJGzBwByBRTOAw%2fVTovnczC49w01AAAADlTIAAB11uY6DrbwRaG30brbaRZqAAAZC7D3AAAJ&attid0=BAAAAAAA&attcnt=1*`
Can anyone tell me how to do it in webview single Window application, so
that it is not directed to IE when download attachment is clicked?
Tuesday, 10 September 2013
CSS gradients vs background Image?
CSS gradients vs background Image?
Some years ago, I've seen a lot of CSS codes using background-image:
url(xxx.png) simulating a gradient background filter, since only (please,
correct if I'm wrong here) IE proprietary filter would provide CSS
gradient.
Nowadays - keeping in mind the most used browsers today and portable
devices browsers (smartphones/tablets), should I use:
CSS gradients, with 1 background property for each engine
OR
background-image: url(xxx.png), 1 tiny image (but still a browser request);
?
And how about IE9 issue there I have seen in some CSS gradient generators?
Some years ago, I've seen a lot of CSS codes using background-image:
url(xxx.png) simulating a gradient background filter, since only (please,
correct if I'm wrong here) IE proprietary filter would provide CSS
gradient.
Nowadays - keeping in mind the most used browsers today and portable
devices browsers (smartphones/tablets), should I use:
CSS gradients, with 1 background property for each engine
OR
background-image: url(xxx.png), 1 tiny image (but still a browser request);
?
And how about IE9 issue there I have seen in some CSS gradient generators?
Creating a compass on a non-directionally aware device
Creating a compass on a non-directionally aware device
I need to develop a compass for a device we are using. This device is
directionally unaware (no gyroscope), but has a GPS module. How can I make
a compass, with a needle, that leads from a start coordinate (likely their
current position) to an end coordinate?
My current thoughts are:
Poll coordinates on the GPS sensor as quickly as appropriate.
Record coordinates where the PDOP is within a respectable range (maybe
less than 2.0).
Determine the direction they are facing based on the coordinate changes of
them walking.
I have a few issues with this though:
Firstly, the unit has to be moved around to get a sense of where they are.
Doesn't seem like it would be the most accurate, i.e. how many past points
do you use to determine direction change?
I'm not really sure if this is a feasible solution. Is there some
implementation theory I can read on this?
Is there a better way to solve my problem? The scope of the project
involves going from a 'current location' to some geo-tagged item in an oil
field.
Using a Windows Mobile 6.5 device - C# on VS2008.
I need to develop a compass for a device we are using. This device is
directionally unaware (no gyroscope), but has a GPS module. How can I make
a compass, with a needle, that leads from a start coordinate (likely their
current position) to an end coordinate?
My current thoughts are:
Poll coordinates on the GPS sensor as quickly as appropriate.
Record coordinates where the PDOP is within a respectable range (maybe
less than 2.0).
Determine the direction they are facing based on the coordinate changes of
them walking.
I have a few issues with this though:
Firstly, the unit has to be moved around to get a sense of where they are.
Doesn't seem like it would be the most accurate, i.e. how many past points
do you use to determine direction change?
I'm not really sure if this is a feasible solution. Is there some
implementation theory I can read on this?
Is there a better way to solve my problem? The scope of the project
involves going from a 'current location' to some geo-tagged item in an oil
field.
Using a Windows Mobile 6.5 device - C# on VS2008.
First value in drop down option should be disabled - Rails
First value in drop down option should be disabled - Rails
I have dropdown list which has the following options
---select an option---
option 1
option 2
option 3
option 4
I want to disable my 1st value ---Select an option--- in dropdown list. So
that it could not be selected as an option.
My code is here
<%= f.select :options, options_for_select([[" ---Select an option---",
""], "option 1", "option 2", "option 3", "option 4"]), {}, :style =>
"margin:20px; width:356px;" %>
How can I implement that??? Thanks.
I have dropdown list which has the following options
---select an option---
option 1
option 2
option 3
option 4
I want to disable my 1st value ---Select an option--- in dropdown list. So
that it could not be selected as an option.
My code is here
<%= f.select :options, options_for_select([[" ---Select an option---",
""], "option 1", "option 2", "option 3", "option 4"]), {}, :style =>
"margin:20px; width:356px;" %>
How can I implement that??? Thanks.
postion to left using position or offset
postion to left using position or offset
I'm using a plugin for image slider and there is not navigation buttons
like this O O O O. So I wanted to make using jquery and having a problem.
I want to take the picture to left of the div. So here is summarized
article with a demo:
html
<div id="banner">
<img class="img1" src="" />
<img class="img2" src="" />
<img class="img3" src="" />
<img class="img4" src="" />
</div>
<ul>
<li class='li1'>one</li>
<li class='li2'>two</li>
<li class='li3'>three</li>
<li class='li4'>four</li>
</ul>
jquery
$('.li4').click(function(){
$('.img4').offset().left;
});
I tried with animate, position, offset and scroll techniques but didn't
result what I want. But also I think I should use scroll method for the
slider. How can I achieve that?
demo
.img4 should be shown at left of the div when clicked to .li4
I'm using a plugin for image slider and there is not navigation buttons
like this O O O O. So I wanted to make using jquery and having a problem.
I want to take the picture to left of the div. So here is summarized
article with a demo:
html
<div id="banner">
<img class="img1" src="" />
<img class="img2" src="" />
<img class="img3" src="" />
<img class="img4" src="" />
</div>
<ul>
<li class='li1'>one</li>
<li class='li2'>two</li>
<li class='li3'>three</li>
<li class='li4'>four</li>
</ul>
jquery
$('.li4').click(function(){
$('.img4').offset().left;
});
I tried with animate, position, offset and scroll techniques but didn't
result what I want. But also I think I should use scroll method for the
slider. How can I achieve that?
demo
.img4 should be shown at left of the div when clicked to .li4
Reading MSBuild arguments from build pre / post events
Reading MSBuild arguments from build pre / post events
I have a post build event that I need to behave differently based on which
build definition it is built from. For example:
Build Def 1: Copy output files & call external script
Build Def 2: Just copy files
I need them both to build under the same configuration, so I thought it
should be possible to pass through a custom property, like this:
/p:myproperty=build1
And then read it. But I can't seem to find any way to do that. The other
option would be to obtain the name of the build itself from within the
build event; although again, I can't see any way to get this.
Can anyone tell me a way to do either of these things or, if not, an
alternative to achieve what I'm trying to?
I have a post build event that I need to behave differently based on which
build definition it is built from. For example:
Build Def 1: Copy output files & call external script
Build Def 2: Just copy files
I need them both to build under the same configuration, so I thought it
should be possible to pass through a custom property, like this:
/p:myproperty=build1
And then read it. But I can't seem to find any way to do that. The other
option would be to obtain the name of the build itself from within the
build event; although again, I can't see any way to get this.
Can anyone tell me a way to do either of these things or, if not, an
alternative to achieve what I'm trying to?
Monday, 9 September 2013
How do I randomly pick an element in each column of a matrix in MATLAB?
How do I randomly pick an element in each column of a matrix in MATLAB?
Question title explains what I would like. For example, if there are 6
elements in a particular column, how do I randomly pick 1 element from
that column. Please keep it simple if possible.
Thanks for the help.
Question title explains what I would like. For example, if there are 6
elements in a particular column, how do I randomly pick 1 element from
that column. Please keep it simple if possible.
Thanks for the help.
OpenGL ES: Screenshot size is different in retina and non-retina devices
OpenGL ES: Screenshot size is different in retina and non-retina devices
I am new in opengl es 2.0 development. The UIImage I got from screenshot
looks good on non-retina devices (iphone 4 and ipad), but when I got
screenshot from retina devices it seems enlarged. Here is the code I used.
-(UIImage *) glToUIImage {
CGSize size = self.view.frame.size;
// the reason I set the height and width up-side-down is because my
// screenshot captured in landscape mode.
int image_height = (int)size.width;
int image_width = (int)size.height;
NSInteger myDataLength = image_width * image_height * 4;
// allocate array and read pixels into it.
GLubyte *buffer = (GLubyte *) malloc(myDataLength);
glReadPixels(0, 0, image_width, image_height, GL_RGBA, GL_UNSIGNED_BYTE,
buffer);
// gl renders "upside down" so swap top to bottom into new array.
// there's gotta be a better way, but this works.
GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
for(int y = 0; y < image_height; y++)
{
for(int x = 0; x < image_width * 4; x++)
{
buffer2[(image_height - 1 - y) * image_width * 4 + x] = buffer[y *
4 * image_width + x];
}
}
// make data provider with data.
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2,
myDataLength, NULL);
// prep the ingredients
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * image_width;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
// make the cgimage
CGImageRef imageRef = CGImageCreate(image_width, image_height,
bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo,
provider, NULL, NO, renderingIntent);
// then make the uiimage from that
UIImage *myImage = [UIImage imageWithCGImage:imageRef];
return myImage;
}
// screenshot function, combined my opengl image with background image and
// saved into Photos.
-(UIImage*)screenshot
{
UIImage *image = [self glToUIImage];
CGRect pos = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContext(image.size);
[image drawInRect:pos];
[self.background.image drawInRect:pos];
UIImage* final = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// final picture I saved into Photos.
return final;
}
Function is working, but the opengl image only shows part in retina
devices, how to solve this problem. Thanks !!!
I am new in opengl es 2.0 development. The UIImage I got from screenshot
looks good on non-retina devices (iphone 4 and ipad), but when I got
screenshot from retina devices it seems enlarged. Here is the code I used.
-(UIImage *) glToUIImage {
CGSize size = self.view.frame.size;
// the reason I set the height and width up-side-down is because my
// screenshot captured in landscape mode.
int image_height = (int)size.width;
int image_width = (int)size.height;
NSInteger myDataLength = image_width * image_height * 4;
// allocate array and read pixels into it.
GLubyte *buffer = (GLubyte *) malloc(myDataLength);
glReadPixels(0, 0, image_width, image_height, GL_RGBA, GL_UNSIGNED_BYTE,
buffer);
// gl renders "upside down" so swap top to bottom into new array.
// there's gotta be a better way, but this works.
GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
for(int y = 0; y < image_height; y++)
{
for(int x = 0; x < image_width * 4; x++)
{
buffer2[(image_height - 1 - y) * image_width * 4 + x] = buffer[y *
4 * image_width + x];
}
}
// make data provider with data.
CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2,
myDataLength, NULL);
// prep the ingredients
int bitsPerComponent = 8;
int bitsPerPixel = 32;
int bytesPerRow = 4 * image_width;
CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
// make the cgimage
CGImageRef imageRef = CGImageCreate(image_width, image_height,
bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo,
provider, NULL, NO, renderingIntent);
// then make the uiimage from that
UIImage *myImage = [UIImage imageWithCGImage:imageRef];
return myImage;
}
// screenshot function, combined my opengl image with background image and
// saved into Photos.
-(UIImage*)screenshot
{
UIImage *image = [self glToUIImage];
CGRect pos = CGRectMake(0, 0, image.size.width, image.size.height);
UIGraphicsBeginImageContext(image.size);
[image drawInRect:pos];
[self.background.image drawInRect:pos];
UIImage* final = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// final picture I saved into Photos.
return final;
}
Function is working, but the opengl image only shows part in retina
devices, how to solve this problem. Thanks !!!
Python: frame parameter of signal handler
Python: frame parameter of signal handler
I was looking through the Python documentation for signal and in the
example code:
def handler(signum, frame):
print 'Signal handler called with signal', signum
raise IOError("Couldn't open device!")
The 'frame' parameter is not used in the actual function. I noticed this
in a lot of code on stackoverflow/online regarding signal handlers. What
is the 'frame' parameter? Why is it kept in the function header?
Thank you
I was looking through the Python documentation for signal and in the
example code:
def handler(signum, frame):
print 'Signal handler called with signal', signum
raise IOError("Couldn't open device!")
The 'frame' parameter is not used in the actual function. I noticed this
in a lot of code on stackoverflow/online regarding signal handlers. What
is the 'frame' parameter? Why is it kept in the function header?
Thank you
Decoding PNG DataURL urlopen vs base64decode
Decoding PNG DataURL urlopen vs base64decode
I have PNG image coded to DataURL representation. It starts regularly:
u'data:image/png;base64,... but it has no == ending. base64.b64decode
raises TypeError: Incorrect padding, but urllib.urlopen returns proper
value - an image which successfully opens by image viewer.
Here is that encoded string:
http://www.sendspace.com/file/8l61im
Its difficult to formulate actual question here - I just wonder what is
the reason of that issue - is it particular buggy string, and urlopen just
has more 'tolerant' algorithm, or something else? Kindly help!
I have PNG image coded to DataURL representation. It starts regularly:
u'data:image/png;base64,... but it has no == ending. base64.b64decode
raises TypeError: Incorrect padding, but urllib.urlopen returns proper
value - an image which successfully opens by image viewer.
Here is that encoded string:
http://www.sendspace.com/file/8l61im
Its difficult to formulate actual question here - I just wonder what is
the reason of that issue - is it particular buggy string, and urlopen just
has more 'tolerant' algorithm, or something else? Kindly help!
Dart, constraints on Generics?
Dart, constraints on Generics?
Is there a Dart equivalent syntax to the c# ability to specify type
constraints on a generic type, e.g. in C#-like syntax where TBase is
SomeType:
class StackPanel<TBase> extends Panel<TBase> where TBase : SomeType{
}
Is there a Dart equivalent syntax to the c# ability to specify type
constraints on a generic type, e.g. in C#-like syntax where TBase is
SomeType:
class StackPanel<TBase> extends Panel<TBase> where TBase : SomeType{
}
Building symbolic link shared library in a shared folder of VirtualBox
Building symbolic link shared library in a shared folder of VirtualBox
I am now building a C++ library in Windows and Linux. For windows I am now
using Visual Studio for development, and for Linux I am now using Ubuntu
via Virtual Box. In order to make develop much easier, I shared the folder
of the project in Windows with Linux via the shared folder function of
Virtual Box. I compile and run the project in Windows first and if it
succeeds I will compile it in Linux. This is made possible thanks to
CMake. The problem I have is that if the shared library to be built is a
symbolic link one it cannot be compiled in Linux as this page suggests. If
it is not a symbolic one, it is fine. Then my questions are as follows:
Is symbolic link property important for a library in Linux?
Are there some solutions that can build the symbolic link library
successfully in shared folder?
I am now building a C++ library in Windows and Linux. For windows I am now
using Visual Studio for development, and for Linux I am now using Ubuntu
via Virtual Box. In order to make develop much easier, I shared the folder
of the project in Windows with Linux via the shared folder function of
Virtual Box. I compile and run the project in Windows first and if it
succeeds I will compile it in Linux. This is made possible thanks to
CMake. The problem I have is that if the shared library to be built is a
symbolic link one it cannot be compiled in Linux as this page suggests. If
it is not a symbolic one, it is fine. Then my questions are as follows:
Is symbolic link property important for a library in Linux?
Are there some solutions that can build the symbolic link library
successfully in shared folder?
How to show (via) in php send mail
How to show (via) in php send mail
In many of the mails, I have seen that they are delivered like xyz@xya.com
via xxx.aaa.com.
I am using php sendmail to send mail through my localhost. I also want to
show this (via) in my mail.
How can I show this via code in the mail through php sendmail ?
Thanks
In many of the mails, I have seen that they are delivered like xyz@xya.com
via xxx.aaa.com.
I am using php sendmail to send mail through my localhost. I also want to
show this (via) in my mail.
How can I show this via code in the mail through php sendmail ?
Thanks
Sunday, 8 September 2013
LWUIT Get combobox selection
LWUIT Get combobox selection
I'm a nwebie in LWUIT. I have created a theme using the resource editor
and generated a code. In the form the user selects the county then presses
a continue command. How do I get what the user selected using the command
and how do I show the next form after getting the user country? I've not
worked with StateMachine.java before and StateMachineBase.Java Below is my
code for the command but I have no idea what to call.
package userclasses;
import com.sun.lwuit.Container;
import generated.StateMachineBase;
public class StateMachine extends StateMachineBase {
public StateMachine(String resFile) {
super(resFile);
// do not modify, write code in initVars and initialize class
members there,
// the constructor might be invoked too late due to race
conditions that might occur
}
/**
* this method should be used to initialize variables instead of the
* constructor/class scope to avoid race conditions
*/
protected void initVars() {
String username;
}
protected boolean onGetUserCountryFormContinue() {
// If the resource file changes the names of components this
call will break notifying you that you should fix the code
boolean val = super.onGetUserCountryFormContinue();
//I should get the user selection here after the command has been selected.
return val;
}
}
I'm a nwebie in LWUIT. I have created a theme using the resource editor
and generated a code. In the form the user selects the county then presses
a continue command. How do I get what the user selected using the command
and how do I show the next form after getting the user country? I've not
worked with StateMachine.java before and StateMachineBase.Java Below is my
code for the command but I have no idea what to call.
package userclasses;
import com.sun.lwuit.Container;
import generated.StateMachineBase;
public class StateMachine extends StateMachineBase {
public StateMachine(String resFile) {
super(resFile);
// do not modify, write code in initVars and initialize class
members there,
// the constructor might be invoked too late due to race
conditions that might occur
}
/**
* this method should be used to initialize variables instead of the
* constructor/class scope to avoid race conditions
*/
protected void initVars() {
String username;
}
protected boolean onGetUserCountryFormContinue() {
// If the resource file changes the names of components this
call will break notifying you that you should fix the code
boolean val = super.onGetUserCountryFormContinue();
//I should get the user selection here after the command has been selected.
return val;
}
}
What is a sensible Python unit testing environment in Windows?
What is a sensible Python unit testing environment in Windows?
I develop Python libraries on a Mac, but I'd like to test them on Windows
as well to make sure everything works there.
I am a test-driven developer and maintain full unit test coverage as well
as application level acceptance/integration tests. I use pytest for unit
testing and behave for acceptance tests.
I only use Windows for very specific tasks like making appointments with
Outlook, but I do have a VMWare Fusion instance of Windows 7 running all
the time. I could run my tests under Windows without having to use a
different machine.
The trouble is, I'm not familiar with how folks typically run Python on
Windows anymore, but would like to use a fairly typical setup so I would
encounter similar problems to most Windows users before they install my
libraries.
Back in my pre-Mac days, I would run Python 2.3 or 2.4 under Cygwin. But
I'm not at all sure that was even typical then.
What kind of Python environment is a good one for testing Python code in a
Windows environment?
I develop Python libraries on a Mac, but I'd like to test them on Windows
as well to make sure everything works there.
I am a test-driven developer and maintain full unit test coverage as well
as application level acceptance/integration tests. I use pytest for unit
testing and behave for acceptance tests.
I only use Windows for very specific tasks like making appointments with
Outlook, but I do have a VMWare Fusion instance of Windows 7 running all
the time. I could run my tests under Windows without having to use a
different machine.
The trouble is, I'm not familiar with how folks typically run Python on
Windows anymore, but would like to use a fairly typical setup so I would
encounter similar problems to most Windows users before they install my
libraries.
Back in my pre-Mac days, I would run Python 2.3 or 2.4 under Cygwin. But
I'm not at all sure that was even typical then.
What kind of Python environment is a good one for testing Python code in a
Windows environment?
Uiscrollview not scroll in start and end position?
Uiscrollview not scroll in start and end position?
I put one uiscrollview and put many buttons at the uiscrollview.
I don't want scroll the uiscrollview at first and last button.
How do i do?
I put one uiscrollview and put many buttons at the uiscrollview.
I don't want scroll the uiscrollview at first and last button.
How do i do?
php change background color of cell based on sql table number
php change background color of cell based on sql table number
First question here on stack, also very new to php as you can probably
tell from my code below. What im trying to do is populate information from
a database onto a page. It appears in table format and users can search
for specific records by one or more filters. What id like to do is have
the 'age' filter show the record with a different color background
depending on the age. It will work for one, as in it will show all users
whose ages are less than 22 with an orange background. What id like it to
do (and I think this is the part where I just dont understand the syntax
yet) is to display all records whose ages are less than 19 with a Red
background AND all records whose ages are less than 22 with an Orange
background.
What im trying to say in the code below is if the row record for 'age' is
less than 22, give the table row a background color of ffab0a, if its less
than 19 give the table row a background color of ffff99, anything else, no
background color.
Can anyone help point me in the right direction? below is the part that
controls this thanks!
if ($row["age"]<22)
echo '<tr style="background-color:#ffab0a">';
else if ($row["age"]<19)
echo '<tr style="background-color:#ffff99">';
else
echo '<tr>'; ?>
<td><?php echo $row["age"]; ?></td>
<td><?php echo $row["location"]; ?></td>
<td><?php echo $row["form"]; ?></td>
First question here on stack, also very new to php as you can probably
tell from my code below. What im trying to do is populate information from
a database onto a page. It appears in table format and users can search
for specific records by one or more filters. What id like to do is have
the 'age' filter show the record with a different color background
depending on the age. It will work for one, as in it will show all users
whose ages are less than 22 with an orange background. What id like it to
do (and I think this is the part where I just dont understand the syntax
yet) is to display all records whose ages are less than 19 with a Red
background AND all records whose ages are less than 22 with an Orange
background.
What im trying to say in the code below is if the row record for 'age' is
less than 22, give the table row a background color of ffab0a, if its less
than 19 give the table row a background color of ffff99, anything else, no
background color.
Can anyone help point me in the right direction? below is the part that
controls this thanks!
if ($row["age"]<22)
echo '<tr style="background-color:#ffab0a">';
else if ($row["age"]<19)
echo '<tr style="background-color:#ffff99">';
else
echo '<tr>'; ?>
<td><?php echo $row["age"]; ?></td>
<td><?php echo $row["location"]; ?></td>
<td><?php echo $row["form"]; ?></td>
Invalid Argument: connect() C socket programming
Invalid Argument: connect() C socket programming
I'm working on a C program that creates a connection between a client and
server. When I run connect on the socket I've already created I keep
getting an error that I'm passing an invalid argument.
Any help would be awesome!
The code for the client function:
void client(char* ipAddress, char* serverPort){
int status;
//server addrinfo
struct addrinfo serverHints, *serverRes;
int socketDescriptor;
int addressLength;
memset(&hints, 0, sizeof hints); // make sure the struct is empty
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_PASSIVE; // fill in my IP for me
//setup client socket
if ((status = getaddrinfo(ipAddress, serverPort, &hints, &res)) != 0) {
printf("%s \n", "This error above");
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
if((socketDescriptor = socket(res->ai_family, res->ai_socktype,
res->ai_protocol)) ==-1){
perror("client: socket");
}
addressLength = sizeof hints;
if(connect(socketDescriptor, res->ai_addr, addressLength)==-1){
close(socketDescriptor);
perror("client: connect");
}
}
I'm working on a C program that creates a connection between a client and
server. When I run connect on the socket I've already created I keep
getting an error that I'm passing an invalid argument.
Any help would be awesome!
The code for the client function:
void client(char* ipAddress, char* serverPort){
int status;
//server addrinfo
struct addrinfo serverHints, *serverRes;
int socketDescriptor;
int addressLength;
memset(&hints, 0, sizeof hints); // make sure the struct is empty
hints.ai_family = AF_UNSPEC; // don't care IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
hints.ai_flags = AI_PASSIVE; // fill in my IP for me
//setup client socket
if ((status = getaddrinfo(ipAddress, serverPort, &hints, &res)) != 0) {
printf("%s \n", "This error above");
fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
exit(1);
}
if((socketDescriptor = socket(res->ai_family, res->ai_socktype,
res->ai_protocol)) ==-1){
perror("client: socket");
}
addressLength = sizeof hints;
if(connect(socketDescriptor, res->ai_addr, addressLength)==-1){
close(socketDescriptor);
perror("client: connect");
}
}
c# Relative position of elements in Windows Form
c# Relative position of elements in Windows Form
I try to create simple app with 2 columns using SpliterContainer and
control panel with buttons. And I would like that on every screen it will
look good. That's why I decided to use relative position of elements.
I read documentation and different forums, but I get something strange.
Second column of splitter doesn't appear at all.
Please, can you help me find the reason of that problem?
private void Form1_Load(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
int screenWidth = Screen.PrimaryScreen.Bounds.Width;
int screenHeight = Screen.PrimaryScreen.Bounds.Height;
//set form size
this.Size = new Size(screenWidth, screenHeight);
//set button panel size
const double percentOfHeightPanel = 0.05;
int heightOfPanelButton = Convert.ToInt32(screenHeight *
percentOfHeightPanel);
this.panel_button.Size = new System.Drawing.Size(screenWidth,
heightOfPanelButton);
this.panel_button.Location = new Point(0, 0);
//set splitContainer size
int widthOfContainer = Convert.ToInt32(0.5 * screenWidth);
int heightOfContainers = Convert.ToInt32(screenHeight * (0.95));
splitContainer1.Panel1.MinimumSize = new
Size(widthOfContainer, heightOfContainers);
splitContainer1.Panel2.MinimumSize = new
Size(widthOfContainer, heightOfContainers);
splitContainer1.Location = new Point(0, heightOfPanelButton);
//this.splitContainer1.Panel2MinSize = screenWidth -
widthOfContainer;
//set textBox size
this.textBox1.Multiline = true;
this.textBox1.Location = new Point(0, heightOfPanelButton);
this.textBox1.MinimumSize = new
System.Drawing.Size(widthOfContainer, heightOfContainers);
this.textBox2.Multiline = true;
this.textBox2.Location = new Point(widthOfContainer,
heightOfPanelButton);
this.textBox1.MinimumSize = new
System.Drawing.Size(widthOfContainer, heightOfContainers);
}
I try to create simple app with 2 columns using SpliterContainer and
control panel with buttons. And I would like that on every screen it will
look good. That's why I decided to use relative position of elements.
I read documentation and different forums, but I get something strange.
Second column of splitter doesn't appear at all.
Please, can you help me find the reason of that problem?
private void Form1_Load(object sender, EventArgs e)
{
WindowState = FormWindowState.Maximized;
int screenWidth = Screen.PrimaryScreen.Bounds.Width;
int screenHeight = Screen.PrimaryScreen.Bounds.Height;
//set form size
this.Size = new Size(screenWidth, screenHeight);
//set button panel size
const double percentOfHeightPanel = 0.05;
int heightOfPanelButton = Convert.ToInt32(screenHeight *
percentOfHeightPanel);
this.panel_button.Size = new System.Drawing.Size(screenWidth,
heightOfPanelButton);
this.panel_button.Location = new Point(0, 0);
//set splitContainer size
int widthOfContainer = Convert.ToInt32(0.5 * screenWidth);
int heightOfContainers = Convert.ToInt32(screenHeight * (0.95));
splitContainer1.Panel1.MinimumSize = new
Size(widthOfContainer, heightOfContainers);
splitContainer1.Panel2.MinimumSize = new
Size(widthOfContainer, heightOfContainers);
splitContainer1.Location = new Point(0, heightOfPanelButton);
//this.splitContainer1.Panel2MinSize = screenWidth -
widthOfContainer;
//set textBox size
this.textBox1.Multiline = true;
this.textBox1.Location = new Point(0, heightOfPanelButton);
this.textBox1.MinimumSize = new
System.Drawing.Size(widthOfContainer, heightOfContainers);
this.textBox2.Multiline = true;
this.textBox2.Location = new Point(widthOfContainer,
heightOfPanelButton);
this.textBox1.MinimumSize = new
System.Drawing.Size(widthOfContainer, heightOfContainers);
}
PhoneGap Mac CLI local install failed because of Node version
PhoneGap Mac CLI local install failed because of Node version
So I want to debug my Phonegap webapp locally in Xcode.
I follow the step here and here, and launch in MAC CLI
$ sudo npm install -g phonegap
BUT install failed and CLI result get lots of errors with the first one is :
engine phonegap@2.9.0rc1-0.12.0: wanted: {"node":">=0.10.0"} (current:
{"node":"v0.8.8","npm":"1.1.59"})
I understand my node version is too old : 0.8.8
node --version
I try to update but I am stuck with those 2 methods here and bot in errors
for me :
BREW
Tried Homebrew but did not work :
$ brew upgrade node
Error: node-0.8.8 already installed
NPM
As I found here
Upgrading Node.js to latest version
How to update node.js, npm and all other dependencies?
$ sudo npm install -g n
$ sudo n stable
sudo: n: command not found
So I want to debug my Phonegap webapp locally in Xcode.
I follow the step here and here, and launch in MAC CLI
$ sudo npm install -g phonegap
BUT install failed and CLI result get lots of errors with the first one is :
engine phonegap@2.9.0rc1-0.12.0: wanted: {"node":">=0.10.0"} (current:
{"node":"v0.8.8","npm":"1.1.59"})
I understand my node version is too old : 0.8.8
node --version
I try to update but I am stuck with those 2 methods here and bot in errors
for me :
BREW
Tried Homebrew but did not work :
$ brew upgrade node
Error: node-0.8.8 already installed
NPM
As I found here
Upgrading Node.js to latest version
How to update node.js, npm and all other dependencies?
$ sudo npm install -g n
$ sudo n stable
sudo: n: command not found
How do I add different colours and show legend for plot in MATLAB?
How do I add different colours and show legend for plot in MATLAB?
I am plotting 4 different vectors in same graph. Although MATLAB is
assigning them different colours, I want to assign them my own colours.
How can I do this? I also want to show the legend. Here is my code:
%Plotting of final solutions
a = 0:h:5.01;
z=1:1:N+2;
%ex=exact
up=upwind(z,M+1);
lf = laxfriedrich(z,M+1);
lw = laxwendroff(z,M+1);
oo = otherone(z,M+1);
plot(a,up,'o',a,lf,'o',a,lw,'o',a,oo,'o');
%plot (a,lf,'o',a,oo,'o');
axis([0,5,-1,1]);
I am plotting 4 different vectors in same graph. Although MATLAB is
assigning them different colours, I want to assign them my own colours.
How can I do this? I also want to show the legend. Here is my code:
%Plotting of final solutions
a = 0:h:5.01;
z=1:1:N+2;
%ex=exact
up=upwind(z,M+1);
lf = laxfriedrich(z,M+1);
lw = laxwendroff(z,M+1);
oo = otherone(z,M+1);
plot(a,up,'o',a,lf,'o',a,lw,'o',a,oo,'o');
%plot (a,lf,'o',a,oo,'o');
axis([0,5,-1,1]);
Saturday, 7 September 2013
How to get the id of the element clicked using jquery
How to get the id of the element clicked using jquery
<div class="main_div">
<div id="inner_div">
<span id="d1" class="get_clicked">click to get id</span>
</div>
</div>
How the get the id of the span when clicked? How to do this using jquery?
<div class="main_div">
<div id="inner_div">
<span id="d1" class="get_clicked">click to get id</span>
</div>
</div>
How the get the id of the span when clicked? How to do this using jquery?
How do I open a page with a different image displayed according to what the user chose on the previous screen?
How do I open a page with a different image displayed according to what
the user chose on the previous screen?
Basically, how it should work is:
-The user chooses an option on the first page
-The next page is displayed with one image changed around according to
what they picked
I can't think of a way to do this, without creating a different page for
each image. There will eventually be hundreds of choices and I'm hoping
there is some sort of JavaScript solution to this so I don't have to
create that many pages. I don't know JavaScript that well, though.
Any help is appreciated.
the user chose on the previous screen?
Basically, how it should work is:
-The user chooses an option on the first page
-The next page is displayed with one image changed around according to
what they picked
I can't think of a way to do this, without creating a different page for
each image. There will eventually be hundreds of choices and I'm hoping
there is some sort of JavaScript solution to this so I don't have to
create that many pages. I don't know JavaScript that well, though.
Any help is appreciated.
Using a parent environment to access child
Using a parent environment to access child
I'm attempting to create a hierarchy of environments, where I have one
main environment which contains a variety of other environments which
could then contain other environments (and so on).
I create the environment and its child like this:
parentEnv <- new.env()
childEnv <- new.env(parentEnv)
We can see that the parent and child were created:
> childEnv
<environment: 0x000000000e811208>
> parentEnv
<environment: 0x000000000d9e2440>
However, I then check the child's parent and it tells me its the R_Global.
(This isn't actually surprising as I was able to access it directly). Does
new.env(parent) not do what I think it does?
> parent.env(childEnv)
<environment: R_GlobalEnv>
That's fine, I then set my child's parent as parent.env(childEnv) <-
parentEnv (though the R docs says this is 'dangerous' and could be become
deprecated, I wanted to try it anyway).
parent.env(childEnv) <- parentEnv
> childEnv
<environment: 0x000000000e811208>
> parent.env(childEnv)
<environment: 0x000000000d9e2440>
We now see that the child's parent is parentEnv! Everything should be
great, right...?
> parentEnv$childEnv
NULL
> with(parentEnv, childEnv)
<environment: 0x000000000e811208>
I can't access it with $. Though I can using the 'with' notation. What's
going on here? Am not understand how environments work in R?
I'm attempting to create a hierarchy of environments, where I have one
main environment which contains a variety of other environments which
could then contain other environments (and so on).
I create the environment and its child like this:
parentEnv <- new.env()
childEnv <- new.env(parentEnv)
We can see that the parent and child were created:
> childEnv
<environment: 0x000000000e811208>
> parentEnv
<environment: 0x000000000d9e2440>
However, I then check the child's parent and it tells me its the R_Global.
(This isn't actually surprising as I was able to access it directly). Does
new.env(parent) not do what I think it does?
> parent.env(childEnv)
<environment: R_GlobalEnv>
That's fine, I then set my child's parent as parent.env(childEnv) <-
parentEnv (though the R docs says this is 'dangerous' and could be become
deprecated, I wanted to try it anyway).
parent.env(childEnv) <- parentEnv
> childEnv
<environment: 0x000000000e811208>
> parent.env(childEnv)
<environment: 0x000000000d9e2440>
We now see that the child's parent is parentEnv! Everything should be
great, right...?
> parentEnv$childEnv
NULL
> with(parentEnv, childEnv)
<environment: 0x000000000e811208>
I can't access it with $. Though I can using the 'with' notation. What's
going on here? Am not understand how environments work in R?
Subscribe to:
Comments (Atom)