How to change rsyslog configuration file directory
Does anyone know how I can recompile rsyslog for Ubuntu 10.04 so that
/etc/rsyslog.conf is read from another location, say for instance
/tmp/rsyslog.conf?
Monday, 30 September 2013
how to backup and restore mailman?
how to backup and restore mailman?
How can I backup and restore mailman list ?
Our server was hacked, We plan to reload OS. We are having mailman list in
server.
I'm new to mailman, It's urgent to backup and restore mailman list.
I've googled and checked this serverfault question, They discussed about
how to change mailman list from one domain to another one. But here I'm
going to just backup and restore.
Please help me to solve this,
Thanks
How can I backup and restore mailman list ?
Our server was hacked, We plan to reload OS. We are having mailman list in
server.
I'm new to mailman, It's urgent to backup and restore mailman list.
I've googled and checked this serverfault question, They discussed about
how to change mailman list from one domain to another one. But here I'm
going to just backup and restore.
Please help me to solve this,
Thanks
Method returns before its end
Method returns before its end
I'm using latest eclipse. How is it possible that my method closes before
its end of before a return statement?! The issue is not random, it fires
only at certain lines, anyway sounds to me impossible. Compiler bug? I
really don't know. Googling I found nothing.
I'm using latest eclipse. How is it possible that my method closes before
its end of before a return statement?! The issue is not random, it fires
only at certain lines, anyway sounds to me impossible. Compiler bug? I
really don't know. Googling I found nothing.
PHP socket script causes many and long CLOSE_WAIT socket connection
PHP socket script causes many and long CLOSE_WAIT socket connection
I have a PHP script (which I found online) that runs infinitely listening
to a port and if there is a connection made to this port it will establish
a TCP connection. However, when I ran this script and there are many
connections (around 500), the number of CLOSE_WAIT connections increase.
The remote device that is connected in this state is not able to connect
again because the CLOSE_WAIT did not terminate.
// port info
$host = "0.0.0.0";
$port = 10260;
$pos = 1;
// don't timeout!
set_time_limit(0);
record("START");
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
$timeout = array('sec'=>3000,'usec'=>0);
$try = socket_set_option($sock,SOL_SOCKET,SO_RCVTIMEO,$timeout);
// Bind the socket to the address/port
if(!socket_bind($sock, $host, $port))
{
echo socket_last_error() ;
die('Could not bind to address');
}
record("SOCKET BIND OK");
// start listening for connections
$result = socket_listen($sock, 1024) or die("Could not set up socket
listener\n");
record("SOCKET LISTEN OK");
$clients = array($sock);
// infinite while loop
while(1)
{
// Setup clients listen socket for reading
$read = $clients;
$e = NULL;
if (socket_select($read, $write = NULL, $except = NULL, 0,0) < 1)
{
continue;
}
/* if a new read ready is being made add it to the client array */
if (in_array($sock, $read)) {
record("NEW CONNECTION");
$clients[$pos] = $newsock = socket_accept($sock);
$curpos = $pos;
$pos++;
socket_getpeername($newsock, $ip,$port);
record("Incoming IP: {$ip} PORT: {$port}");
// remove the listening socket from the clients-with-data array
$key = array_search($sock, $read);
unset($read[$key]);
} // end if in_array
// loop through all the clients that have data to read from
foreach ($read as $read_key => $read_sock) {
// read until newline or 1024 bytes
// socket_read while show errors when the client is disconnected,
so silence the error messages
$key = $read_key;
$fulldata = $data = @socket_read($read_sock, 1024);
// check if the client is disconnected
if ($data === false) {
// remove client for $clients array
$key = array_search($read_sock, $clients);
socket_close($read_sock);
unset($clients[$key]);
record("NO DATA");
// continue to the next client to read from, if any
continue;
}
// .. do something with $data ...
}
}
socket_close($sock);
record("END");
die("DONE");
I tried to use socket_close() in the code but to no avail. CLOSE_WAIT
seems to take longer to move to the next state.
I have a PHP script (which I found online) that runs infinitely listening
to a port and if there is a connection made to this port it will establish
a TCP connection. However, when I ran this script and there are many
connections (around 500), the number of CLOSE_WAIT connections increase.
The remote device that is connected in this state is not able to connect
again because the CLOSE_WAIT did not terminate.
// port info
$host = "0.0.0.0";
$port = 10260;
$pos = 1;
// don't timeout!
set_time_limit(0);
record("START");
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
$timeout = array('sec'=>3000,'usec'=>0);
$try = socket_set_option($sock,SOL_SOCKET,SO_RCVTIMEO,$timeout);
// Bind the socket to the address/port
if(!socket_bind($sock, $host, $port))
{
echo socket_last_error() ;
die('Could not bind to address');
}
record("SOCKET BIND OK");
// start listening for connections
$result = socket_listen($sock, 1024) or die("Could not set up socket
listener\n");
record("SOCKET LISTEN OK");
$clients = array($sock);
// infinite while loop
while(1)
{
// Setup clients listen socket for reading
$read = $clients;
$e = NULL;
if (socket_select($read, $write = NULL, $except = NULL, 0,0) < 1)
{
continue;
}
/* if a new read ready is being made add it to the client array */
if (in_array($sock, $read)) {
record("NEW CONNECTION");
$clients[$pos] = $newsock = socket_accept($sock);
$curpos = $pos;
$pos++;
socket_getpeername($newsock, $ip,$port);
record("Incoming IP: {$ip} PORT: {$port}");
// remove the listening socket from the clients-with-data array
$key = array_search($sock, $read);
unset($read[$key]);
} // end if in_array
// loop through all the clients that have data to read from
foreach ($read as $read_key => $read_sock) {
// read until newline or 1024 bytes
// socket_read while show errors when the client is disconnected,
so silence the error messages
$key = $read_key;
$fulldata = $data = @socket_read($read_sock, 1024);
// check if the client is disconnected
if ($data === false) {
// remove client for $clients array
$key = array_search($read_sock, $clients);
socket_close($read_sock);
unset($clients[$key]);
record("NO DATA");
// continue to the next client to read from, if any
continue;
}
// .. do something with $data ...
}
}
socket_close($sock);
record("END");
die("DONE");
I tried to use socket_close() in the code but to no avail. CLOSE_WAIT
seems to take longer to move to the next state.
Sunday, 29 September 2013
Multi Selective Hover Not Working
Multi Selective Hover Not Working
Alright so well i had already asked a question about multi hover and i got
a jquery answer so when i was fixing everything up on the code i
integrated the jquery code and well it doesn't work that well. What i was
trying to do is when i hover over the box, the box has to have a box
shadow and the text on the right has to become bold or different color and
vice versa and well idk what i did wrong but the jquery code isnt working
correctly so i wanted to know what was the mistake thanks in advance.
heres the jquery:
$('#a').hover(function(){
$('#a').css('box-shadow','1px 3px');
$('#b').css('color','blue');
}, function(){
$('#a').css('box-shadow','none');
$('#b').css('color','red');
})
$('#b').hover(function(){
$('#a').css('box-shadow','1px 3px');
$('#b').css('color','blue');
}, function(){
$('#a').css('box-shadow','none');
$('#b').css('color','red');
})
heres the code: http://jsfiddle.net/gtdGU/1/
Alright so well i had already asked a question about multi hover and i got
a jquery answer so when i was fixing everything up on the code i
integrated the jquery code and well it doesn't work that well. What i was
trying to do is when i hover over the box, the box has to have a box
shadow and the text on the right has to become bold or different color and
vice versa and well idk what i did wrong but the jquery code isnt working
correctly so i wanted to know what was the mistake thanks in advance.
heres the jquery:
$('#a').hover(function(){
$('#a').css('box-shadow','1px 3px');
$('#b').css('color','blue');
}, function(){
$('#a').css('box-shadow','none');
$('#b').css('color','red');
})
$('#b').hover(function(){
$('#a').css('box-shadow','1px 3px');
$('#b').css('color','blue');
}, function(){
$('#a').css('box-shadow','none');
$('#b').css('color','red');
})
heres the code: http://jsfiddle.net/gtdGU/1/
Coprime Factorization in Python
Coprime Factorization in Python
I have to write a code to find the two highest co prime factors of an
entered number.
Right now, I've written:
def coprimes(num):
for x in range (2, num):
for y in range (2, num):
while (gcd(x,y) == 1) & (x != y):
if (x*y==num):
return (x,y)
Which is obviously a really slow program because of the forloops. Whenever
I enter it into the terminal, it's too slow to produce an answer. I'm also
not sure if this is correct. Do you have any suggestions on how I could
improve this method?
An example answer of this method should be:
>>> coprimes(10)
(9765625, 1024)
I have to write a code to find the two highest co prime factors of an
entered number.
Right now, I've written:
def coprimes(num):
for x in range (2, num):
for y in range (2, num):
while (gcd(x,y) == 1) & (x != y):
if (x*y==num):
return (x,y)
Which is obviously a really slow program because of the forloops. Whenever
I enter it into the terminal, it's too slow to produce an answer. I'm also
not sure if this is correct. Do you have any suggestions on how I could
improve this method?
An example answer of this method should be:
>>> coprimes(10)
(9765625, 1024)
Python program's "main()" not run on invocation
Python program's "main()" not run on invocation
I'm new to learning Python and using Eclipse + PyDev. I can't seem to
figure out why my program isn't running.
Here is my code:
def main():
print("Testing")
test1 = float(input("Test1: "))
test2 = float(input("Test2: "))
test3 = float(input("Test3: "))
calculate_cost (test1, test2, test3)
def calculate_cost (test1, test2, test3):
print("Testing")
I am assuming I am missing something in one or both of the functions to
make this run properly.
I'm new to learning Python and using Eclipse + PyDev. I can't seem to
figure out why my program isn't running.
Here is my code:
def main():
print("Testing")
test1 = float(input("Test1: "))
test2 = float(input("Test2: "))
test3 = float(input("Test3: "))
calculate_cost (test1, test2, test3)
def calculate_cost (test1, test2, test3):
print("Testing")
I am assuming I am missing something in one or both of the functions to
make this run properly.
Iterated TextArea in HTML which is changed and empty
Iterated TextArea in HTML which is changed and empty
I have a list of TextArea loop by forEach of JSTL, just like this:
<c:forEach var="test" items="${data}">
<td><textarea class="no-resize" name="submit-${test}"></textarea></td>
</c:forEach>
I want to know which TextArea is changed and if it empty when a button is
clicked using JQuery
The button is just like this
<button class="btn " type="submit" form="controller" name="save"
value="save" id="save" onClick="return onSave()">Save</button>
Here's what i tried so far:
function onSave()
{
$('.no-resize1').each(function(){
$(this).change(function(){
if(!$(this).val() == ''){
return true;
} else {
return false;
}
});
});
};
What am i doing wrong?
I have a list of TextArea loop by forEach of JSTL, just like this:
<c:forEach var="test" items="${data}">
<td><textarea class="no-resize" name="submit-${test}"></textarea></td>
</c:forEach>
I want to know which TextArea is changed and if it empty when a button is
clicked using JQuery
The button is just like this
<button class="btn " type="submit" form="controller" name="save"
value="save" id="save" onClick="return onSave()">Save</button>
Here's what i tried so far:
function onSave()
{
$('.no-resize1').each(function(){
$(this).change(function(){
if(!$(this).val() == ''){
return true;
} else {
return false;
}
});
});
};
What am i doing wrong?
Saturday, 28 September 2013
How mysql is ordering textual data?
How mysql is ordering textual data?
This is the query result from some dataset of articles ordered by article
title ascending with limit 10 in MySQL. Encoding is set to
utf8_unicode_ci.
'GTA 5' Sells $800 Million In One Day
'Infinity Blade III' hits the App Store ahead of i...
'Have you lurked her texts?' How the directors of ...
'Second Moon' by Katie Paterson now on a journey a...
"Do not track" effort in trouble as Digital Advert...
"Forbes": Bill Gates wci¹¿ najbogatszym obywatelem...
"Here Is Something False: You Only Live Once"
"That's The Dumbest Thing I've Ever Heard Of."
[Introduction to Special Issue] The Future Is Now
1 Great Dividend You Can Buy Right Now
I thought ordering works by getting the position of the character in the
encoding table. like ' is 39 and " is 34 in unicode but apostrophe ʼ
and double quote " have much higher position. From my understanding
ʼ" shouldn't make it into the result and " should be at the top. I'm
clearly missing something here.
My goal is to order this data by title in python to get the same results
as if data was ordered in mysql.
This is the query result from some dataset of articles ordered by article
title ascending with limit 10 in MySQL. Encoding is set to
utf8_unicode_ci.
'GTA 5' Sells $800 Million In One Day
'Infinity Blade III' hits the App Store ahead of i...
'Have you lurked her texts?' How the directors of ...
'Second Moon' by Katie Paterson now on a journey a...
"Do not track" effort in trouble as Digital Advert...
"Forbes": Bill Gates wci¹¿ najbogatszym obywatelem...
"Here Is Something False: You Only Live Once"
"That's The Dumbest Thing I've Ever Heard Of."
[Introduction to Special Issue] The Future Is Now
1 Great Dividend You Can Buy Right Now
I thought ordering works by getting the position of the character in the
encoding table. like ' is 39 and " is 34 in unicode but apostrophe ʼ
and double quote " have much higher position. From my understanding
ʼ" shouldn't make it into the result and " should be at the top. I'm
clearly missing something here.
My goal is to order this data by title in python to get the same results
as if data was ordered in mysql.
socket.error: [Errno 48] Address already in use
socket.error: [Errno 48] Address already in use
I'm trying to set up a server with python from mac command line.
I navigate to folder location an use:
python -m SimpleHTTPServer
But this gives me error:
socket.error: [Errno 48] Address already in use
I had previously open a connection using the same command for a different
website in a different location in my machine.
I'm trying to set up a server with python from mac command line.
I navigate to folder location an use:
python -m SimpleHTTPServer
But this gives me error:
socket.error: [Errno 48] Address already in use
I had previously open a connection using the same command for a different
website in a different location in my machine.
MySQL Workbench couldnt set new date type for "DATE"
MySQL Workbench couldnt set new date type for "DATE"
I'm having a problem with mysql workbench - for some reason it doesn't
allow me to set 'DATE' as datatype any record. I'm a total beginner if it
comes to mysql but i'm forced to use this program (school relevent). I
hope any one of you may be able to help me with this. I uploaded a
screenshot with the error.
http://imgur.com/vgx4Er4
Thanks in advance
I'm having a problem with mysql workbench - for some reason it doesn't
allow me to set 'DATE' as datatype any record. I'm a total beginner if it
comes to mysql but i'm forced to use this program (school relevent). I
hope any one of you may be able to help me with this. I uploaded a
screenshot with the error.
http://imgur.com/vgx4Er4
Thanks in advance
Dragging track from spotify depends on source
Dragging track from spotify depends on source
Using spotify's client on windows 7, when dragging a track from a playlist
into a browser the dropped element has several options:
event.dataTransfer.getData("text/plain") returns an open.spotify.com URL
such as http://open.spotify.com/track/3OpUG4N7Igc6ZbC0SONuVc
event.dataTransfer.getData("text/uri-list") returns a spotify URI such as
spotify:track:4w8CsAnzn0lXJxYlAuCtCW
However if you are on the Artist's page, e.g. if you search for Lorde and
then drag a track into the browser both text/plain and text/uri-list
return the open.spotify.com URL
(http://open.spotify.com/track/4w8CsAnzn0lXJxYlAuCtCW). The same happens
when dragging a link to a track from the discover tab.
Is it likely that one will change so they both implement the same
behaviour? I want to develop a site that handles spotify objects being
dropped from anywhere in the client.
Note the http://play.spotify.com site doesn't appear to implement drag and
drop of any elements.
Using spotify's client on windows 7, when dragging a track from a playlist
into a browser the dropped element has several options:
event.dataTransfer.getData("text/plain") returns an open.spotify.com URL
such as http://open.spotify.com/track/3OpUG4N7Igc6ZbC0SONuVc
event.dataTransfer.getData("text/uri-list") returns a spotify URI such as
spotify:track:4w8CsAnzn0lXJxYlAuCtCW
However if you are on the Artist's page, e.g. if you search for Lorde and
then drag a track into the browser both text/plain and text/uri-list
return the open.spotify.com URL
(http://open.spotify.com/track/4w8CsAnzn0lXJxYlAuCtCW). The same happens
when dragging a link to a track from the discover tab.
Is it likely that one will change so they both implement the same
behaviour? I want to develop a site that handles spotify objects being
dropped from anywhere in the client.
Note the http://play.spotify.com site doesn't appear to implement drag and
drop of any elements.
Friday, 27 September 2013
python: How to compare values in a list by row?
python: How to compare values in a list by row?
i need to convert a csv into a list and count the amount of 'z's in a row
and print out the row headers of 5 rows with the top amount of Z's. Also
links to more help would be great! thank you
Here is my current code
economistData = open('C:/foo.csv','r')
economistDataList = []s
for line in economistData:
economistDataList.append(line.split(','))
for row in economistDataList:
rowcnt = row.count('z')
i need to convert a csv into a list and count the amount of 'z's in a row
and print out the row headers of 5 rows with the top amount of Z's. Also
links to more help would be great! thank you
Here is my current code
economistData = open('C:/foo.csv','r')
economistDataList = []s
for line in economistData:
economistDataList.append(line.split(','))
for row in economistDataList:
rowcnt = row.count('z')
ASP .NET Update command different SQL Data Sources
ASP .NET Update command different SQL Data Sources
I have DetailsView that automatically selects data from a datasource.
Within that detailsview I have 2 dropdown lists bound from a different
datasource. On update I want the text and value of each drop down list to
store into the database.
I can't seem to get the value of the dropdown lists so I can update the
paramaters before the SQL command is executed. Or if there is another way
to do so that'd be great.
<asp:DetailsView ID="UserProfile" runat="server"
AutoGenerateRows="False" DataKeyNames="UserId" DefaultMode="Edit"
DataSourceID="UserProfileDataSource"
onitemupdated="UserProfile_ItemUpdated"
OnPageIndexChanging="UserProfile_PageIndexChanging">
<Fields>
<asp:BoundField DataField="fname" HeaderText="First Name:"
SortExpression="fname" />
<asp:BoundField DataField="lname" HeaderText="Last Name:"
SortExpression="lname" />
<asp:BoundField DataField="address" HeaderText="Address:"
SortExpression="address" />
<asp:BoundField DataField="city" HeaderText="City:"
SortExpression="city" />
<asp:TemplateField HeaderText="State:" SortExpression="state">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="State_en"
DataValueField="StateId">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#
Bind("state") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#
Bind("state") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="zip" HeaderText="Zip Code:"
SortExpression="zip" />
<asp:BoundField DataField="phoneNum" HeaderText="Phone Number:"
SortExpression="phoneNum" />
<asp:TemplateField HeaderText="Auto Carrier:"
SortExpression="autoCarrier">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="SqlDataSource2" DataTextField="Name"
DataValueField="CarrerID">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%#
Bind("autoCarrier") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#
Bind("autoCarrier") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="policyNum" HeaderText="Policy Number:"
SortExpression="policyNum" />
<asp:CommandField ShowEditButton="True" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="UserProfileDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT [fname], [lname], [address], [city],
[state], [zip], [phoneNum], [autoCarrier], [policyNum],
[accountid] ,[UserId] FROM [UserProfile] WHERE ([UserId] =
@UserId)"
OnSelecting="UserProfileDataSource_Selecting"
OnUpdating="OnSqlUpdating"
UpdateCommand="UPDATE UserProfile SET
stateId = @stateId,
carrierId = @carrierId,
fname = @fname,
lname= @lname,
address = @address,
city = @city,
state = @state,
zip = @zip,
phoneNum = @phoneNum,
autoCarrier = @autoCarrier,
policyNum = @policyNum
WHERE ([UserId] = @UserId)">
<SelectParameters>
<asp:Parameter Name="UserId" Type="Object" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="fname" />
<asp:Parameter Name="lname" />
<asp:Parameter Name="address" />
<asp:Parameter Name="city" />
<asp:Parameter Name="state" />
<asp:Parameter Name="zip" />
<asp:Parameter Name="phoneNum" />
<asp:Parameter Name="autoCarrier" />
<asp:Parameter Name="policyNum" />
<asp:Parameter Name="stateId" />
<asp:Parameter Name="carrierId" />
<asp:Parameter Name="UserId" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT [StateId], [State_en] FROM
[States]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT [CarrerID], [Name] FROM ### WHERE
([AccountID] = (SELECT [accountid] FROM ### WHERE ([UserId] =
@UserId)))" OnSelecting="UserProfileDataSource_Selecting">
<SelectParameters>
<asp:Parameter Name="UserId" Type="Object" />
</SelectParameters>
</asp:SqlDataSource>
Here's the code Behind that I wrote, but doesn't work:
protected void OnSqlUpdating(object sender, SqlDataSourceCommandEventArgs e)
{
string state = DropDownList1.SelectedItem.Text;
string autoCarrier = DropDownList2.SelectedItem.Text;
string stateId = DropDownList1.SelectedItem.Value;
string carrierId = DropDownList2.SelectedItem.Value;
e.Command.Parameters["@state"].Value = state;
e.Command.Parameters["@autoCarrier"].Value = autoCarrier;
e.Command.Parameters["@stateId"].Value = stateId;
e.Command.Parameters["@carrierId"].Value = carrierId;
}
I keep getting:
Error 99 The name 'DropDownList1' does not exist in the current context
Error 102 The name 'DropDownList1' does not exist in the current context
Error 101 The name 'DropDownList2' does not exist in the current context
Error 103 The name 'DropDownList2' does not exist in the current context
I'm new to ASP so any suggestions you recommend or cleaning up of bad code
practices is appreciated.
I have DetailsView that automatically selects data from a datasource.
Within that detailsview I have 2 dropdown lists bound from a different
datasource. On update I want the text and value of each drop down list to
store into the database.
I can't seem to get the value of the dropdown lists so I can update the
paramaters before the SQL command is executed. Or if there is another way
to do so that'd be great.
<asp:DetailsView ID="UserProfile" runat="server"
AutoGenerateRows="False" DataKeyNames="UserId" DefaultMode="Edit"
DataSourceID="UserProfileDataSource"
onitemupdated="UserProfile_ItemUpdated"
OnPageIndexChanging="UserProfile_PageIndexChanging">
<Fields>
<asp:BoundField DataField="fname" HeaderText="First Name:"
SortExpression="fname" />
<asp:BoundField DataField="lname" HeaderText="Last Name:"
SortExpression="lname" />
<asp:BoundField DataField="address" HeaderText="Address:"
SortExpression="address" />
<asp:BoundField DataField="city" HeaderText="City:"
SortExpression="city" />
<asp:TemplateField HeaderText="State:" SortExpression="state">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="State_en"
DataValueField="StateId">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%#
Bind("state") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#
Bind("state") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="zip" HeaderText="Zip Code:"
SortExpression="zip" />
<asp:BoundField DataField="phoneNum" HeaderText="Phone Number:"
SortExpression="phoneNum" />
<asp:TemplateField HeaderText="Auto Carrier:"
SortExpression="autoCarrier">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server"
DataSourceID="SqlDataSource2" DataTextField="Name"
DataValueField="CarrerID">
</asp:DropDownList>
</EditItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%#
Bind("autoCarrier") %>'></asp:TextBox>
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%#
Bind("autoCarrier") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="policyNum" HeaderText="Policy Number:"
SortExpression="policyNum" />
<asp:CommandField ShowEditButton="True" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="UserProfileDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT [fname], [lname], [address], [city],
[state], [zip], [phoneNum], [autoCarrier], [policyNum],
[accountid] ,[UserId] FROM [UserProfile] WHERE ([UserId] =
@UserId)"
OnSelecting="UserProfileDataSource_Selecting"
OnUpdating="OnSqlUpdating"
UpdateCommand="UPDATE UserProfile SET
stateId = @stateId,
carrierId = @carrierId,
fname = @fname,
lname= @lname,
address = @address,
city = @city,
state = @state,
zip = @zip,
phoneNum = @phoneNum,
autoCarrier = @autoCarrier,
policyNum = @policyNum
WHERE ([UserId] = @UserId)">
<SelectParameters>
<asp:Parameter Name="UserId" Type="Object" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="fname" />
<asp:Parameter Name="lname" />
<asp:Parameter Name="address" />
<asp:Parameter Name="city" />
<asp:Parameter Name="state" />
<asp:Parameter Name="zip" />
<asp:Parameter Name="phoneNum" />
<asp:Parameter Name="autoCarrier" />
<asp:Parameter Name="policyNum" />
<asp:Parameter Name="stateId" />
<asp:Parameter Name="carrierId" />
<asp:Parameter Name="UserId" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT [StateId], [State_en] FROM
[States]"></asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:DefaultConnection %>"
SelectCommand="SELECT [CarrerID], [Name] FROM ### WHERE
([AccountID] = (SELECT [accountid] FROM ### WHERE ([UserId] =
@UserId)))" OnSelecting="UserProfileDataSource_Selecting">
<SelectParameters>
<asp:Parameter Name="UserId" Type="Object" />
</SelectParameters>
</asp:SqlDataSource>
Here's the code Behind that I wrote, but doesn't work:
protected void OnSqlUpdating(object sender, SqlDataSourceCommandEventArgs e)
{
string state = DropDownList1.SelectedItem.Text;
string autoCarrier = DropDownList2.SelectedItem.Text;
string stateId = DropDownList1.SelectedItem.Value;
string carrierId = DropDownList2.SelectedItem.Value;
e.Command.Parameters["@state"].Value = state;
e.Command.Parameters["@autoCarrier"].Value = autoCarrier;
e.Command.Parameters["@stateId"].Value = stateId;
e.Command.Parameters["@carrierId"].Value = carrierId;
}
I keep getting:
Error 99 The name 'DropDownList1' does not exist in the current context
Error 102 The name 'DropDownList1' does not exist in the current context
Error 101 The name 'DropDownList2' does not exist in the current context
Error 103 The name 'DropDownList2' does not exist in the current context
I'm new to ASP so any suggestions you recommend or cleaning up of bad code
practices is appreciated.
Calculate variable based on criteria in r
Calculate variable based on criteria in r
How can i add a new column to my data frame that would take into
consideration some criteria such as:
ID AGE PERNO
1 30 1
1 25 2
2 25 1
2 24 2
2 3 3
3 65 1
3 55 2
to end with a table like:
ID AGE PERNO AGE_HEAD
1 30 1 30
1 25 2 30
2 25 1 25
2 24 2 25
2 3 3 25
3 65 1 65
3 55 2 65
Pretty much have the age of perno one in all the rows related to the id
How can i add a new column to my data frame that would take into
consideration some criteria such as:
ID AGE PERNO
1 30 1
1 25 2
2 25 1
2 24 2
2 3 3
3 65 1
3 55 2
to end with a table like:
ID AGE PERNO AGE_HEAD
1 30 1 30
1 25 2 30
2 25 1 25
2 24 2 25
2 3 3 25
3 65 1 65
3 55 2 65
Pretty much have the age of perno one in all the rows related to the id
Python Regex for parsing site
Python Regex for parsing site
I am trying to write python script to pull data from a site and place it
into a json string.
The site is http://mtc.sri.com/live_data/attackers/.
I have python pulling the source, but can't quite figure out the regex
portion
When I use RegExr, this regex works:
</?table[^>]*>|</?tr[^>]*>|</?td[^>]*>|</?thead[^>]*>|</?tbody[^>]*>|</?font[^>]*>
But when I put it into the script, I get no match.
#!/usr/bin/python
import urllib2
import re
f = urllib2.urlopen("http://mtc.sri.com/live_data/attackers/")
out = f.read();
matchObj = re.match(
r'</?table[^>]*>|</?tr[^>]*>|</?td[^>]*>|</?thead[^>]*>|</?tbody[^>]*>|</?font[^>]*>',
out, re.M|re.I)
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"
Any idea why I am not getting the appropriate response?
I am trying to write python script to pull data from a site and place it
into a json string.
The site is http://mtc.sri.com/live_data/attackers/.
I have python pulling the source, but can't quite figure out the regex
portion
When I use RegExr, this regex works:
</?table[^>]*>|</?tr[^>]*>|</?td[^>]*>|</?thead[^>]*>|</?tbody[^>]*>|</?font[^>]*>
But when I put it into the script, I get no match.
#!/usr/bin/python
import urllib2
import re
f = urllib2.urlopen("http://mtc.sri.com/live_data/attackers/")
out = f.read();
matchObj = re.match(
r'</?table[^>]*>|</?tr[^>]*>|</?td[^>]*>|</?thead[^>]*>|</?tbody[^>]*>|</?font[^>]*>',
out, re.M|re.I)
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"
Any idea why I am not getting the appropriate response?
System for securely authenticating content acquisition
System for securely authenticating content acquisition
I'm having trouble designing a system for having authenticated content
from my site distributed by other people. I'm working in Ruby on Rails,
but I don't think that at a theoretical level my question is restricted to
that framework. In order to not give too much away, my site (let's call it
www.site.com) helps businesses keep inventory of who has purchased what
item, and allows customers to view their purchase history.
Hence, I have the following problem:
Suppose Alice sells cheeseburgers. Alice makes an account on site.com and
registers her cheeseburgers as an item that she sells. Consequently,
site.com stores Alice's cheeseburger in a SQL database with the id 92314
Bob is a customer at Alice's cheeseburger stand and has recently purchased
a cheeseburger.
Alice would like to tell Bob about site.com and its ability to track
purchases. Hence, Alice sends a request to site.com to return hashA that
corresponds to item with id 92314.
Bob visits www.site.com/purchase/hashA and is prompted to either create an
account or sign in to log his new cheeseburger purchase from Alice's
Delicious and Delectable cheeseburgers.
Charlie also visits Alice's cheeseburger stand and purchases a cheeseburger.
Alice would also like to tell Charlie about site.com and sends a request
that generates hashB for Charlie to use in the same manner.
My question is, how do I come up with a scheme that can generate hashA and
hashB in a way that my web server can efficiently lookup the items. I
suspect that hashB can be generated from hashA using some sort cipher
using hashA as a seed. I don't know how, upon receiving hashA or hashB,
site.com will know that it corresponds to item 92314. I suspect that using
a nonce will help.
Things that I would like to avoid include:
Having Charlie use hashA after it has been used by Bob
Exposing the id 92314 to the user
Having a single point of failure (i.e. a single key that encrypts hashes
for all ids)
Having things break if Charlie uses hashB before Bob uses hashA.
Disclaimer: My expertise is more in computer graphics and less in web
development or cryptography, so pointing me towards things to Google is
helpful. If this belongs in any of the other stackexchange sites
(Cryptography, Programmers, etc). Feel free to let me know and I will move
it.
I'm having trouble designing a system for having authenticated content
from my site distributed by other people. I'm working in Ruby on Rails,
but I don't think that at a theoretical level my question is restricted to
that framework. In order to not give too much away, my site (let's call it
www.site.com) helps businesses keep inventory of who has purchased what
item, and allows customers to view their purchase history.
Hence, I have the following problem:
Suppose Alice sells cheeseburgers. Alice makes an account on site.com and
registers her cheeseburgers as an item that she sells. Consequently,
site.com stores Alice's cheeseburger in a SQL database with the id 92314
Bob is a customer at Alice's cheeseburger stand and has recently purchased
a cheeseburger.
Alice would like to tell Bob about site.com and its ability to track
purchases. Hence, Alice sends a request to site.com to return hashA that
corresponds to item with id 92314.
Bob visits www.site.com/purchase/hashA and is prompted to either create an
account or sign in to log his new cheeseburger purchase from Alice's
Delicious and Delectable cheeseburgers.
Charlie also visits Alice's cheeseburger stand and purchases a cheeseburger.
Alice would also like to tell Charlie about site.com and sends a request
that generates hashB for Charlie to use in the same manner.
My question is, how do I come up with a scheme that can generate hashA and
hashB in a way that my web server can efficiently lookup the items. I
suspect that hashB can be generated from hashA using some sort cipher
using hashA as a seed. I don't know how, upon receiving hashA or hashB,
site.com will know that it corresponds to item 92314. I suspect that using
a nonce will help.
Things that I would like to avoid include:
Having Charlie use hashA after it has been used by Bob
Exposing the id 92314 to the user
Having a single point of failure (i.e. a single key that encrypts hashes
for all ids)
Having things break if Charlie uses hashB before Bob uses hashA.
Disclaimer: My expertise is more in computer graphics and less in web
development or cryptography, so pointing me towards things to Google is
helpful. If this belongs in any of the other stackexchange sites
(Cryptography, Programmers, etc). Feel free to let me know and I will move
it.
WebClient POST fails for ActiveX control in web application
WebClient POST fails for ActiveX control in web application
Hi All i have weird requirement, based on clients request i have developed
activeX control to drag and drop files then upload files to server. I am
using upload ActiveX control in web application which has forms & Windows
athentication. My ActiveX control is Windows User control where i am
trying to POST files using WebClient API. I am assuming that ActiveX's
WebClient API should use credentials of website i logged in to POST files
to server but its not happening when i use
WebClient client = new WebClient();
client.UseDefaultCredentials = true;
//It redirects me to login page.
When i use network credentials? Not sure i whether to use win login or
website login credentils
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("me", "password", "domain");
//Throws me an error
//The remote server returned an error: (401) Unauthorized.
What is the best way to pass authentication/Authorization to ActiveX so
that it can upload easily to server.
Hi All i have weird requirement, based on clients request i have developed
activeX control to drag and drop files then upload files to server. I am
using upload ActiveX control in web application which has forms & Windows
athentication. My ActiveX control is Windows User control where i am
trying to POST files using WebClient API. I am assuming that ActiveX's
WebClient API should use credentials of website i logged in to POST files
to server but its not happening when i use
WebClient client = new WebClient();
client.UseDefaultCredentials = true;
//It redirects me to login page.
When i use network credentials? Not sure i whether to use win login or
website login credentils
WebClient client = new WebClient();
client.Credentials = new NetworkCredential("me", "password", "domain");
//Throws me an error
//The remote server returned an error: (401) Unauthorized.
What is the best way to pass authentication/Authorization to ActiveX so
that it can upload easily to server.
UpdateProgress not showing with custom postback
UpdateProgress not showing with custom postback
I have a page with an UpdateProgress and and UpdatePanel.
I want to trigger a postback in the UpdatePanel immediately after the page
has completed loading, so implemented a custom control, called
UpdateTrigger that just causes a postback once:
public partial class UpdateTrigger : System.Web.UI.UserControl {
public event EventHandler<EventArgs> Tick;
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
Page.ClientScript.RegisterStartupScript(GetType(), ClientID,
string.Format("<script type='text/javascript'>{0}</script>",
Page.ClientScript.GetPostBackEventReference(this, "")));
} else {
if (object.ReferenceEquals(sender, this) && Tick != null) {
Tick(this, EventArgs.Empty);
}
}
}
}
Then, in my aspx page, I put my custom control inside an UpdatePanel, like
this:
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>Loading...</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<ut:UpdateTrigger ID="UpdateTrigger1" runat="server"
OnTick="UpdateTrigger1_Tick"/>
</ContentTemplate>
</asp:UpdatePanel>
The only problem is that the UpdateProgress is not displayed on the
postback, while if I use a Timer it works perfectly (of course, the reason
I did all this is because I don't want to use a Timer).
According to this documentation (Programming UpdateProgress Controls in
Client Script), the UpdateProgress should be displayed if the postback is
caused by a control inside the associated UpdatePanel, but in this case it
does not seem to work.
What am I missing?
I have a page with an UpdateProgress and and UpdatePanel.
I want to trigger a postback in the UpdatePanel immediately after the page
has completed loading, so implemented a custom control, called
UpdateTrigger that just causes a postback once:
public partial class UpdateTrigger : System.Web.UI.UserControl {
public event EventHandler<EventArgs> Tick;
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
Page.ClientScript.RegisterStartupScript(GetType(), ClientID,
string.Format("<script type='text/javascript'>{0}</script>",
Page.ClientScript.GetPostBackEventReference(this, "")));
} else {
if (object.ReferenceEquals(sender, this) && Tick != null) {
Tick(this, EventArgs.Empty);
}
}
}
}
Then, in my aspx page, I put my custom control inside an UpdatePanel, like
this:
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>Loading...</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<ut:UpdateTrigger ID="UpdateTrigger1" runat="server"
OnTick="UpdateTrigger1_Tick"/>
</ContentTemplate>
</asp:UpdatePanel>
The only problem is that the UpdateProgress is not displayed on the
postback, while if I use a Timer it works perfectly (of course, the reason
I did all this is because I don't want to use a Timer).
According to this documentation (Programming UpdateProgress Controls in
Client Script), the UpdateProgress should be displayed if the postback is
caused by a control inside the associated UpdatePanel, but in this case it
does not seem to work.
What am I missing?
Thursday, 26 September 2013
iOS simulator behind corporate proxy
iOS simulator behind corporate proxy
I have to test my application on iOS simulator behind proxy. I am able to
open URLs on safari browser on mac machine but same URLs are not working
on iOS simulator on same mac machine. I made sure my proxy settings are
correct in system preferences on mac machines and I have provided user
name and password for the proxy also.
I read about using charles proxy for simulator. Also I read about using
connection:didReceiveAuthenticationChallenge: from
NSURLCOnnectiondelegate. Both of them are good solutions but I have some
constraints due to which I can not use these.
Other than above mentioned is there any other solution to this? Like
modifying some configuration file etc. where I can mention proxy and
username password??
I have to test my application on iOS simulator behind proxy. I am able to
open URLs on safari browser on mac machine but same URLs are not working
on iOS simulator on same mac machine. I made sure my proxy settings are
correct in system preferences on mac machines and I have provided user
name and password for the proxy also.
I read about using charles proxy for simulator. Also I read about using
connection:didReceiveAuthenticationChallenge: from
NSURLCOnnectiondelegate. Both of them are good solutions but I have some
constraints due to which I can not use these.
Other than above mentioned is there any other solution to this? Like
modifying some configuration file etc. where I can mention proxy and
username password??
Thursday, 19 September 2013
How to enable permissions in SQL Server 2012 FileTable folder share?
How to enable permissions in SQL Server 2012 FileTable folder share?
After successfully creating a FileTable, I tried viewing the fileshare but
my permissions are denied. In Management Studio, right-clicking on
FileTable then "Explore FilteTable Directory" gives me the following error
message:
The File location cannot be opened. Either access is not enabled or your
do not have permissions for the same.
If I try to manually reach the share using \mycomputer\sqlexpress..., I'm
still denied access.
This is SQL Express running on my local machine. I'm accessing this share
from the same machine. What am I missing?
After successfully creating a FileTable, I tried viewing the fileshare but
my permissions are denied. In Management Studio, right-clicking on
FileTable then "Explore FilteTable Directory" gives me the following error
message:
The File location cannot be opened. Either access is not enabled or your
do not have permissions for the same.
If I try to manually reach the share using \mycomputer\sqlexpress..., I'm
still denied access.
This is SQL Express running on my local machine. I'm accessing this share
from the same machine. What am I missing?
Which rules apply and why?
Which rules apply and why?
I'm trying to parse this sample PHP program:
class SimpleClass
{
// Deklaration einer Eigenschaft
public $var = 'ein Standardwert';
// Deklaration einer Methode
public function displayVar() {
echo $this->var;
}
}
Wile the generated parser sees public, it fails to continue with
class_variable_declaration in the first alternative of class_statement.
Additionally, I wonder why as of the graphics below, the first
class_statement node is empty.
Could someone help out?
Class declaration:
class_declaration_statement:
( 'class' | 'abstract' 'class' | 'trait' | 'final' 'class' )
SYMBOL_NAME_LITERAL
( 'extends' fully_qualified_class_name ) ?
( 'implements' interface_list ) ?
'{' class_statement* '}'
| 'interface' SYMBOL_NAME_LITERAL
( 'extends' interface_list ) ?
'{' class_statement* '}'
;
Class statement:
class_statement:
variable_modifiers class_variable_declaration ';'
| class_constant_declaration ';'
| trait_use_statement
| method_modifiers function is_reference SYMBOL_NAME_LITERAL
'(' parameter_list ')'
( ';' | ( '{' inner_statement_list '}' )
;
Class variable declaration
class_variable_declaration:
DOLLAR_VARIABLE ( ',' DOLLAR_VARIABLE )* ( '=' static_scalar )?
;
Modifiers
variable_modifiers:
member_modifier *
| VAR
;
member_modifier:
PUBLIC
| PROTECTED
| PRIVATE
| STATIC
| ABSTRACT
| FINAL
;
ANTLR v 4.1 in use
I'm trying to parse this sample PHP program:
class SimpleClass
{
// Deklaration einer Eigenschaft
public $var = 'ein Standardwert';
// Deklaration einer Methode
public function displayVar() {
echo $this->var;
}
}
Wile the generated parser sees public, it fails to continue with
class_variable_declaration in the first alternative of class_statement.
Additionally, I wonder why as of the graphics below, the first
class_statement node is empty.
Could someone help out?
Class declaration:
class_declaration_statement:
( 'class' | 'abstract' 'class' | 'trait' | 'final' 'class' )
SYMBOL_NAME_LITERAL
( 'extends' fully_qualified_class_name ) ?
( 'implements' interface_list ) ?
'{' class_statement* '}'
| 'interface' SYMBOL_NAME_LITERAL
( 'extends' interface_list ) ?
'{' class_statement* '}'
;
Class statement:
class_statement:
variable_modifiers class_variable_declaration ';'
| class_constant_declaration ';'
| trait_use_statement
| method_modifiers function is_reference SYMBOL_NAME_LITERAL
'(' parameter_list ')'
( ';' | ( '{' inner_statement_list '}' )
;
Class variable declaration
class_variable_declaration:
DOLLAR_VARIABLE ( ',' DOLLAR_VARIABLE )* ( '=' static_scalar )?
;
Modifiers
variable_modifiers:
member_modifier *
| VAR
;
member_modifier:
PUBLIC
| PROTECTED
| PRIVATE
| STATIC
| ABSTRACT
| FINAL
;
ANTLR v 4.1 in use
How to fetch id when using dup.update_attributes()
How to fetch id when using dup.update_attributes()
p = product.dup.update_attributes(name: "The latest thing")
The code above creates (and saves) a duplicate of the product object, with
one attribute altered.
How do I retrieve the id of the newly created record? The variable p is
only returning true.
p = product.dup.update_attributes(name: "The latest thing")
The code above creates (and saves) a duplicate of the product object, with
one attribute altered.
How do I retrieve the id of the newly created record? The variable p is
only returning true.
Selenium IDE: how to get the current date and check whether it lies within a quarter
Selenium IDE: how to get the current date and check whether it lies within
a quarter
Selenium IDE: how to get the current date and compare it with another date
and prove that it is a future date or past date.
a quarter
Selenium IDE: how to get the current date and compare it with another date
and prove that it is a future date or past date.
Store (almost) all objects in workspace in a list
Store (almost) all objects in workspace in a list
Let's say that I have many objects in my workspace (global environment)
and I want to store most of those in a list. Here's a simplified example:
# Put some objects in the workspace
A <- 1
B <- 2
C <- 3
I would like to store objects A and C in a list. Of course, I can do that
explicitly:
mylist <- list(A,C)
However, when the number of objects in the workspace is very large, this
would become rather cumbersome. Hence, I would like to do this differently
and attempted the following:
mylist <- list(setdiff(ls(),B))
But this obviously is not what I want, as it only stores the names of the
objects in the workspace.
Any suggestions on how I can do this?
Many thanks!
Let's say that I have many objects in my workspace (global environment)
and I want to store most of those in a list. Here's a simplified example:
# Put some objects in the workspace
A <- 1
B <- 2
C <- 3
I would like to store objects A and C in a list. Of course, I can do that
explicitly:
mylist <- list(A,C)
However, when the number of objects in the workspace is very large, this
would become rather cumbersome. Hence, I would like to do this differently
and attempted the following:
mylist <- list(setdiff(ls(),B))
But this obviously is not what I want, as it only stores the names of the
objects in the workspace.
Any suggestions on how I can do this?
Many thanks!
Rails and MiniTest: add additional folder
Rails and MiniTest: add additional folder
I use Ruby 2 and Rails 4. I have a folder test/lib, where a few tests are
located. But running rake test does not use them. Only the other tests
(models, controllers, ...) are running.
Where do I have to add the lib folder?
I already tried MiniTest::Rails::Testing.default_tasks << 'lib', but I get
NameError Exception: uninitialized constant MiniTest::Rails. I did not add
the minitest gem to my Gemfile, because Ruby 2 uses it by default.
I use Ruby 2 and Rails 4. I have a folder test/lib, where a few tests are
located. But running rake test does not use them. Only the other tests
(models, controllers, ...) are running.
Where do I have to add the lib folder?
I already tried MiniTest::Rails::Testing.default_tasks << 'lib', but I get
NameError Exception: uninitialized constant MiniTest::Rails. I did not add
the minitest gem to my Gemfile, because Ruby 2 uses it by default.
Sorting city names fails
Sorting city names fails
I want to sort the inputted city names but below code gives me such as:
Ýnput:
Newyork Georgetown Berlin
Output:
Berlin Gewyork Beorgetown
Why is that?
I was thinking to compare with strcmp and swap the pointers then but it
seeems it is not working.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(char *dummy);
void swap(char *first, char *second);
int i;
char *names[3];
char *temp;
int main(void){
//get the names of the cities
puts("Enter names of cities");
for (i = 0; i < 3; i++)
{
names[i]=malloc(100);
fgets( names[i], 99, stdin);
}
//print entered names
for (i = 0; i < 3; i++)
{
printf("%s", names[i]);
}
sort(names);
//print sorted names
for (i = 0; i < 3; i++)
{
printf("%s", names[i]);
}
getch();
}
//sorting function
void sort(char *dummy){
for (i = 0; i < 2; i++)
{
if (strcmp( &dummy[i], &dummy[i+1]) >0)
{
swap(&dummy[i], &dummy[i+1]);
}
}
}
//swapping function
void swap(char *first, char *second){
temp=second;
second=first;
first=temp;
}
I want to sort the inputted city names but below code gives me such as:
Ýnput:
Newyork Georgetown Berlin
Output:
Berlin Gewyork Beorgetown
Why is that?
I was thinking to compare with strcmp and swap the pointers then but it
seeems it is not working.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void sort(char *dummy);
void swap(char *first, char *second);
int i;
char *names[3];
char *temp;
int main(void){
//get the names of the cities
puts("Enter names of cities");
for (i = 0; i < 3; i++)
{
names[i]=malloc(100);
fgets( names[i], 99, stdin);
}
//print entered names
for (i = 0; i < 3; i++)
{
printf("%s", names[i]);
}
sort(names);
//print sorted names
for (i = 0; i < 3; i++)
{
printf("%s", names[i]);
}
getch();
}
//sorting function
void sort(char *dummy){
for (i = 0; i < 2; i++)
{
if (strcmp( &dummy[i], &dummy[i+1]) >0)
{
swap(&dummy[i], &dummy[i+1]);
}
}
}
//swapping function
void swap(char *first, char *second){
temp=second;
second=first;
first=temp;
}
Packaging a BCS Solution as a SharePoint Application for SharePoint 2013
Packaging a BCS Solution as a SharePoint Application for SharePoint 2013
Our team recently setup our own SharePoint 2013 Server and we are starting
to enable some of the Service Applications one by one. One of my colleague
was able to setup some solution using external content types which
connects to an SQL Server Database. Would it be possible for us to
repackage that same solution so that it can be distributed using the
SharePoint App Store?
Our team recently setup our own SharePoint 2013 Server and we are starting
to enable some of the Service Applications one by one. One of my colleague
was able to setup some solution using external content types which
connects to an SQL Server Database. Would it be possible for us to
repackage that same solution so that it can be distributed using the
SharePoint App Store?
Wednesday, 18 September 2013
nodejs querying data and code organization
nodejs querying data and code organization
Just started to learn nodejs, pretty new to js as well, and looked around
for best practices and came across this:
http://stackoverflow.com/a/15572522/1203349
I'm working on an app using this structure. He recommended putting the db
calls in corresponding model/model.js files.
E.g.
Using his sample, suppose I want a complete listing of blogs.
In routes/blog/index.js, should I do something like:
var Model = require('../../models');
module.exports = function(app){
app.get('/blog', function(req,res){
//what now? function calls into Model? how?
//also, why doesn't Model.blogModel.find({}, function(err, blogs){
//work with blogs
//}; work? I'm getting a ReferenceError: blogModel is not defined.
});
}
and in models/blog.js,
....
exports.<every function for crud>?
example implementation would be greatly appreciated.
Just started to learn nodejs, pretty new to js as well, and looked around
for best practices and came across this:
http://stackoverflow.com/a/15572522/1203349
I'm working on an app using this structure. He recommended putting the db
calls in corresponding model/model.js files.
E.g.
Using his sample, suppose I want a complete listing of blogs.
In routes/blog/index.js, should I do something like:
var Model = require('../../models');
module.exports = function(app){
app.get('/blog', function(req,res){
//what now? function calls into Model? how?
//also, why doesn't Model.blogModel.find({}, function(err, blogs){
//work with blogs
//}; work? I'm getting a ReferenceError: blogModel is not defined.
});
}
and in models/blog.js,
....
exports.<every function for crud>?
example implementation would be greatly appreciated.
What naming scheme(s) will allow an iOS app's background to be autodetected?
What naming scheme(s) will allow an iOS app's background to be autodetected?
In a newly created iOS project in Xcode, there exists Default.png and
Default@2x.png, as best I remember.
Is there a standard naming schema that will populate screen sizes for all
present iOS devices, once they're created and added to the project? Or how
can I provide a background image for each resolution, and have that
background be displayed before any images are drawn, and perhaps displayed
for a splash screen?
In a newly created iOS project in Xcode, there exists Default.png and
Default@2x.png, as best I remember.
Is there a standard naming schema that will populate screen sizes for all
present iOS devices, once they're created and added to the project? Or how
can I provide a background image for each resolution, and have that
background be displayed before any images are drawn, and perhaps displayed
for a splash screen?
toggleclass not binding click event
toggleclass not binding click event
Added a class to my button and trying to launch on onclick event after,
not working . pretty simple code why is the event not binding what am I
doing wrong?
http://jsfiddle.net/davidThomas/n2WUn/3/
$(".remove-participant").on("click",function(){
$(this).html('Approve');
$(this).toggleClass('add-participant');
});
$(".add-participant").on("click",function(){
alert('why no alert?');
$(this).html('Waitlist');
$(this).toggleClass('add-participant');
});
Added a class to my button and trying to launch on onclick event after,
not working . pretty simple code why is the event not binding what am I
doing wrong?
http://jsfiddle.net/davidThomas/n2WUn/3/
$(".remove-participant").on("click",function(){
$(this).html('Approve');
$(this).toggleClass('add-participant');
});
$(".add-participant").on("click",function(){
alert('why no alert?');
$(this).html('Waitlist');
$(this).toggleClass('add-participant');
});
consult tablespace of a table but unused dba_tablespaces
consult tablespace of a table but unused dba_tablespaces
I need know the tablespace of particulary table, the typical query SELECT
owner, table_name, tablespace_name FROM dba_tables; can't use, because I
haven't permissions. There is other way to consult Tablespace unused
dba_tablespaces?
I need know the tablespace of particulary table, the typical query SELECT
owner, table_name, tablespace_name FROM dba_tables; can't use, because I
haven't permissions. There is other way to consult Tablespace unused
dba_tablespaces?
static members throught static methods
static members throught static methods
Given: 1. public class Base { 2. public static final String FOO = "foo";
3. public static void main(String[] args) { 4. Base b = new Base(); 5. Sub
s = new Sub(); 6. System.out.print(Base.FOO); 7.
System.out.print(Sub.FOO); 8. System.out.print(b.FOO); 9.
System.out.print(s.FOO); 10. System.out.print(((Base)s).FOO); 11. } } 12.
class Sub extends Base {public static final String FOO="bar";}
What is the result? A. foofoofoofoofoo B. foobarfoobarbar C.
foobarfoofoofoo D. foobarfoobarfoo E. barbarbarbarbar F. foofoofoobarbar
G. foofoofoobarfoo Answer: D
My doubt is that in line 8 and line we are using reference variables to
access static members of class..is it possible? because static members are
accessed by class names only..plz correct me where i am wrong?
Given: 1. public class Base { 2. public static final String FOO = "foo";
3. public static void main(String[] args) { 4. Base b = new Base(); 5. Sub
s = new Sub(); 6. System.out.print(Base.FOO); 7.
System.out.print(Sub.FOO); 8. System.out.print(b.FOO); 9.
System.out.print(s.FOO); 10. System.out.print(((Base)s).FOO); 11. } } 12.
class Sub extends Base {public static final String FOO="bar";}
What is the result? A. foofoofoofoofoo B. foobarfoobarbar C.
foobarfoofoofoo D. foobarfoobarfoo E. barbarbarbarbar F. foofoofoobarbar
G. foofoofoobarfoo Answer: D
My doubt is that in line 8 and line we are using reference variables to
access static members of class..is it possible? because static members are
accessed by class names only..plz correct me where i am wrong?
SQL Server DateTime2 Error
SQL Server DateTime2 Error
I'm in a process of migrating data from Oracle to Microsoft SQL Server. In
oracle, date range is between '01-01-0001' to '31-12-9999'. I'm using
Pentaho tool to migrate data from Oracle to Microsoft SQLServer. When I
migrate data, it pops error that, "Only dates between January 1, 1753 and
December 31, 9999 are accepted."
To resolve this kind of date issue, I converted "Datetime" data type to
"Datetime2". Even after changing data type, I get the same error of "Only
dates between January 1, 1753 and December 31, 9999 are accepted." I'm
using Pentaho Data Integration to Migrate data.
Any kind of solution?
I'm in a process of migrating data from Oracle to Microsoft SQL Server. In
oracle, date range is between '01-01-0001' to '31-12-9999'. I'm using
Pentaho tool to migrate data from Oracle to Microsoft SQLServer. When I
migrate data, it pops error that, "Only dates between January 1, 1753 and
December 31, 9999 are accepted."
To resolve this kind of date issue, I converted "Datetime" data type to
"Datetime2". Even after changing data type, I get the same error of "Only
dates between January 1, 1753 and December 31, 9999 are accepted." I'm
using Pentaho Data Integration to Migrate data.
Any kind of solution?
Reading JSON on Android, No Output
Reading JSON on Android, No Output
This is my JSON data.
{"JSONDATA":[{"key":0,"value":"--Any--"},{"key":61,"value":"Accounting"},{"key":81,"value":"Aerospace
&
Defense"},{"key":72,"value":"Automotive"},{"key":83,"value":"Banking"},{"key":84,"value":"Biotech"},{"key":85,"value":"Construction"},{"key":86,"value":"Customer
Service"},{"key":87,"value":"Education"},{"key":82,"value":"Energy"},{"key":70,"value":"Finance"},{"key":193,"value":"Government"},{"key":194,"value":"Healthcare"},{"key":71,"value":"Insurance"},{"key":73,"value":"Legal"},{"key":62,"value":"Management"},{"key":63,"value":"Manufacturing"},{"key":64,"value":"Marketing\/Advertising"},{"key":77,"value":"Media
- Journalism"},{"key":74,"value":"Pharmaceutical"},{"key":75,"value":"Real
Estate"},{"key":76,"value":"Research"},{"key":65,"value":"Restaurant"},{"key":66,"value":"Retail"},{"key":67,"value":"Sales"},{"key":78,"value":"Science"},{"key":68,"value":"Telecommunications"},{"key":79,"value":"Training"},{"key":69,"value":"Transportation"},{"key":80,"value":"Utilities"}]}
I want to decode it on my Android App, This is the code i have used., But
i don't get anything on my output. No errors too.
JSONObject jObject= new JSONObject();
JSONArray menuObject = new JSONArray(jObject.getString("JSONDATA"));
String app;
for (int i = 0; i<menuObject.length(); i++) {
{
app=menuObject.getJSONObject(i).getString("value").toString();
a.append(app); // a is my TextView
}
This is my JSON data.
{"JSONDATA":[{"key":0,"value":"--Any--"},{"key":61,"value":"Accounting"},{"key":81,"value":"Aerospace
&
Defense"},{"key":72,"value":"Automotive"},{"key":83,"value":"Banking"},{"key":84,"value":"Biotech"},{"key":85,"value":"Construction"},{"key":86,"value":"Customer
Service"},{"key":87,"value":"Education"},{"key":82,"value":"Energy"},{"key":70,"value":"Finance"},{"key":193,"value":"Government"},{"key":194,"value":"Healthcare"},{"key":71,"value":"Insurance"},{"key":73,"value":"Legal"},{"key":62,"value":"Management"},{"key":63,"value":"Manufacturing"},{"key":64,"value":"Marketing\/Advertising"},{"key":77,"value":"Media
- Journalism"},{"key":74,"value":"Pharmaceutical"},{"key":75,"value":"Real
Estate"},{"key":76,"value":"Research"},{"key":65,"value":"Restaurant"},{"key":66,"value":"Retail"},{"key":67,"value":"Sales"},{"key":78,"value":"Science"},{"key":68,"value":"Telecommunications"},{"key":79,"value":"Training"},{"key":69,"value":"Transportation"},{"key":80,"value":"Utilities"}]}
I want to decode it on my Android App, This is the code i have used., But
i don't get anything on my output. No errors too.
JSONObject jObject= new JSONObject();
JSONArray menuObject = new JSONArray(jObject.getString("JSONDATA"));
String app;
for (int i = 0; i<menuObject.length(); i++) {
{
app=menuObject.getJSONObject(i).getString("value").toString();
a.append(app); // a is my TextView
}
how to set request attributes in jsp and how to get in servlet
how to set request attributes in jsp and how to get in servlet
i am setting request attributes in jsp. but i am not getting that request
attributes in servlet it is getting null.if i set like
request.getSession().setAttribute(); it is working fine but
request.setAttribute() means it is getting null. please help me how set
request attributes in jsp without session.
i am setting request attributes in jsp. but i am not getting that request
attributes in servlet it is getting null.if i set like
request.getSession().setAttribute(); it is working fine but
request.setAttribute() means it is getting null. please help me how set
request attributes in jsp without session.
Tuesday, 17 September 2013
how to use expandable listview for different images?
how to use expandable listview for different images?
I want to use different images in place of text string as child of
expandable list view. and on click event of these images,the different
child layouts should open. Can anybody tell how can i achieve this? I have
gone through many codes but unable to find correct answer.I don't
understand how to fetch images on expandable list view from drawable
folder. I know how to get text from strings but I have used array for
images and don't know how to add these. I am new to android so don't know
about proper format of code.
I want to use different images in place of text string as child of
expandable list view. and on click event of these images,the different
child layouts should open. Can anybody tell how can i achieve this? I have
gone through many codes but unable to find correct answer.I don't
understand how to fetch images on expandable list view from drawable
folder. I know how to get text from strings but I have used array for
images and don't know how to add these. I am new to android so don't know
about proper format of code.
python gevent import error
python gevent import error
When I run an example of gevent, I get import error here. I am using
macos, gevent is installed by pip.
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import gevent
>>> from gevent import socket
>>> urls = ['www.google.com', 'www.example.com', 'www.python.org']
>>> jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "gevent/greenlet.py", line 201, in spawn
g = cls(*args, **kwargs)
File "gevent/greenlet.py", line 75, in __init__
hub = get_hub()
File "gevent/hub.py", line 169, in get_hub
hub = _threadlocal.hub = hubtype(*args, **kwargs)
File "gevent/hub.py", line 268, in __init__
loop_class = _import(self.loop_class)
File "gevent/hub.py", line 198, in _import
return _import(path[-1])
File "gevent/hub.py", line 210, in _import
x = __import__(module)
ImportError: No module named core
=============================================================== PS:When I
install gevent, there are some warnings in the output.
tanminghuan@bogon ~/Code/gevent (master)$ sudo pip install gevent
Downloading/unpacking gevent
Downloading gevent-0.13.8.tar.gz (300kB): 300kB downloaded
Running setup.py egg_info for package gevent
Requirement already satisfied (use --upgrade to upgrade): greenlet in
/Library/Python/2.7/site-packages/greenlet-0.4.1-py2.7-macosx-10.8-intel.egg
(from gevent)
Installing collected packages: gevent
Running setup.py install for gevent
building 'gevent.core' extension
clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe
-fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd
-DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes
-Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes
-DENABLE_DTRACE -arch i386 -arch x86_64 -pipe
-I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7
-c gevent/core.c -o build/temp.macosx-10.8-intel-2.7/gevent/core.o
clang: warning: argument unused during compilation: '-mno-fused-madd'
gevent/core.c:8113:15: warning: implicit conversion loses integer
precision: 'size_t' (aka 'unsigned long') to 'int'
[-Wshorten-64-to-32]
__pyx_r = evbuffer_get_length(__pyx_v_self->__pyx___obj);
~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning generated.
clang -bundle -undefined dynamic_lookup -Wl,-F. -arch i386 -arch
x86_64 build/temp.macosx-10.8-intel-2.7/gevent/core.o -levent -o
build/lib.macosx-10.8-intel-2.7/gevent/core.so
ld: warning: ignoring file /usr/local/lib/libevent.dylib, file was
built for unsupported file format ( 0xcf 0xfa 0xed 0xfe 0x 7 0x 0 0x 0
0x 1 0x 3 0x 0 0x 0 0x 0 0x 6 0x 0 0x 0 0x 0 ) which is not the
architecture being linked (i386): /usr/local/lib/libevent.dylib
Linking
/private/tmp/pip_build_root/gevent/build/lib.macosx-10.8-intel-2.7/gevent/core.so
to /private/tmp/pip_build_root/gevent/gevent/core.so
Successfully installed gevent
Cleaning up...
When I run an example of gevent, I get import error here. I am using
macos, gevent is installed by pip.
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import gevent
>>> from gevent import socket
>>> urls = ['www.google.com', 'www.example.com', 'www.python.org']
>>> jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "gevent/greenlet.py", line 201, in spawn
g = cls(*args, **kwargs)
File "gevent/greenlet.py", line 75, in __init__
hub = get_hub()
File "gevent/hub.py", line 169, in get_hub
hub = _threadlocal.hub = hubtype(*args, **kwargs)
File "gevent/hub.py", line 268, in __init__
loop_class = _import(self.loop_class)
File "gevent/hub.py", line 198, in _import
return _import(path[-1])
File "gevent/hub.py", line 210, in _import
x = __import__(module)
ImportError: No module named core
=============================================================== PS:When I
install gevent, there are some warnings in the output.
tanminghuan@bogon ~/Code/gevent (master)$ sudo pip install gevent
Downloading/unpacking gevent
Downloading gevent-0.13.8.tar.gz (300kB): 300kB downloaded
Running setup.py egg_info for package gevent
Requirement already satisfied (use --upgrade to upgrade): greenlet in
/Library/Python/2.7/site-packages/greenlet-0.4.1-py2.7-macosx-10.8-intel.egg
(from gevent)
Installing collected packages: gevent
Running setup.py install for gevent
building 'gevent.core' extension
clang -fno-strict-aliasing -fno-common -dynamic -g -Os -pipe
-fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd
-DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes
-Wshorten-64-to-32 -DNDEBUG -g -Os -Wall -Wstrict-prototypes
-DENABLE_DTRACE -arch i386 -arch x86_64 -pipe
-I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7
-c gevent/core.c -o build/temp.macosx-10.8-intel-2.7/gevent/core.o
clang: warning: argument unused during compilation: '-mno-fused-madd'
gevent/core.c:8113:15: warning: implicit conversion loses integer
precision: 'size_t' (aka 'unsigned long') to 'int'
[-Wshorten-64-to-32]
__pyx_r = evbuffer_get_length(__pyx_v_self->__pyx___obj);
~ ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 warning generated.
clang -bundle -undefined dynamic_lookup -Wl,-F. -arch i386 -arch
x86_64 build/temp.macosx-10.8-intel-2.7/gevent/core.o -levent -o
build/lib.macosx-10.8-intel-2.7/gevent/core.so
ld: warning: ignoring file /usr/local/lib/libevent.dylib, file was
built for unsupported file format ( 0xcf 0xfa 0xed 0xfe 0x 7 0x 0 0x 0
0x 1 0x 3 0x 0 0x 0 0x 0 0x 6 0x 0 0x 0 0x 0 ) which is not the
architecture being linked (i386): /usr/local/lib/libevent.dylib
Linking
/private/tmp/pip_build_root/gevent/build/lib.macosx-10.8-intel-2.7/gevent/core.so
to /private/tmp/pip_build_root/gevent/gevent/core.so
Successfully installed gevent
Cleaning up...
get value of hidden field set by another function
get value of hidden field set by another function
I have a form that has a checkbox that when click, triggers an event in
javascript that assigns a value to a hidden field. However, I cannot
access this when I try to validate the form. It actually causes the entire
script to fail. I've tried to access it with:
var hiddenField = document.forms[myForm].elements[hiddenField].value;
and with:
var hiddenField = document.getElementById('hiddenField').value;
and:
var hiddenField = document.getElementById('hiddenField');
then adding .value to variable when it's actually used in the script. I've
stepped through all of it in firebug and watched the other function assign
the appropriate value to the hidden field. This variable assignment is
actually where the script gets killed. Any help or suggestions would be
greatly appreciated!
I have a form that has a checkbox that when click, triggers an event in
javascript that assigns a value to a hidden field. However, I cannot
access this when I try to validate the form. It actually causes the entire
script to fail. I've tried to access it with:
var hiddenField = document.forms[myForm].elements[hiddenField].value;
and with:
var hiddenField = document.getElementById('hiddenField').value;
and:
var hiddenField = document.getElementById('hiddenField');
then adding .value to variable when it's actually used in the script. I've
stepped through all of it in firebug and watched the other function assign
the appropriate value to the hidden field. This variable assignment is
actually where the script gets killed. Any help or suggestions would be
greatly appreciated!
Java Test Client can not find properties file in Java Project
Java Test Client can not find properties file in Java Project
I have following set-up in Eclipse:
Project A - A Dynamic Web Project used as a code for Web Service. Project
B - A test client with class containing Main() so that I can test the
project A.
Project A contains a properties file which works fine when project A is
deployed as web service. But when I run the test from test client project
B, the properties file is not recognized. I have created a folder called
'resources' which is at same level as 'src' folder in Project A and this
resources folder contains the properties file. The project B has Project A
in it's build path.
I have following set-up in Eclipse:
Project A - A Dynamic Web Project used as a code for Web Service. Project
B - A test client with class containing Main() so that I can test the
project A.
Project A contains a properties file which works fine when project A is
deployed as web service. But when I run the test from test client project
B, the properties file is not recognized. I have created a folder called
'resources' which is at same level as 'src' folder in Project A and this
resources folder contains the properties file. The project B has Project A
in it's build path.
Knockout vs. JQuery
Knockout vs. JQuery
I am trying to evaluate javascript libraries/framework for my big
data/cloud computing project. I am a back end developer trying to get
started with frontend so keeping that perspective in my mind as you
respond to this question and thinking about performance, learning curve,
ease of use, etc (issues one deals with in the big data arena) can you
give me any pointers (pros n cons) for picking knockout vs. jquery? Thanks
in advance for your suggestions.
I am trying to evaluate javascript libraries/framework for my big
data/cloud computing project. I am a back end developer trying to get
started with frontend so keeping that perspective in my mind as you
respond to this question and thinking about performance, learning curve,
ease of use, etc (issues one deals with in the big data arena) can you
give me any pointers (pros n cons) for picking knockout vs. jquery? Thanks
in advance for your suggestions.
Binding with a class that derives from List
Binding with a class that derives from List
How can I bind my ComboBox with a class that derives from List(Of T)? I
have tried assigning the class instance directly to ComboBox.DataSource,
which doesn't work. I have tried to assign the instance to
BindingSource.DataSource too (and then assigning that BindingSource to
ComboBox.DataSource), this one also doesn't update my ComboBox when new
items are added to/removed from the List. Only the objects that existed in
the List at the time of binding are shown.
The DisplayMember and ValueMember properties of the ComboBox are properly
set.
Here is my List class:
Public Class DrawingObjectsList
Inherits List(Of DrawingObjectBase)
...
End Class
Here is the list instance:
Private mDOs As New DrawingObjectsList
Here's my ComboBox and accompanying BindingSource binding:
Dim WithEvents bsDOs As System.Windows.Forms.BindingSource
bsDOs.DataSource = mDOs
cboObjects.DataSource = Me.bsDOs
cboObjects.DisplayMember = "Name"
cboObjects.ValueMember = "ObjectID"
How can I bind my ComboBox with a class that derives from List(Of T)? I
have tried assigning the class instance directly to ComboBox.DataSource,
which doesn't work. I have tried to assign the instance to
BindingSource.DataSource too (and then assigning that BindingSource to
ComboBox.DataSource), this one also doesn't update my ComboBox when new
items are added to/removed from the List. Only the objects that existed in
the List at the time of binding are shown.
The DisplayMember and ValueMember properties of the ComboBox are properly
set.
Here is my List class:
Public Class DrawingObjectsList
Inherits List(Of DrawingObjectBase)
...
End Class
Here is the list instance:
Private mDOs As New DrawingObjectsList
Here's my ComboBox and accompanying BindingSource binding:
Dim WithEvents bsDOs As System.Windows.Forms.BindingSource
bsDOs.DataSource = mDOs
cboObjects.DataSource = Me.bsDOs
cboObjects.DisplayMember = "Name"
cboObjects.ValueMember = "ObjectID"
Sunday, 15 September 2013
Standard Fortran interface for cuBLAS
Standard Fortran interface for cuBLAS
I am using a commercial simulation software on Linux that does intensive
matrix manipulation. The software uses Intel MKL by default, but it allows
me to replace it with a custom BLAS/LAPACK library. This library must be a
shared object (.so) library and must export both BLAS and LAPACK standard
routines. The software requires the standard Fortran interface for all of
them.
To verify that I can use a custom library, I compiled ATLAS and linked
LAPACK (from netlib) inside it. The software was able to use my compiled
ATLAS version without any problems.
Now, I want to make the software use cuBLAS in order to enhance the
simulation speed. I was confronted by the problem that cuBLAS doesn't
export the standard BLAS function names (they have a cublas prefix).
Moreover, the library cuBLAS library doesn't include LAPACK routines. I
use readelf -a to check for the exported function.
On another hand, I tried to use MAGMA to solve this problem. I succeeded
to compile and link it against all of ATLAS, LAPACK and cuBLAS. But still
it doesn't export the correct functions and doesn't include LAPACK in the
final shared object. I am not sure if this is the way it is supposed to be
or I did something wrong during the build process.
I have also found CULA, but I am not sure if this will solve the problem
or not.
Did anybody tried to get cuBLAS/LAPACK (or a proper wrapper) linked into a
single (.so) exporting the standard Fortran interface with the correct
function names? I believe it is conceptually possible, but I don't know
how to do it!
I am using a commercial simulation software on Linux that does intensive
matrix manipulation. The software uses Intel MKL by default, but it allows
me to replace it with a custom BLAS/LAPACK library. This library must be a
shared object (.so) library and must export both BLAS and LAPACK standard
routines. The software requires the standard Fortran interface for all of
them.
To verify that I can use a custom library, I compiled ATLAS and linked
LAPACK (from netlib) inside it. The software was able to use my compiled
ATLAS version without any problems.
Now, I want to make the software use cuBLAS in order to enhance the
simulation speed. I was confronted by the problem that cuBLAS doesn't
export the standard BLAS function names (they have a cublas prefix).
Moreover, the library cuBLAS library doesn't include LAPACK routines. I
use readelf -a to check for the exported function.
On another hand, I tried to use MAGMA to solve this problem. I succeeded
to compile and link it against all of ATLAS, LAPACK and cuBLAS. But still
it doesn't export the correct functions and doesn't include LAPACK in the
final shared object. I am not sure if this is the way it is supposed to be
or I did something wrong during the build process.
I have also found CULA, but I am not sure if this will solve the problem
or not.
Did anybody tried to get cuBLAS/LAPACK (or a proper wrapper) linked into a
single (.so) exporting the standard Fortran interface with the correct
function names? I believe it is conceptually possible, but I don't know
how to do it!
OpenGL 2D Game Texture Artifacts
OpenGL 2D Game Texture Artifacts
I'm drawing supposedly a pixel-perfect game for iOS:
glitchypixels
The problem is that every few frames I see random pieces of another
texture being drawn (the teal dots floating in the blackness). First, I
tried making sure the quads all lined up completely. Next, I changed the
Z-buffer size. Neither of these things seemed to help.
I am using a texture atlas, but unfortunately I can't add in padding
pixels (one solution I've seen). Now, if I change the texture coordinates
from 0,1 to 0.005,0.95 the problem goes away but it looks like garbage.
Does the behavior of this screenshot suggest another solution I haven't
tied? Note that my filtering mode has to stay NEAREST for the sprite art,
and that the problem goes away when I force my character/camera to move in
whole pixel increments (which unfortunately doesn't feel as good as moving
in subpixels).
I'm drawing supposedly a pixel-perfect game for iOS:
glitchypixels
The problem is that every few frames I see random pieces of another
texture being drawn (the teal dots floating in the blackness). First, I
tried making sure the quads all lined up completely. Next, I changed the
Z-buffer size. Neither of these things seemed to help.
I am using a texture atlas, but unfortunately I can't add in padding
pixels (one solution I've seen). Now, if I change the texture coordinates
from 0,1 to 0.005,0.95 the problem goes away but it looks like garbage.
Does the behavior of this screenshot suggest another solution I haven't
tied? Note that my filtering mode has to stay NEAREST for the sprite art,
and that the problem goes away when I force my character/camera to move in
whole pixel increments (which unfortunately doesn't feel as good as moving
in subpixels).
Plot 3D Contour from an Image using extent with Matplotlib
Plot 3D Contour from an Image using extent with Matplotlib
As I present here (in 2D), I'm wondering if how I could "scale" an image
input to be plotted to a range in the plot. To be more clear, this is what
I need:
I have a 400 * 400 image that is generated based on a function which
interval is -1..1. So, I do a translate to save this data, like this:
x = Utils.translate(pos_x, 0, self.width, -1, 1)
y = Utils.translate(pos_y, 0, self.height, -1, 1)
data = Utils.map_position_to_function(x, y)
I.e, first I map its position to my range and then I calculate de f(x, y)
based on this "new position" and save the data. Also, as I save this
image, I do a translate in data so it fits in a 0..255 range, generating a
grayscale image.
The problem is that, later, I have to represent the image contour in the
function range. So, I have an image, 400 * 400, that I have to represent
in a plot which range is -1..1.
In 2D, I could do this with this code:
im = plt.array(Image.open('Mean.png').convert('L'))
plt.figure()
CS = plt.contour(im, origin='image', extent=[-1, 1, -1, 1])
plt.clabel(CS, inline=1, fontsize=10)
plt.savefig("CountorLevel2D.png")
In 3D, I tried this:
fig = plt.figure()
ax = fig.gca(projection='3d')
row = np.linspace(0, 400, 400)
X,Y = np.meshgrid(row,row)
CS = ax.contour(X, Y, im, cmap=cm.coolwarm, extent=[-1, 1, -1, 1])
plt.clabel(CS, inline=1, fontsize=10)
plt.savefig("ContourLevel3D.png")
But the X and Y are still in the 0..400 range. I don't know what is wrong,
or what I have to do to have X and Y in -1..1 range. Besides, no label is
shown.
Also, as im is an image, I read values which ranges between 0..255 values.
How could I present this in an -1..1 range too?
Thanks in advance. (:
As I present here (in 2D), I'm wondering if how I could "scale" an image
input to be plotted to a range in the plot. To be more clear, this is what
I need:
I have a 400 * 400 image that is generated based on a function which
interval is -1..1. So, I do a translate to save this data, like this:
x = Utils.translate(pos_x, 0, self.width, -1, 1)
y = Utils.translate(pos_y, 0, self.height, -1, 1)
data = Utils.map_position_to_function(x, y)
I.e, first I map its position to my range and then I calculate de f(x, y)
based on this "new position" and save the data. Also, as I save this
image, I do a translate in data so it fits in a 0..255 range, generating a
grayscale image.
The problem is that, later, I have to represent the image contour in the
function range. So, I have an image, 400 * 400, that I have to represent
in a plot which range is -1..1.
In 2D, I could do this with this code:
im = plt.array(Image.open('Mean.png').convert('L'))
plt.figure()
CS = plt.contour(im, origin='image', extent=[-1, 1, -1, 1])
plt.clabel(CS, inline=1, fontsize=10)
plt.savefig("CountorLevel2D.png")
In 3D, I tried this:
fig = plt.figure()
ax = fig.gca(projection='3d')
row = np.linspace(0, 400, 400)
X,Y = np.meshgrid(row,row)
CS = ax.contour(X, Y, im, cmap=cm.coolwarm, extent=[-1, 1, -1, 1])
plt.clabel(CS, inline=1, fontsize=10)
plt.savefig("ContourLevel3D.png")
But the X and Y are still in the 0..400 range. I don't know what is wrong,
or what I have to do to have X and Y in -1..1 range. Besides, no label is
shown.
Also, as im is an image, I read values which ranges between 0..255 values.
How could I present this in an -1..1 range too?
Thanks in advance. (:
Duplicating a group of effects from another document using actions
Duplicating a group of effects from another document using actions
I want to apply different effects and overlays (images) collected in a
single group onto multiple images using batch processing.
Is there a way to copy them onto the images instead of recreating and
recording them in an action?
To clarify: Effect Group (Adjustment layers and an image) --->
IMG_0001.jpg, IMG_0002.jpg ...
I want to apply different effects and overlays (images) collected in a
single group onto multiple images using batch processing.
Is there a way to copy them onto the images instead of recreating and
recording them in an action?
To clarify: Effect Group (Adjustment layers and an image) --->
IMG_0001.jpg, IMG_0002.jpg ...
how do I open bootstrap gem in sublime
how do I open bootstrap gem in sublime
I'm building a project and I need to override the default styles of
bootstrap in the source code . So how do I access the source code ?
I'm building a project and I need to override the default styles of
bootstrap in the source code . So how do I access the source code ?
How would I go about selecting more columns with this query
How would I go about selecting more columns with this query
I just need to know how I would place more table columns in this query,
like major ect.
Thank you!
MySqlDataAdapter adap = new MySqlDataAdapter(@"SELECT * FROM student", conn);
MySqlCommandBuilder sqlCmd = new MySqlCommandBuilder(adap);
DataSet sqlSet = new DataSet();
adap.Fill(sqlSet, "studentNumber");
conn.Close();
return sqlSet;
I just need to know how I would place more table columns in this query,
like major ect.
Thank you!
MySqlDataAdapter adap = new MySqlDataAdapter(@"SELECT * FROM student", conn);
MySqlCommandBuilder sqlCmd = new MySqlCommandBuilder(adap);
DataSet sqlSet = new DataSet();
adap.Fill(sqlSet, "studentNumber");
conn.Close();
return sqlSet;
how to customize a key board shortcuts on windows?
how to customize a key board shortcuts on windows?
Can any one provide me with step by step algorithm to make a keyboard
shortcut on windows 7.
Also kindly tell me that where the hibernation file resides in a computer
, so that I can make its shortcut too.
Can any one provide me with step by step algorithm to make a keyboard
shortcut on windows 7.
Also kindly tell me that where the hibernation file resides in a computer
, so that I can make its shortcut too.
Saturday, 14 September 2013
Generating random numbers in python
Generating random numbers in python
don't mean to bother, but I'm new to programming, and i'm not entirely
sure what to do here. I'm trying to make a basic dice roller. When i run
this program in Codeskulptor, it throws an error on the randint function.
Can I not set the range for it using raw_input plugged into variables? Is
there a different function I should use? Thanks, and sorry if im not using
correct terminologies.
"""Program to roll random numbers within the ranges set."""
import random
sides_of_die=raw_input("Enter how many sides your die has: ")
number_of_dice=raw_input("Enter number of dice you have: ")
total=sides_of_die*number_of_dice
rollinput=raw_input("Would you like to roll now?")
rollinputcap=rollinput.upper()
if rollinputcap =="Y":
print random.randint(number_of_dice,total)
else:
print "What do you want then?"
don't mean to bother, but I'm new to programming, and i'm not entirely
sure what to do here. I'm trying to make a basic dice roller. When i run
this program in Codeskulptor, it throws an error on the randint function.
Can I not set the range for it using raw_input plugged into variables? Is
there a different function I should use? Thanks, and sorry if im not using
correct terminologies.
"""Program to roll random numbers within the ranges set."""
import random
sides_of_die=raw_input("Enter how many sides your die has: ")
number_of_dice=raw_input("Enter number of dice you have: ")
total=sides_of_die*number_of_dice
rollinput=raw_input("Would you like to roll now?")
rollinputcap=rollinput.upper()
if rollinputcap =="Y":
print random.randint(number_of_dice,total)
else:
print "What do you want then?"
Marionette.js.append div clear element after render
Marionette.js.append div clear element after render
Marionette.Js problem unable to append clear div
evey thing i do i keed having the div clear appended before my items
like
list clear item item item
here is my code
var MyItemView = Backbone.Marionette.ItemView.extend({
template: tplI ,
className: 'item',
tagName : 'article',
});
var myCompositeView = Backbone.Marionette.CompositeView.extend({
itemView: MyItemView ,
itemViewContainer: "#list",
template: tplC ,
className : 'wikis' ,
initialize: function () {
this.collection = new Collection () ;
this.model = new CollectionModel() ;
this.listenTo(this.collection, "reset", this.set);
},
set: function ( collect ) {
this.model.set( collect.wiki ) ;
this.render() ;
} ,
onRender : function( evt ){
if ( $.trim( this.$('#list').html() ) != "" ) {
this.$('#list').append( '<div class="clear"></div>' ) ;
}
},
onClose :function() { $('#list').
this.$el.height( 0 ) ;
}
});
Thanks for your help
Marionette.Js problem unable to append clear div
evey thing i do i keed having the div clear appended before my items
like
list clear item item item
here is my code
var MyItemView = Backbone.Marionette.ItemView.extend({
template: tplI ,
className: 'item',
tagName : 'article',
});
var myCompositeView = Backbone.Marionette.CompositeView.extend({
itemView: MyItemView ,
itemViewContainer: "#list",
template: tplC ,
className : 'wikis' ,
initialize: function () {
this.collection = new Collection () ;
this.model = new CollectionModel() ;
this.listenTo(this.collection, "reset", this.set);
},
set: function ( collect ) {
this.model.set( collect.wiki ) ;
this.render() ;
} ,
onRender : function( evt ){
if ( $.trim( this.$('#list').html() ) != "" ) {
this.$('#list').append( '<div class="clear"></div>' ) ;
}
},
onClose :function() { $('#list').
this.$el.height( 0 ) ;
}
});
Thanks for your help
An Applescript to remove duplicate fields within the same contact card
An Applescript to remove duplicate fields within the same contact card
I noticed that I have many (hundreds) duplicate field names and values in
my OS X 10.8.5 Address Book. "Field names and values" are probably not the
right words, but what I mean is, that I have many contact cards that seem
to have identical fields like this:
The problem is not confined to social profiles. Also emails, addresses,
phones, (and maybe more) suffer from duplication.
I got introduced to AppleScript yesterday, and although I do get it a
little (can run them, can play around a bit with existing scripts, know
about save :)), this is still beyond my capabilities:
I would be really helped by such an AppleScript that removes duplicate
fields per card if they have the same type(?) and the same label(?) and
the same value(?). (But keeping one instance.)
I can imagine that addresses (with street, postal code, etc), might be
asking too much. But, non-composite "fields" would already clean up my
address book significantly.
Apologies for surely not getting the technical terms right.
I noticed that I have many (hundreds) duplicate field names and values in
my OS X 10.8.5 Address Book. "Field names and values" are probably not the
right words, but what I mean is, that I have many contact cards that seem
to have identical fields like this:
The problem is not confined to social profiles. Also emails, addresses,
phones, (and maybe more) suffer from duplication.
I got introduced to AppleScript yesterday, and although I do get it a
little (can run them, can play around a bit with existing scripts, know
about save :)), this is still beyond my capabilities:
I would be really helped by such an AppleScript that removes duplicate
fields per card if they have the same type(?) and the same label(?) and
the same value(?). (But keeping one instance.)
I can imagine that addresses (with street, postal code, etc), might be
asking too much. But, non-composite "fields" would already clean up my
address book significantly.
Apologies for surely not getting the technical terms right.
java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
java.security.InvalidAlgorithmParameterException: the trustAnchors
parameter must be non-empty
net.ssl.SSLException: java.lang.RuntimeException: Unexpected error:
java.security.InvalidAlgorithmParameterException: the trustAnchors
parameter must be non-empty" error on my ARM device with a linux and
openjdk when my application tries to connect to an SSL service as a
client. I've tried a lot of things and nothing worked. If i add path
cacert thing as a parameter, then it always writes that it's invalid. I've
created a new keystore, but of course that is invalid too...
parameter must be non-empty
net.ssl.SSLException: java.lang.RuntimeException: Unexpected error:
java.security.InvalidAlgorithmParameterException: the trustAnchors
parameter must be non-empty" error on my ARM device with a linux and
openjdk when my application tries to connect to an SSL service as a
client. I've tried a lot of things and nothing worked. If i add path
cacert thing as a parameter, then it always writes that it's invalid. I've
created a new keystore, but of course that is invalid too...
Modify Node.js req object parameters
Modify Node.js req object parameters
So as usual, I tried to find this question on SO but still no luck.
I am aware that the answer is "Yes, you CAN modify the req object" but
nothing is said about the req object parameters.
For example the following code will throw an error:
app.get('/search', function(req, res) {
req.param('q') = "something";
});
Error:
ReferenceError: Invalid left-hand side in assignment
I imagine this has something to do with the property not having a 'SET'
method or something along those lines.
There are a few scenarios where this could come in handy.
A service that turns quick-links into full blown requests and proxies
those out.
Simply modifying the parameters before sending it off to another function
that you have no desire to modify.
Onto the question, Is there a way to modify the req object parameters?
So as usual, I tried to find this question on SO but still no luck.
I am aware that the answer is "Yes, you CAN modify the req object" but
nothing is said about the req object parameters.
For example the following code will throw an error:
app.get('/search', function(req, res) {
req.param('q') = "something";
});
Error:
ReferenceError: Invalid left-hand side in assignment
I imagine this has something to do with the property not having a 'SET'
method or something along those lines.
There are a few scenarios where this could come in handy.
A service that turns quick-links into full blown requests and proxies
those out.
Simply modifying the parameters before sending it off to another function
that you have no desire to modify.
Onto the question, Is there a way to modify the req object parameters?
Display multiple values present in a list in a view in mvc4 without using foreach loop
Display multiple values present in a list in a view in mvc4 without using
foreach loop
var technology = (from tech in context.TECHNOLOGies select new {
tech.NAME,tech.NOTES,tech.FDA_POC,tech.CATEGORY,tech.DESCRIPTION}).ToList();
return View(technology);
foreach loop
var technology = (from tech in context.TECHNOLOGies select new {
tech.NAME,tech.NOTES,tech.FDA_POC,tech.CATEGORY,tech.DESCRIPTION}).ToList();
return View(technology);
Friday, 13 September 2013
Android Dialog black out
Android Dialog black out
In my first Activity I show a dialog. While dialog is visible I show one
or two new activities. When I dismiss new activities and come back, the
dialog is still there, but not visible, it's controls work but there is
nothing on display, just a dim screen over underlying activity and all of
dialog is transparent (not rendered) This happens sometimes and AFAIK only
on gingerbread.
@CommonsWare
In my first Activity I show a dialog. While dialog is visible I show one
or two new activities. When I dismiss new activities and come back, the
dialog is still there, but not visible, it's controls work but there is
nothing on display, just a dim screen over underlying activity and all of
dialog is transparent (not rendered) This happens sometimes and AFAIK only
on gingerbread.
@CommonsWare
gen_bridge_metadata throwing error when processing headers
gen_bridge_metadata throwing error when processing headers
If I try running the command
`gen_bridge_metadata -F complete --no-64-bit -c '-DNDEBUG -I.' *.h -o
~/some/path/CocosDenshion.bridgesupport`
or any other command to generate bridgesupport files to process the
meta_data from some headers in a folder, I recieve this error:
/usr/bin/gen_bridge_metadata:60:in `basename': can't convert nil into
String (TypeError)
from /usr/bin/gen_bridge_metadata:60
I recieve this error regardless of the file, it could be something with
ruby... I dont know please help! Much appreciated!
If I try running the command
`gen_bridge_metadata -F complete --no-64-bit -c '-DNDEBUG -I.' *.h -o
~/some/path/CocosDenshion.bridgesupport`
or any other command to generate bridgesupport files to process the
meta_data from some headers in a folder, I recieve this error:
/usr/bin/gen_bridge_metadata:60:in `basename': can't convert nil into
String (TypeError)
from /usr/bin/gen_bridge_metadata:60
I recieve this error regardless of the file, it could be something with
ruby... I dont know please help! Much appreciated!
PseudoCode for Matrix Row Norm
PseudoCode for Matrix Row Norm
I tried doing an extensive research and could not come up with a pseudo
code or proper definition of how to calculate the row norm of a matrix.
I assume that this is the row norm of each separate row. How is one going
to find the row norm of the entire matrix?
Moreover how would I go about converting the above equation to pseudo-code.
Any of these questions answered, will be appreciated.
I tried doing an extensive research and could not come up with a pseudo
code or proper definition of how to calculate the row norm of a matrix.
I assume that this is the row norm of each separate row. How is one going
to find the row norm of the entire matrix?
Moreover how would I go about converting the above equation to pseudo-code.
Any of these questions answered, will be appreciated.
ObjC: Having my application launch a network volume upon launch
ObjC: Having my application launch a network volume upon launch
Just starting out with ObjC and Xcode.
I would like my application to connect/mount an AFP network volume upon
launch (the credentials are already saved to the keychain of the
computer). I realize that I need to place this code here:
(void)applicationDidFinishLaunching:(NSNotification *)aNotification {
XXX
}
Except Im not quite sure what needs to go here?!
I have learned that FSMountVolume is now deprecated, and it wants to see
NSURL, except Im not sure how to implement this - I'm so new that I am
having a hard time understanding how to read and implement the Xcode
documentation...
Does anyone know of a quick and dirty way to do this?
Thanks in advance for your time!
Dev
Just starting out with ObjC and Xcode.
I would like my application to connect/mount an AFP network volume upon
launch (the credentials are already saved to the keychain of the
computer). I realize that I need to place this code here:
(void)applicationDidFinishLaunching:(NSNotification *)aNotification {
XXX
}
Except Im not quite sure what needs to go here?!
I have learned that FSMountVolume is now deprecated, and it wants to see
NSURL, except Im not sure how to implement this - I'm so new that I am
having a hard time understanding how to read and implement the Xcode
documentation...
Does anyone know of a quick and dirty way to do this?
Thanks in advance for your time!
Dev
Python: How to remove items from a list that contains words found in items in another list
Python: How to remove items from a list that contains words found in items
in another list
I want to remove items from list 'a' where list 'b' contains items with
words found in list 'a'
a = ['one two three', 'four five six', 'seven eight nine']
b = ['two', 'five six']
The result should be:
a = ['seven eight nine']
This because the words 'two' and 'five six' are found in items in list 'a'.
This is how I have tried to solve it:
for i in a:
for x in b:
if x in i:
a.remove(i)
This returns:
print a
['four five six', 'seven eight nine']
Why does this not work, and how can I solve this problem?
Thanks.
in another list
I want to remove items from list 'a' where list 'b' contains items with
words found in list 'a'
a = ['one two three', 'four five six', 'seven eight nine']
b = ['two', 'five six']
The result should be:
a = ['seven eight nine']
This because the words 'two' and 'five six' are found in items in list 'a'.
This is how I have tried to solve it:
for i in a:
for x in b:
if x in i:
a.remove(i)
This returns:
print a
['four five six', 'seven eight nine']
Why does this not work, and how can I solve this problem?
Thanks.
Keylogger for linux using jna library
Keylogger for linux using jna library
All i need is an equivalent code for linux.Thanks in advance. I'm trying
to write this code for linux but unable to know how to do the similar for
linux.:
public class KeyHook {
private static volatile boolean quit;
private static HHOOK hhk;
private static LowLevelKeyboardProc keyboardHook;
public static void main(String[] args) {
final User32 lib = User32.INSTANCE;
HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
keyboardHook = new LowLevelKeyboardProc() {
public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT
info) {
if (nCode >= 0) {
switch(wParam.intValue()) {
case WinUser.WM_KEYUP:
case WinUser.WM_KEYDOWN:
case WinUser.WM_SYSKEYUP:
case WinUser.WM_SYSKEYDOWN:
System.err.println("in callback, key=" + info.vkCode);
if (info.vkCode == 81) {
quit = true;
}
}
}
return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
}
};
hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod,
0);
System.out.println("Keyboard hook installed, type anywhere, 'q' to
quit");
new Thread() {
public void run() {
while (!quit) {
try { Thread.sleep(10); } catch(Exception e) { }
}
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
}.start();
// This bit never returns from GetMessage
int result;
MSG msg = new MSG();
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
if (result == -1) {
System.err.println("error in get message");
break;
}
else {
System.err.println("got message");
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
lib.UnhookWindowsHookEx(hhk);
}
}
This code works fine in windows but i don't understand how to implement
similar code for linux.
All i need is an equivalent code for linux.Thanks in advance. I'm trying
to write this code for linux but unable to know how to do the similar for
linux.:
public class KeyHook {
private static volatile boolean quit;
private static HHOOK hhk;
private static LowLevelKeyboardProc keyboardHook;
public static void main(String[] args) {
final User32 lib = User32.INSTANCE;
HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
keyboardHook = new LowLevelKeyboardProc() {
public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT
info) {
if (nCode >= 0) {
switch(wParam.intValue()) {
case WinUser.WM_KEYUP:
case WinUser.WM_KEYDOWN:
case WinUser.WM_SYSKEYUP:
case WinUser.WM_SYSKEYDOWN:
System.err.println("in callback, key=" + info.vkCode);
if (info.vkCode == 81) {
quit = true;
}
}
}
return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
}
};
hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod,
0);
System.out.println("Keyboard hook installed, type anywhere, 'q' to
quit");
new Thread() {
public void run() {
while (!quit) {
try { Thread.sleep(10); } catch(Exception e) { }
}
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
}.start();
// This bit never returns from GetMessage
int result;
MSG msg = new MSG();
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
if (result == -1) {
System.err.println("error in get message");
break;
}
else {
System.err.println("got message");
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
lib.UnhookWindowsHookEx(hhk);
}
}
This code works fine in windows but i don't understand how to implement
similar code for linux.
Enable Controls within Panel which is disable in VB.Net
Enable Controls within Panel which is disable in VB.Net
I am developing windows application in VB.Net. Now in that, I have one
situation where there is a form. In that form , there is panel and in that
panel there are some controls. Now i want to disable panel but some
controls which is inside the panel needs to enable.
So is there any way to enable some controls within panel which is disable?
Give some idea how to do that?
Thanks in Advance.
I am developing windows application in VB.Net. Now in that, I have one
situation where there is a form. In that form , there is panel and in that
panel there are some controls. Now i want to disable panel but some
controls which is inside the panel needs to enable.
So is there any way to enable some controls within panel which is disable?
Give some idea how to do that?
Thanks in Advance.
Thursday, 12 September 2013
tilemaps in 2d games
tilemaps in 2d games
I have 160 'world tiles', each world tile has 25 region tiles, each region
tile is 100x100 grid 50px by 50px
what do i need to know to be able to make it such that:
1). Initial zoom is the region tile. (100x100) 2). When player 'explores'
onto another region tile, the 2nd region tile is added to the player view;
and the player is now able to zoom in and out to show all explored.. down
to initial region.
do I just create one large image and work with that?? I am confused and
been looking through a few java game programming books to find an answer
on how to approach this with no avail.
I have 160 'world tiles', each world tile has 25 region tiles, each region
tile is 100x100 grid 50px by 50px
what do i need to know to be able to make it such that:
1). Initial zoom is the region tile. (100x100) 2). When player 'explores'
onto another region tile, the 2nd region tile is added to the player view;
and the player is now able to zoom in and out to show all explored.. down
to initial region.
do I just create one large image and work with that?? I am confused and
been looking through a few java game programming books to find an answer
on how to approach this with no avail.
How to override android home button
How to override android home button
I have been searching through Android docs and stackoverflow and most of
the answers I am reading say that you cannot disable or override the
Android home button.
Tried - does not work
Says not possible
The problem is there are known apps that are doing this:
Kids Care
Kids Place
This is what I want:
A parent loads the app then gives device to a child. The child can only
see the approved apps that are on the device (I know how to do this part).
If they load an approved app from the main launcher screen on my app - if
they press the home button, it takes them back to my app and not back to
the device home screen. If a user presses the home button from my app -
nothing should happen. Same goes for the back button.
I am looking for the proper solution in duplicating functionality of Kids
Care app in overriding home button. How do I do it?
I have been searching through Android docs and stackoverflow and most of
the answers I am reading say that you cannot disable or override the
Android home button.
Tried - does not work
Says not possible
The problem is there are known apps that are doing this:
Kids Care
Kids Place
This is what I want:
A parent loads the app then gives device to a child. The child can only
see the approved apps that are on the device (I know how to do this part).
If they load an approved app from the main launcher screen on my app - if
they press the home button, it takes them back to my app and not back to
the device home screen. If a user presses the home button from my app -
nothing should happen. Same goes for the back button.
I am looking for the proper solution in duplicating functionality of Kids
Care app in overriding home button. How do I do it?
Sequel DB Connection PoolTimeout Error
Sequel DB Connection PoolTimeout Error
I have been unable to determine what the cause of the following
Sequel::PoolTimeout error is coming from in a Ruby script I have written:
Sequel::PoolTimeout: Sequel::PoolTimeout
hold at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/connection_pool/threaded.rb:100
hold at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/connection_pool/threaded.rb:93
synchronize at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/database/connecting.rb:234
execute at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/adapters/jdbc.rb:258
execute at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:793
fetch_rows at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/adapters/jdbc.rb:671
each at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:143
single_record at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:583
single_value at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:591
get at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:250
empty? at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:153
scrap at
/Users/username/projectname/processers/get_category.rb:46
each at org/jruby/RubyArray.java:1617
each_with_index at org/jruby/RubyEnumerable.java:920
scrap at
/Users/username/projectname/processers/get_category.rb:44
scrap at
/Users/username/projectname/processers/get_category.rb:32
I have tried this with both MRI and JRuby with exactly the same results.
As per the instructions on the Sequel gem here, I have attempted to raise
the pool_timeout limit as follows:
DB =
Sequel.connect("jdbc:mysql://localhost/project_db?user=USERNAME&password=PASSWD&max_connections=10&pool_timeout=120")
It seems as though the max_connections and pool_timeout may not be
recognized, however I'm not seeing any other way to pass these args on
into the connection.
The actual code that is in question here is: if DB[:products].where(url:
url.to_s).empty?
I have seen the code work just fine for a little bit, but without fail it
fails either right away or after a couple minutes without any
reproducibility in terms of when it occurs. I am starting to suspect that
this is a MySQL config issue or something causing the localhost DBMS to
have some prolonged delays, although, again, I cannot manually reproduce a
visible timeout that I can tell with manual queries, etc.
Any ideas on this issue as to why the timout would keep happening or, more
particularly, how to resolve it either via feeding Sequel proper settings
(perhaps I have a malformed arg list) or modifying MySQL's /etc/my.cnf for
such a scenario?
I have been unable to determine what the cause of the following
Sequel::PoolTimeout error is coming from in a Ruby script I have written:
Sequel::PoolTimeout: Sequel::PoolTimeout
hold at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/connection_pool/threaded.rb:100
hold at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/connection_pool/threaded.rb:93
synchronize at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/database/connecting.rb:234
execute at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/adapters/jdbc.rb:258
execute at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:793
fetch_rows at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/adapters/jdbc.rb:671
each at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:143
single_record at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:583
single_value at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:591
get at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:250
empty? at
/Users/username/.rvm/gems/jruby-1.7.4@all/gems/sequel-4.2.0/lib/sequel/dataset/actions.rb:153
scrap at
/Users/username/projectname/processers/get_category.rb:46
each at org/jruby/RubyArray.java:1617
each_with_index at org/jruby/RubyEnumerable.java:920
scrap at
/Users/username/projectname/processers/get_category.rb:44
scrap at
/Users/username/projectname/processers/get_category.rb:32
I have tried this with both MRI and JRuby with exactly the same results.
As per the instructions on the Sequel gem here, I have attempted to raise
the pool_timeout limit as follows:
DB =
Sequel.connect("jdbc:mysql://localhost/project_db?user=USERNAME&password=PASSWD&max_connections=10&pool_timeout=120")
It seems as though the max_connections and pool_timeout may not be
recognized, however I'm not seeing any other way to pass these args on
into the connection.
The actual code that is in question here is: if DB[:products].where(url:
url.to_s).empty?
I have seen the code work just fine for a little bit, but without fail it
fails either right away or after a couple minutes without any
reproducibility in terms of when it occurs. I am starting to suspect that
this is a MySQL config issue or something causing the localhost DBMS to
have some prolonged delays, although, again, I cannot manually reproduce a
visible timeout that I can tell with manual queries, etc.
Any ideas on this issue as to why the timout would keep happening or, more
particularly, how to resolve it either via feeding Sequel proper settings
(perhaps I have a malformed arg list) or modifying MySQL's /etc/my.cnf for
such a scenario?
Get second smallest number(s) in sql column
Get second smallest number(s) in sql column
I currently have the code below and it works for getting me the 2 smallest
number, but I want to get all of the 2nd smallest numbers and link them to
their name as opposed to just one of them. lets say the numbers in the
tables was made up of this:
Name| number
----|------
w 2
a 8
s 2
e 2
I would want to get
w 2
s 2
e 2
and now I am just getting w 2 select name, gunsize from ships order by
gunsize desc limit 1,1
I currently have the code below and it works for getting me the 2 smallest
number, but I want to get all of the 2nd smallest numbers and link them to
their name as opposed to just one of them. lets say the numbers in the
tables was made up of this:
Name| number
----|------
w 2
a 8
s 2
e 2
I would want to get
w 2
s 2
e 2
and now I am just getting w 2 select name, gunsize from ships order by
gunsize desc limit 1,1
How to access EGL Image directly from Android Surface for use in MediaCodec video decoder?
How to access EGL Image directly from Android Surface for use in
MediaCodec video decoder?
I'm currently writing an android app where I need to cache video-frames so
that I can easily go back and forth with little to no delay.
Right now I'm letting android decode the video frame by providing a
Surface to the Configure call of the MediaCodec object and calling
releaseOutputBuffer with the render flag set to 'true'.
The only way I found to access the decoded surface data (besides decoding
the returned bytebuffer whose format appears to be device-dependent) is to
call updateTeximage on the SurfaceTexture linked to the Surface, attaching
this to the GL_TEXTURE_EXTERNAL_OES target and rendering it to a
GL_TEXTURE2D target texture I created myself in order to cache it.
I would like to optimize this caching process and be able to decode the
frames on a different thread. Using my current method, this means that I
would have to create another EGL context for the video decoder, share the
context etc...
My question is:
Is it possible to access the EGL-image or native buffer data associated
with the Surface without calling updateTexImage? That way I could cache
the egl image (which does not require EGL context according to
EGL_ANDROID_image_native_buffer). This would also cache in YUV format
which would be much more storage-efficient than the raw RGB textures I'm
caching now.
I'm hoping that someone can point me in the right direction.
Thanks, Nico
MediaCodec video decoder?
I'm currently writing an android app where I need to cache video-frames so
that I can easily go back and forth with little to no delay.
Right now I'm letting android decode the video frame by providing a
Surface to the Configure call of the MediaCodec object and calling
releaseOutputBuffer with the render flag set to 'true'.
The only way I found to access the decoded surface data (besides decoding
the returned bytebuffer whose format appears to be device-dependent) is to
call updateTeximage on the SurfaceTexture linked to the Surface, attaching
this to the GL_TEXTURE_EXTERNAL_OES target and rendering it to a
GL_TEXTURE2D target texture I created myself in order to cache it.
I would like to optimize this caching process and be able to decode the
frames on a different thread. Using my current method, this means that I
would have to create another EGL context for the video decoder, share the
context etc...
My question is:
Is it possible to access the EGL-image or native buffer data associated
with the Surface without calling updateTexImage? That way I could cache
the egl image (which does not require EGL context according to
EGL_ANDROID_image_native_buffer). This would also cache in YUV format
which would be much more storage-efficient than the raw RGB textures I'm
caching now.
I'm hoping that someone can point me in the right direction.
Thanks, Nico
java json objects best practice
java json objects best practice
A web api responses with this JSON:
// GET /sales/products+dates?start_date=2010-11-24end_date=2010-11-31
{
"12345": {
"2010-11-24": {
"date": "2010-11-24",
"country": null,
"iso": null,
"product_id": 12345,
"downloads": 11,
"net_downloads": 11,
"updates": 0,
"revenue": "0.00",
"returns": 0,
"gift_redemptions": 0,
"promos": 0
},
...
},
"123456": {
"2010-11-24": {
"date": "2010-11-24",
"product_id": 123456,
"downloads": 28,
"net_downloads": 29,
"updates": 6,
"revenue": "19.02",
"returns": 1,
"gift_redemptions": 0,
"promos": 0
},
...
}
}
With GSON in Java I want to get objects, which represent this JSON. So I
define a class like:
public class SalesList{
private ArrayList<SaleData> mySales;
private class SaleData{
private int downloads;
private int net_downloads;
private int updates;
private int returns;
private int gifts;
private int gift_redemptions;
private int promos;
private float revenue;
private String date;
private String product_id;
private String iso;
private String country;
private String product;
However this seems not to be realy the way to go, is it? Since the
response is a JSON Object, not Array, I'm not sure how to map the product
IDs (first level in JSON response), which can be 0 - infinite and the
dates (second level). Is arrays the right way? Or is it totaly wrong
approach to JSON in Java?
A web api responses with this JSON:
// GET /sales/products+dates?start_date=2010-11-24end_date=2010-11-31
{
"12345": {
"2010-11-24": {
"date": "2010-11-24",
"country": null,
"iso": null,
"product_id": 12345,
"downloads": 11,
"net_downloads": 11,
"updates": 0,
"revenue": "0.00",
"returns": 0,
"gift_redemptions": 0,
"promos": 0
},
...
},
"123456": {
"2010-11-24": {
"date": "2010-11-24",
"product_id": 123456,
"downloads": 28,
"net_downloads": 29,
"updates": 6,
"revenue": "19.02",
"returns": 1,
"gift_redemptions": 0,
"promos": 0
},
...
}
}
With GSON in Java I want to get objects, which represent this JSON. So I
define a class like:
public class SalesList{
private ArrayList<SaleData> mySales;
private class SaleData{
private int downloads;
private int net_downloads;
private int updates;
private int returns;
private int gifts;
private int gift_redemptions;
private int promos;
private float revenue;
private String date;
private String product_id;
private String iso;
private String country;
private String product;
However this seems not to be realy the way to go, is it? Since the
response is a JSON Object, not Array, I'm not sure how to map the product
IDs (first level in JSON response), which can be 0 - infinite and the
dates (second level). Is arrays the right way? Or is it totaly wrong
approach to JSON in Java?
Wednesday, 11 September 2013
In a grid change the Selected Item Model properties but it should not reflect back in the grid unless user saves it
In a grid change the Selected Item Model properties but it should not
reflect back in the grid unless user saves it
I am working on a wpf application, where most of the screens consist of a
details grid and a form where the selected item of the grid is displayed.
In this details form the user can update the individual properties of the
selected item.
This is a MVVM application and in my view model i have exposed two
properties one is observable collection of the model which acts as item
source for the grid. and there is a Selected Item Model which binds to the
selected item of the grid.
Now my problem is when user changes any property of the selected item in
the details forms, it automatically reflects back to the grid, i have
tried changing modes of binding but nothing works.
I just want to make sure the selected item changes but it should not be
reflected back to grid unless user saves these changes.
reflect back in the grid unless user saves it
I am working on a wpf application, where most of the screens consist of a
details grid and a form where the selected item of the grid is displayed.
In this details form the user can update the individual properties of the
selected item.
This is a MVVM application and in my view model i have exposed two
properties one is observable collection of the model which acts as item
source for the grid. and there is a Selected Item Model which binds to the
selected item of the grid.
Now my problem is when user changes any property of the selected item in
the details forms, it automatically reflects back to the grid, i have
tried changing modes of binding but nothing works.
I just want to make sure the selected item changes but it should not be
reflected back to grid unless user saves these changes.
Android: Rotate Dialog X degrees
Android: Rotate Dialog X degrees
How can I rotate a dialog fragment 90 (actually, the number will vary)
degrees in android? My app has the screen locked to portrait orientation,
but when the dialog pops up, I want it rotated some number of degrees.
Here is how I am currently creating the dialog:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose an option")
.setItems(R.array.options_array, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position of the
selected item
switch (which) {
case 0: //copy 1
mListener.onDialogClickCopy(CardDialog.this);
break;
case 1: //copy ...
mListener.onDialogClickCopyX(CardDialog.this);
break;
case 2: //edit text ...
mListener.onDialogClickEdit(CardDialog.this);
break;
case 3: //edit p/t ...
mListener.onDialogClickEditPT(CardDialog.this);
break;
default:
break;
}
}
});
return builder.create();
}
I have tried using .setView with a layout rotated 90 degrees, but that
doesn't help. I want to avoid using a custom view for the dialog so I can
easily use .setItems.
How can I rotate a dialog fragment 90 (actually, the number will vary)
degrees in android? My app has the screen locked to portrait orientation,
but when the dialog pops up, I want it rotated some number of degrees.
Here is how I am currently creating the dialog:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose an option")
.setItems(R.array.options_array, new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position of the
selected item
switch (which) {
case 0: //copy 1
mListener.onDialogClickCopy(CardDialog.this);
break;
case 1: //copy ...
mListener.onDialogClickCopyX(CardDialog.this);
break;
case 2: //edit text ...
mListener.onDialogClickEdit(CardDialog.this);
break;
case 3: //edit p/t ...
mListener.onDialogClickEditPT(CardDialog.this);
break;
default:
break;
}
}
});
return builder.create();
}
I have tried using .setView with a layout rotated 90 degrees, but that
doesn't help. I want to avoid using a custom view for the dialog so I can
easily use .setItems.
Set the variables instead of having the user input them
Set the variables instead of having the user input them
I would like to change the code to have origin and destination be
populated from set variables, instead of from an html form. Any ideas? I
think this is fairly easy. Any advice is very much appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Draggable elevation</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var recalcHeight = function() {
$("#map").height($(window).height() - $("form").height() -
$("#elevation").height());
map && google.maps.event.trigger(map, 'resize');
};
$(window).resize(recalcHeight);
recalcHeight();
for (o in google.maps.DirectionsTravelMode) {
$("#mode").append(new Option(o));
}
var map = new google.maps.Map($('#map')[0], {
center: new google.maps.LatLng(-33.86685, 151.19348),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 10
});
var dr = new google.maps.DirectionsRenderer({
map: map,
draggable: true,
preserveViewport: true
});
var hoverMarker = new google.maps.Marker({
map: map
});
$("#elevation").mouseleave(function() {
hoverMarker.setVisible(false);
$("#elevation-hover").hide();
});
var es = new google.maps.ElevationService();
var ds = new google.maps.DirectionsService();
var fitBounds = false;
google.maps.event.addListener(dr, 'directions_changed', function() {
var route = dr.getDirections().routes[0];
var path = route.overview_path;
es.getElevationAlongPath({
path: path,
samples: Math.max(50, path.length * 2)
}, function(result, status) {
if (status == google.maps.ElevationStatus.OK) {
drawElevation(result);
recalcHeight();
if (fitBounds) {
map.fitBounds(route.bounds);
fitBounds = false;
}
}
else {
$('#error').text(status).show();
}
recalcHeight();
});
});
$('#directions-form').submit(function(e) {
$('#error').hide();
ds.route({
origin: $('#from').val(),
destination: $('#to').val(),
travelMode: $('#mode').val()
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
fitBounds = true;
dr.setDirections(result);
}
else {
$('#error').text(status).show();
}
recalcHeight();
});
e.preventDefault();
return false;
});
var drawElevation = function(r) {
var max = writeStats(r);
drawGraph(r, max);
};
var writeStats = function(r) {
var prevElevation = r[0].elevation;
var climb = 0;
var drop = 0;
var max = 0;
for (var i = 1; i < r.length; i++) {
var diff = r[i].elevation - prevElevation;
prevElevation = r[i].elevation;
if (diff > 0) {
climb += diff;
}
else {
drop -= diff;
}
if (r[i].elevation > max) {
max = r[i].elevation;
}
}
max = Math.ceil(max);
$('#climb-drop').text("Climb: " + Math.round(climb) + "m Drop: " +
Math.round(drop) + "m");
return max;
};
var drawGraph = function(r, max) {
var ec = $("#elevation-chart").empty()
var width = Math.max(1, Math.floor(Math.min(11, ec.width() /
r.length)) - 1);
var height = 100;
$.each(r, function(i, e) {
var barHeight = Math.round(e.elevation / max * height);
var bar = $("<div style='width:" + width + "px'><div
style='height:" + barHeight + "px;'></div></div>");
ec.append(bar);
bar.mouseenter(function() {
var offset = bar.find("div").offset();
offset.top -= 25;
offset.left -= 3;
hoverMarker.setVisible(true);
hoverMarker.setPosition(e.location);
$("#elevation-hover").show().text(Math.round(e.elevation) +
'm').offset(offset);
if (!map.getBounds().contains(e.location)) {
map.panTo(e.location);
}
}).click(function() {
map.panTo(e.location);
});
});
};
$(".share").click(function() {
$(this).find("input").focus().select();
});
});
</script>
<link rel="stylesheet" href="styles.css" type="text/css" media="screen"
charset="utf-8">
</head>
<body>
<form action="#" method="get" accept-charset="utf-8" id="directions-form">
<input id="from" name="from" value="Bondi Beach, Sydney Australia">
<input id="to" name="to" value="48 Pirrama Rd, Sydney Australia">
<select name="mode" id="mode"></select>
<input type="submit" value="Elevate →">
<span class="share">Share this page: <input type="text" readonly
value="http://goo.gl/v2UB"></span>
<div id="error"></div>
</form>
<div id="map"></div>
<div id="elevation">
<div id="elevation-hover"></div>
<div id="climb-drop"></div>
<div id="elevation-chart"></div>
</div>
</body>
</html>
I would like to change the code to have origin and destination be
populated from set variables, instead of from an html form. Any ideas? I
think this is fairly easy. Any advice is very much appreciated.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Draggable elevation</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var recalcHeight = function() {
$("#map").height($(window).height() - $("form").height() -
$("#elevation").height());
map && google.maps.event.trigger(map, 'resize');
};
$(window).resize(recalcHeight);
recalcHeight();
for (o in google.maps.DirectionsTravelMode) {
$("#mode").append(new Option(o));
}
var map = new google.maps.Map($('#map')[0], {
center: new google.maps.LatLng(-33.86685, 151.19348),
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 10
});
var dr = new google.maps.DirectionsRenderer({
map: map,
draggable: true,
preserveViewport: true
});
var hoverMarker = new google.maps.Marker({
map: map
});
$("#elevation").mouseleave(function() {
hoverMarker.setVisible(false);
$("#elevation-hover").hide();
});
var es = new google.maps.ElevationService();
var ds = new google.maps.DirectionsService();
var fitBounds = false;
google.maps.event.addListener(dr, 'directions_changed', function() {
var route = dr.getDirections().routes[0];
var path = route.overview_path;
es.getElevationAlongPath({
path: path,
samples: Math.max(50, path.length * 2)
}, function(result, status) {
if (status == google.maps.ElevationStatus.OK) {
drawElevation(result);
recalcHeight();
if (fitBounds) {
map.fitBounds(route.bounds);
fitBounds = false;
}
}
else {
$('#error').text(status).show();
}
recalcHeight();
});
});
$('#directions-form').submit(function(e) {
$('#error').hide();
ds.route({
origin: $('#from').val(),
destination: $('#to').val(),
travelMode: $('#mode').val()
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
fitBounds = true;
dr.setDirections(result);
}
else {
$('#error').text(status).show();
}
recalcHeight();
});
e.preventDefault();
return false;
});
var drawElevation = function(r) {
var max = writeStats(r);
drawGraph(r, max);
};
var writeStats = function(r) {
var prevElevation = r[0].elevation;
var climb = 0;
var drop = 0;
var max = 0;
for (var i = 1; i < r.length; i++) {
var diff = r[i].elevation - prevElevation;
prevElevation = r[i].elevation;
if (diff > 0) {
climb += diff;
}
else {
drop -= diff;
}
if (r[i].elevation > max) {
max = r[i].elevation;
}
}
max = Math.ceil(max);
$('#climb-drop').text("Climb: " + Math.round(climb) + "m Drop: " +
Math.round(drop) + "m");
return max;
};
var drawGraph = function(r, max) {
var ec = $("#elevation-chart").empty()
var width = Math.max(1, Math.floor(Math.min(11, ec.width() /
r.length)) - 1);
var height = 100;
$.each(r, function(i, e) {
var barHeight = Math.round(e.elevation / max * height);
var bar = $("<div style='width:" + width + "px'><div
style='height:" + barHeight + "px;'></div></div>");
ec.append(bar);
bar.mouseenter(function() {
var offset = bar.find("div").offset();
offset.top -= 25;
offset.left -= 3;
hoverMarker.setVisible(true);
hoverMarker.setPosition(e.location);
$("#elevation-hover").show().text(Math.round(e.elevation) +
'm').offset(offset);
if (!map.getBounds().contains(e.location)) {
map.panTo(e.location);
}
}).click(function() {
map.panTo(e.location);
});
});
};
$(".share").click(function() {
$(this).find("input").focus().select();
});
});
</script>
<link rel="stylesheet" href="styles.css" type="text/css" media="screen"
charset="utf-8">
</head>
<body>
<form action="#" method="get" accept-charset="utf-8" id="directions-form">
<input id="from" name="from" value="Bondi Beach, Sydney Australia">
<input id="to" name="to" value="48 Pirrama Rd, Sydney Australia">
<select name="mode" id="mode"></select>
<input type="submit" value="Elevate →">
<span class="share">Share this page: <input type="text" readonly
value="http://goo.gl/v2UB"></span>
<div id="error"></div>
</form>
<div id="map"></div>
<div id="elevation">
<div id="elevation-hover"></div>
<div id="climb-drop"></div>
<div id="elevation-chart"></div>
</div>
</body>
</html>
Any idea on how can this exercise can be solved ? don't know if it should be used synchronized methods or so, thanks
Any idea on how can this exercise can be solved ? don't know if it should
be used synchronized methods or so, thanks
/**
* Java programming exercise Add to class Counter the methods stop, resume,
* restart and finish, making respectively the counting towards up to stop,
* resume where it stopped, return to 0 (stopped or not) and finish
* definitively. Observation: Do not use methods like interrupt, suspend,
* resume, stop, etc., inherited from class Thread.
**/
class Counter extends Thread {
private int n = 0;
private boolean running = true;
private boolean active = true;
private static int number;
public void run() {
while (running) {
if (active)
System.out.println(n++);
}
}
}
be used synchronized methods or so, thanks
/**
* Java programming exercise Add to class Counter the methods stop, resume,
* restart and finish, making respectively the counting towards up to stop,
* resume where it stopped, return to 0 (stopped or not) and finish
* definitively. Observation: Do not use methods like interrupt, suspend,
* resume, stop, etc., inherited from class Thread.
**/
class Counter extends Thread {
private int n = 0;
private boolean running = true;
private boolean active = true;
private static int number;
public void run() {
while (running) {
if (active)
System.out.println(n++);
}
}
}
Spring 3 Hibernate 4 and Jsf Integration not working
Spring 3 Hibernate 4 and Jsf Integration not working
I am trying of integration spring 3.2 hibernate 4.1 and jsf 2.1, but when
i run application and i do click in search does not go into the service
layer and dao. This's my code
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"
xmlns:cache="http://www.springframework.org/schema/cache">
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan
base-package="com.example" />
<context:property-placeholder
location="classpath:application.properties"/>
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/example"/>
<property name="lookupOnStartup" value="false"/>
<property name="cache" value="true" />
<property name="proxyInterface" value="javax.sql.DataSource" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:packagesToScan="com.example.entity">
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">${jdbc.hibernate.dialect}
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop
key="hibernate.cache.use_second_level_cache">true</prop>
<prop
key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop
key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop>
<prop
key="hibernate.cache.provider_configuration_file_resource_path">classpath:ehcache.xml</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
</beans>
entity Chart
public class Chart {
private String status;
private int count;
public Chart() {
}
public Chart(String status, int count) {
this.status = status;
this.count = count;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
interface dao
public interface IChartDAO {
List<Chart> getData();
}
implements dao
@Repository("chartDAOImpl")
public class ChartDAOImpl implements IChartDAO, Serializable {
@Autowired
SessionFactory sessionFactory;
Session session;
@Override
public List<Chart> getData() {
List<Chart> dataList = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createSQLQuery("query")
.addScalar("status").addScalar("count")
.setResultTransformer(Transformers.aliasToBean(Chart.class));
dataList = query.list();
session.getTransaction().commit();
} catch (Exception e) {
System.out.println(e.getMessage());
session.getTransaction().rollback();
}
finally
{
session.close();
}
return dataList;
}
interface service
public interface IChartService {
List<ChartPie> getData();
}
implements service
@Service("chartServiceImpl")
@Transactional(readOnly=true)
public class ChartServiceImpl implements IChartService, Serializable {
@Autowired
IChartDAO chartDao;
List<Chart> dataList;
@Transactional(propagation= Propagation.REQUIRED, readOnly=true)
@Override
public List<Chart> getData() {
try {
dataList = chartDao.getData();
} catch (Exception e) {
System.out.println("fallo service: "+e.getMessage());
}
return dataList;
}
my bo
public class ChartBO implements Serializable {
@Autowired
IChartService chartService;
List<ChartPie> dataList;
public List<Chart> getData() {
try {
dataList = chartService.getData();
} catch (Exception e) {
}
return dataList;
}
jsf bean
@ManagedBean(name = "beanChart")
@ViewScoped
public class ChartBean implements Serializable {
private PieChartModel data;
ChartBO chartBo;
public PieChartModel getData() {
return data;
}
public ChartBean() {
chartBo = new ChartBO();
data = new PieChartModel();
buildData();
}
public void buildData() {
try {
List<Chart> dataList = chartBo.getData();
for (Chart cq : dataList) {
data.set(cq.getStatus(), cq.getCount());
}
} catch (Exception e) {
System.out.println("Fallo en bean: "+e.getMessage());
}
}
I am trying of integration spring 3.2 hibernate 4.1 and jsf 2.1, but when
i run application and i do click in search does not go into the service
layer and dao. This's my code
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-
class>
</listener>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache-3.1.xsd"
xmlns:cache="http://www.springframework.org/schema/cache">
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:component-scan
base-package="com.example" />
<context:property-placeholder
location="classpath:application.properties"/>
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/example"/>
<property name="lookupOnStartup" value="false"/>
<property name="cache" value="true" />
<property name="proxyInterface" value="javax.sql.DataSource" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:packagesToScan="com.example.entity">
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">${jdbc.hibernate.dialect}
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop
key="hibernate.cache.use_second_level_cache">true</prop>
<prop
key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop
key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</prop>
<prop
key="hibernate.cache.provider_configuration_file_resource_path">classpath:ehcache.xml</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
</beans>
entity Chart
public class Chart {
private String status;
private int count;
public Chart() {
}
public Chart(String status, int count) {
this.status = status;
this.count = count;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
interface dao
public interface IChartDAO {
List<Chart> getData();
}
implements dao
@Repository("chartDAOImpl")
public class ChartDAOImpl implements IChartDAO, Serializable {
@Autowired
SessionFactory sessionFactory;
Session session;
@Override
public List<Chart> getData() {
List<Chart> dataList = null;
try {
session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.createSQLQuery("query")
.addScalar("status").addScalar("count")
.setResultTransformer(Transformers.aliasToBean(Chart.class));
dataList = query.list();
session.getTransaction().commit();
} catch (Exception e) {
System.out.println(e.getMessage());
session.getTransaction().rollback();
}
finally
{
session.close();
}
return dataList;
}
interface service
public interface IChartService {
List<ChartPie> getData();
}
implements service
@Service("chartServiceImpl")
@Transactional(readOnly=true)
public class ChartServiceImpl implements IChartService, Serializable {
@Autowired
IChartDAO chartDao;
List<Chart> dataList;
@Transactional(propagation= Propagation.REQUIRED, readOnly=true)
@Override
public List<Chart> getData() {
try {
dataList = chartDao.getData();
} catch (Exception e) {
System.out.println("fallo service: "+e.getMessage());
}
return dataList;
}
my bo
public class ChartBO implements Serializable {
@Autowired
IChartService chartService;
List<ChartPie> dataList;
public List<Chart> getData() {
try {
dataList = chartService.getData();
} catch (Exception e) {
}
return dataList;
}
jsf bean
@ManagedBean(name = "beanChart")
@ViewScoped
public class ChartBean implements Serializable {
private PieChartModel data;
ChartBO chartBo;
public PieChartModel getData() {
return data;
}
public ChartBean() {
chartBo = new ChartBO();
data = new PieChartModel();
buildData();
}
public void buildData() {
try {
List<Chart> dataList = chartBo.getData();
for (Chart cq : dataList) {
data.set(cq.getStatus(), cq.getCount());
}
} catch (Exception e) {
System.out.println("Fallo en bean: "+e.getMessage());
}
}
XPath regex for file extension
XPath regex for file extension
<root>
<url>
<str>http://test.com/test.csv</str>
<str>http://example.org/rsgis.html</str>
<str>http://something.edu/thro.zip</str>
</url>
</root>
Using Xpath can I find ONLY the file extensions (csv or html or zip) for
the url's. Any help is greatly appreciated..
Thanks in advance.
<root>
<url>
<str>http://test.com/test.csv</str>
<str>http://example.org/rsgis.html</str>
<str>http://something.edu/thro.zip</str>
</url>
</root>
Using Xpath can I find ONLY the file extensions (csv or html or zip) for
the url's. Any help is greatly appreciated..
Thanks in advance.
JavaScript that must be placed outside a function
JavaScript that must be placed outside a function
I am writing a JS merger application, which would consider two similar js
files, (maintained by different developers) namely oldfile and newfile and
merges the changes from newfile to oldfile while keeping additional
content that is solely present in oldfile.
JavaScript found to be so dynamic that it is almost impossible to identify
the matching content between oldfile and newfile. The only area that works
for me is the named functions. So I am going to wrap all the JS file
contents into named functions before delivering to the developers to
maintain. When it comes back for merge, I will match the function names to
find what to replace and what to keep intact.
The areas I workout are:
Move the anonymous functions found in jQuery into named functions and call
them in jQuery
Name any anonymous function like var v = function()...
Wrap all jQueries into named self executable functions
Wrap any other pieces of code that is not inside the functions into self
executable functions while keeping the order intact.
The global variables are moved to top of the JS file. They are verified by
their names.
I am wondering if there is any other crucial content than variables that
must be placed outside the function.
The merging process works as follows:
Capture all strings (single quote, double quote), comments (inline, block)
and replace with some unique identifiers
Capture the function body (based on the count of '{' and '}') and replace
with unique identifier.
Compare and replace the captured function bodies with latest version content.
Restore all captures to generate the final output.
This is working for the files in hand. Is there a plausible cases that
would fail in this approach?
I am writing a JS merger application, which would consider two similar js
files, (maintained by different developers) namely oldfile and newfile and
merges the changes from newfile to oldfile while keeping additional
content that is solely present in oldfile.
JavaScript found to be so dynamic that it is almost impossible to identify
the matching content between oldfile and newfile. The only area that works
for me is the named functions. So I am going to wrap all the JS file
contents into named functions before delivering to the developers to
maintain. When it comes back for merge, I will match the function names to
find what to replace and what to keep intact.
The areas I workout are:
Move the anonymous functions found in jQuery into named functions and call
them in jQuery
Name any anonymous function like var v = function()...
Wrap all jQueries into named self executable functions
Wrap any other pieces of code that is not inside the functions into self
executable functions while keeping the order intact.
The global variables are moved to top of the JS file. They are verified by
their names.
I am wondering if there is any other crucial content than variables that
must be placed outside the function.
The merging process works as follows:
Capture all strings (single quote, double quote), comments (inline, block)
and replace with some unique identifiers
Capture the function body (based on the count of '{' and '}') and replace
with unique identifier.
Compare and replace the captured function bodies with latest version content.
Restore all captures to generate the final output.
This is working for the files in hand. Is there a plausible cases that
would fail in this approach?
How to prevent DbSet Results view return all rows in debug
How to prevent DbSet Results view return all rows in debug
When a developer click on the results view in debug, it will return all
rows of the table. How to prevent because it may be a very large table?
Thanks Wilson
When a developer click on the results view in debug, it will return all
rows of the table. How to prevent because it may be a very large table?
Thanks Wilson
Subscribe to:
Posts (Atom)