instruction
stringlengths 0
30k
⌀ |
---|
How do I make a menu in python that does not require the user to press (enter) to make a selection? |
|python| |
I've got a menu in python. That part was easy. I'm using raw_input() to get the selection from the user.
The problem is that raw_input (and input) require the user to press Enter after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:
import sys
print """Menu
1) Say Foo
2) Say Bar"""
answer = raw_input("Make a selection> ")
if "1" in answer: print "foo"
elif "2" in answer: print "bar"
It would be great to have something like
print menu
while lastKey = "":
lastKey = check_for_recent_keystrokes()
if "1" in lastKey: #do stuff... |
I've got a menu in python. That part was easy. I'm using raw_input() to get the selection from the user.
The problem is that raw_input (and input) require the user to press Enter after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:
import sys
print """Menu
1) Say Foo
2) Say Bar"""
answer = raw_input("Make a selection> ")
if "1" in answer: print "foo"
elif "2" in answer: print "bar"
It would be great to have something like
print menu
while lastKey = "":
lastKey = check_for_recent_keystrokes()
if "1" in lastKey: #do stuff...
Edit: Problem 50% solved. Now to get it working on Windows... |
I've got a menu in python. That part was easy. I'm using raw_input() to get the selection from the user.
The problem is that raw_input (and input) require the user to press Enter after they make a selection. Is there any way to make the program act immediately upon a keystroke? Here's what I've got so far:
import sys
print """Menu
1) Say Foo
2) Say Bar"""
answer = raw_input("Make a selection> ")
if "1" in answer: print "foo"
elif "2" in answer: print "bar"
It would be great to have something like
print menu
while lastKey = "":
lastKey = check_for_recent_keystrokes()
if "1" in lastKey: #do stuff... |
Dang -- lbrandy beat me to the punch, but that doesn't mean I can't provide you with the system results for Vista!
>>> import os
>>> print os.name
nt
>>> import platform
>>> platform.system()
'Windows'
>>> platform.release()
'Vista' |
> Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer.
Can you do some rudimentary string function to force JavaScript into changing it into a string? Like
value = value + "" |
System.Windows.Forms.Cursor.Position |
**C# 3.5**
Without notifyicon, you will need to terminate this application in task manager
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
static void Main()
{
Timer timer = new Timer();
// timer.Interval = 4 minutes
timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 / TimeSpan.TicksPerMillisecond);
timer.Tick += (sender, args) => { System.Windows.Forms.Cursor.Position = new System.Drawing.Point(System.Windows.Forms.Cursor.Position.X + 1, System.Windows.Forms.Cursor.Position.Y + 1); };
timer.Start();
Application.Run();
}
}
} |
**for C# 3.5**
without notifyicon therefore you will need to terminate this application in task manager manually
using System;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Timer timer = new Timer();
// timer.Interval = 4 minutes
timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 / TimeSpan.TicksPerMillisecond);
timer.Tick += (sender, args) => { System.Windows.Forms.Cursor.Position = new System.Drawing.Point(System.Windows.Forms.Cursor.Position.X + 1, System.Windows.Forms.Cursor.Position.Y + 1); };
timer.Start();
Application.Run();
}
} |
**for C# 3.5**
without notifyicon therefore you will need to terminate this application in task manager manually
using System;
using System.Drawing;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Timer timer = new Timer();
// timer.Interval = 4 minutes
timer.Interval = (int)(TimeSpan.TicksPerMinute * 4 / TimeSpan.TicksPerMillisecond);
timer.Tick += (sender, args) => { Cursor.Position = new Point(Cursor.Position.X + 1, Cursor.Position.Y + 1); };
timer.Start();
Application.Run();
}
} |
Thanks all, for the record here's the results on Mac:
<pre>
>>> import os
>>> os.name
'posix'
>>> import platform
>>> platform.system()
'Darwin'
>>> platform.release()
'8.11.1'
</pre> |
Try putting the extra text inside the server-side script block and concatenating.
onclick='<%# "ToggleDisplay(""" & DataBinder.Eval(Container.DataItem, "JobCode") & """);" %>'
Edit: I'm pretty sure you could just use double quotes outside the script block as well. |
The reason msvcrt fails in IDLE is because IDLE is not accessing the library that runs msvcrt. Whereas when you run the program natively in cmd.exe it works nicely. For the same reason that your program blows up on Mac and Linux terminals.
But I guess if you're going to be using this specifically for windows, more power to ya. |
Wow, that took forever. Ok, here's what I've ended up with
#!C:\python25\python.exe
import msvcrt
print """Menu
1) Say Foo
2) Say Bar"""
while 1:
char = msvcrt.getch()
if char == chr(27): #escape
break
if char == "1":
print "foo"
break
if char == "2":
print "Bar"
break
I fails hard using IDLE, the python...thing...that comes with python. But once I tried it in DOS (er, CMD.exe), as a real program, then it ran fine.
No one try it in IDLE, unless you have Task Manager handy.
I've already forgotten how I lived with menus that arn't super-instant responsive. |
Wow, that took forever. Ok, here's what I've ended up with
#!C:\python25\python.exe
import msvcrt
print """Menu
1) Say Foo
2) Say Bar"""
while 1:
char = msvcrt.getch()
if char == chr(27): #escape
break
if char == "1":
print "foo"
break
if char == "2":
print "Bar"
break
It fails hard using IDLE, the python...thing...that comes with python. But once I tried it in DOS (er, CMD.exe), as a real program, then it ran fine.
No one try it in IDLE, unless you have Task Manager handy.
I've already forgotten how I lived with menus that arn't super-instant responsive. |
I create folders named after the build versions and put upgrade and downgrade scripts in there. For example, you could have the following folders: 1.0.0, 1.0.1 and 1.0.2. Each one contains the script that allows you to upgrade or downgrade your database between versions.
Should a client or customer call you with a problem with version 1.0.1 and you are using 1.0.2, bringing the database back to his version will not be a problem.
In your database, create a table called "schema" where you put in the current version of the database. Then writing a program that can upgrade or downgrade your database for you is easy.
Just like Joey said, if you are in a Rails world, use Migrations. :) |
I had recently similar problem and the only way to solve it was to use plain old HTML codes for single (`"`) and double quotes (`'`) to escape it 3-times.
Source code was total mess but it worked. |
I had recently similar problem and the only way to solve it was to use plain old HTML codes for single (`"`) and double quotes (`'`).
Source code was total mess of course but it worked.
I don't know if I correctly understand your example, but try
<a id="aShowHide" onclick='ToggleDisplay("<%# DataBinder.Eval(Container.DataItem, "JobCode") %>");'>Show/Hide</a>
or
<a id="aShowHide" onclick='ToggleDisplay('<%# DataBinder.Eval(Container.DataItem, "JobCode") %>');'>Show/Hide</a> |
I had recently similar problem and the only way to solve it was to use plain old HTML codes for single (`"`) and double quotes (`'`).
Source code was total mess of course but it worked.
Try
<a id="aShowHide" onclick='ToggleDisplay("<%# DataBinder.Eval(Container.DataItem, "JobCode") %>");'>Show/Hide</a>
or
<a id="aShowHide" onclick='ToggleDisplay('<%# DataBinder.Eval(Container.DataItem, "JobCode") %>');'>Show/Hide</a> |
CSV File Imports in .Net |
|c#|vb.net|file|csv|import| |
I realize this is a newbie question, but I'm looking for a simple solution - it seems like there should be one.
What's the best way to import a CSV file into a strongly-typed data structure? Again simple = better.
Thanks. |
Triple Quotes? How do I delimit a databound Javascript string parameter in ASP.NET? |
|asp.net|javascript|anchor|display|single|quotes| |
How do I delimit a Javascript databound string parameter in an anchor OnClick event?
I have an anchor tag in an ASP.NET Repeater control.
The OnClick event of the anchor contains a call to a Javascript function.
The Javascript funciton takes a string for it's input parameter.
The string parameter is populated with a databound value from the Repeater.
I need the 'double quotes' for the Container.DataItem.
I need the 'single quotes' for the OnClick.
And I still need *one more delimiter* (triple quotes?) for the input string parameter of the Javascript function call.
Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer?
Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer.
Cheers in advance for any knowledge you can drop.
The anchor:
<a id="aShowHide" onclick='ToggleDisplay(<%# DataBinder.Eval(Container.DataItem, "JobCode") %>);' >Show/Hide</a>
and
here is the Javascript:
<script language="JavaScript" type="text/javascript">
/* Shows/Hides the Jobs Div */
function ToggleDisplay(jobCode)
{
/* Each div has it's ID set dynamically ('d' plus the JobCode) */
var elem = document.getElementById('d' + jobCode);
if (elem)
{
if (elem.style.display != 'block')
{
elem.style.display = 'block';
elem.style.visibility = 'visible';
}
else
{
elem.style.display = 'none';
elem.style.visibility = 'hidden';
}
}
}
</script> |
|asp.net|javascript|anchor|quotes| |
|asp.net|javascript|quotes|anchor| |
How do I delimit a Javascript databound string parameter in an anchor OnClick event?
- I have an anchor tag in an ASP.NET Repeater control.
- The OnClick event of the anchor contains a call to a Javascript function.
- The Javascript funciton takes a string for it's input parameter.
- The string parameter is populated with a databound value from the Repeater.
I need the 'double quotes' for the Container.DataItem.
I need the 'single quotes' for the OnClick.
And I still need *one more delimiter* (triple quotes?) for the input string parameter of the Javascript function call.
Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer?
Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer.
Cheers in advance for any knowledge you can drop.
The anchor:
<a id="aShowHide" onclick='ToggleDisplay(<%# DataBinder.Eval(Container.DataItem, "JobCode") %>);' >Show/Hide</a>
and
here is the Javascript:
<script language="JavaScript" type="text/javascript">
/* Shows/Hides the Jobs Div */
function ToggleDisplay(jobCode)
{
/* Each div has it's ID set dynamically ('d' plus the JobCode) */
var elem = document.getElementById('d' + jobCode);
if (elem)
{
if (elem.style.display != 'block')
{
elem.style.display = 'block';
elem.style.visibility = 'visible';
}
else
{
elem.style.display = 'none';
elem.style.visibility = 'hidden';
}
}
}
</script> |
How do I delimit a Javascript databound string parameter in an anchor OnClick event?
- I have an anchor tag in an ASP.NET Repeater control.
- The OnClick event of the anchor contains a call to a Javascript function.
- The Javascript funciton takes a string for it's input parameter.
- The string parameter is populated with a databound value from the Repeater.
I need the 'double quotes' for the Container.DataItem.
I need the 'single quotes' for the OnClick.
And I still need *one more delimiter* (triple quotes?) for the input string parameter of the Javascript function call.
Since I can't use 'single quotes' again, how do I ensure the Javascript function knows the input parameter is a string and not an integer?
Without the extra quotes around the input string parameter, the Javascript function thinks I'm passing in an integer.
Cheers in advance for any knowledge you can drop.
The anchor:
<a id="aShowHide" onclick='ToggleDisplay(<%# DataBinder.Eval(Container.DataItem, "JobCode") %>);' >Show/Hide</a>
and here is the Javascript:
<script language="JavaScript" type="text/javascript">
/* Shows/Hides the Jobs Div */
function ToggleDisplay(jobCode)
{
/* Each div has it's ID set dynamically ('d' plus the JobCode) */
var elem = document.getElementById('d' + jobCode);
if (elem)
{
if (elem.style.display != 'block')
{
elem.style.display = 'block';
elem.style.visibility = 'visible';
}
else
{
elem.style.display = 'none';
elem.style.visibility = 'hidden';
}
}
}
</script> |
Extending on what [Mike Powell][1] has to say, I am actually a big fan of almost all of the podcasts at [http://www.twit.tv][2]. Most of the content is watered down a bit, but some of the speakers are top notch thinkers - especially on "This Week in Tech", the flagship program.
Oh - and Car Talk on NPR but those guys hardly EVER get into the SDLC!
[1]: http://stackoverflow.com/users/205/mike-powell
[2]: http://www.twit.tv |
Chris' probably has the best pure answer to the question: http://stackoverflow.com/questions/1104/#1109
However, I'm curious about the root of the question. If the user should *always* wrap the call in a try/catch block, should the user-called function really be throwing exceptions in the first place?
This is a difficult question to answer without more context regarding the code-base in question. Shooting from the hip, I think the best answer here is to wrap the function up such that the recommended (if not only, depending on the overall exception style of the code) public interface does the try/catch *for* the user. If you're just trying to ensure that there are no unhandled exceptions in your code, unit tests and code review are probably the best solution. |
You are going to get a lot of strings, that's for sure...
![\sum_{i=x}^y{\frac{r!}{{(r-i)}!}}][1]
Where, x and y is how you define them and r is the number of characters we are selecting from --if I am understanding you correctly. You should definitely generate these as needed and not get sloppy and say, generate a powerset and then filter the length of strings.
The following definitely isn't the best way to generate these, but it's an interesting aside, none-the-less.
Knuth (volume 4, fascicle 2, 7.2.1.3) tells us that (s,t)-combination is equivalent to s+1 things taken t at a time with repetition -- an (s,t)-combination is notation used by Knuth that is equal to ![{t \choose {s+t}][2]. We can figure this out by first generating each (s,t)-combination in binary form (so, of length (s+t)) and counting the number of 0's to the left of each 1.
10001000011101 --> becomes the permutation: {0, 3, 4, 4, 4, 1}
[1]: http://www.codecogs.com/eq.latex?\sum_{i=x}^y%20{%20\frac{r!}{{(r-i)}!}%20}
[2]: http://www.codecogs.com/eq.latex?{t%20\choose%20{s+t}}
[3]: http://beta.stackoverflow.com/questions/561/using-combinations-of-sets-as-test-data |
If you can guarantee that there are no commas in the data, then the simplest way would probably be to use [String.split][1].
For example:
String[] values = myString.Split(',');
myObject.StringField = values[0];
myObject.IntField = Int32.Parse(values[1]);
There may be libraries you could use to help, but that's probably as simple as you can get. Just make sure you can't have commas in the data, otherwise you will need to parse it better.
[1]: http://msdn.microsoft.com/en-us/library/system.string.split(VS.71).aspx |
A good simple way to do it is to open the file, and read each line into an array, linked list, data-structure-of-your-choice. Be careful about handling the first line though.
This may be over your head, but there seems to be a direct way to access them as well using a [connection string][1].
Why not try using python instead of c# or vb? It has a nice CSV module to import that does all the heavy lifting for you.
[1]: http://weblogs.asp.net/fmarguerie/archive/2003/10/01/29964.aspx |
A good simple way to do it is to open the file, and read each line into an array, linked list, data-structure-of-your-choice. Be careful about handling the first line though.
This may be over your head, but there seems to be a direct way to access them as well using a [connection string][1].
Why not try using python instead of c# or vb? It has a nice CSV module to import that does all the heavy lifting for you.
EDIT: @NotMyself - just because we commented poorly on your trolling question, please don't vote down our answers. sasb and i appreciate it.
[1]: http://weblogs.asp.net/fmarguerie/archive/2003/10/01/29964.aspx |
I listen to the [javaposse][1] regularly, they cover mostly Java, but not solely.
[1]: http://javaposse.com |
Two articles on CodeProject that provide code for a solution, one that [uses SteamReader][1] and one that [imports CSV data][2] using the [Microsoft Text Driver][3].
[1]: http://www.codeproject.com/KB/database/CsvReader.aspx
[2]: http://www.codeproject.com/KB/database/FinalCSVReader.aspx
[3]: http://support.microsoft.com/kb/187670 |
the problem is that the sphere can be distorted a number of ways, and having all those points known on the equator, lets say, wont help you map points further away.
You need better 'close' points, then you can assume these three points are on a plane with the fourth and do the interpolation. Without knowing the distortion, it's computationally hard to discover it. |
the problem is that the sphere can be distorted a number of ways, and having all those points known on the equator, lets say, wont help you map points further away.
You need better 'close' points, then you can assume these three points are on a plane with the fourth and do the interpolation --knowing that the distance of longitudes is a function, not a constant. |
I'm not clear on whether or not you're wanting to add the asynchronous bits to the server in C# or the client in C++.
If you're talking about doing this in C++, desktop Windows platforms can do socket I/O asynchronously through the API's that use overlapped I/O. For sockets, WSASend, WSARecv both allow async I/O (read the documentation on their LPOVERLAPPED parameters, which you can populate with events that get set when the I/O completes).
I don't know if Windows Mobile platforms support these functions, so you might have to do some additional digging. |
Ummm. Maybe I am missing something about the question here, but if you have long/lat info, you also have the direction of north?
It seems you need to map Cartesian coordinates to a geodesic coordinates system. For example wgs84 is oblated spheroid if I remember correctly.
The maths involved is non-trivial, but the code comes out a only a few lines. If I had more time I'd post more but I need a shower so I will be boring and link to the [wikipedia][1] entry which is pretty good.
[1]: http://en.wikipedia.org/wiki/Geographic_coordinate_system |
Ummm. Maybe I am missing something about the question here, but if you have long/lat info, you also have the direction of north?
It seems you need to map geodesic coordinates to a projected coordinates system. For example osgb to wgs84.
The maths involved is non-trivial, but the code comes out a only a few lines. If I had more time I'd post more but I need a shower so I will be boring and link to the [wikipedia][1] entry which is pretty good.
Note: Post shower edited.
[1]: http://en.wikipedia.org/wiki/Geographic_coordinate_system |
Use SVN Revision to label build in CCNET |
|cruisecontrol.net|svn|msbuild| |
I am using CCNET on a sample project with SVN as my source control. CCNET is configured to create a build on every check in. CCNET uses MSBuild to build the source code.
I would like to use the latest revision number to generate AssemblyInfo.cs while compiling.
How can I retrieve the latest revision from subversion and use the value in CCNET? |
|svn|msbuild|cruisecontrol.net| |
I am using CCNET on a sample project with SVN as my source control. CCNET is configured to create a build on every check in. CCNET uses MSBuild to build the source code.
I would like to use the latest revision number to generate AssemblyInfo.cs while compiling.
How can I retrieve the latest revision from subversion and use the value in CCNET?
Edit: I'm not using NAnt - only MSBuild. |
Here is some sample code. I think this is what you are looking for. The following displays exactly the same in Firefox 3 (mac) and IE7.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
#absdiv {
position: absolute;
left: 100px;
top: 100px;
width: 80%;
height: 60%;
background: #999;
}
#pctchild {
width: 60%;
height: 40%;
background: #CCC;
}
#reldiv {
position: relative;
left: 20px;
top: 20px;
height: 25px;
width: 40%;
background: red;
}
</style>
</head>
<body>
<div id="absdiv">
<div id="reldiv">
</div>
<div id="pctchild">
</div>
</div>
</body>
</html> |
recognizing text inside an image is indeed a hot topic for researchers in that field, but only begun to grow out of control when [captcha's][1] became the "norm" in terms of defense against spam bots. Why use captcha's as protection? well because it is/was very hard to locate (and read) text inside an image!
The reason why I mention captcha's is because the most advancement* is made within that tiny area, and I think that your solution could be best found there.
especially because captcha's are indeed about locating text (or something that resembles text) inside a cluttered image and afterwards trying to read the letters correctly.
so if you can find yourself [a good open source captcha breaking tool][2] you probably have all you need to continue your quest...
You could probably even throw away the most dificult code that handles the character recognition itself, because those OCR's are used to read distorted text, something you don't have to do.
*: advancement in terms of visible, usable, and **practical** information for a "non-researcher"
[1]: http://en.wikipedia.org/wiki/Captcha
[2]: http://libcaca.zoy.org/wiki/PWNtcha |
How many DataContexts are appropriate? |
|.net|asp.net|datacontext|database|linq-to-sql|visual-studio| |
Are Multiple DataContext classes ever appropriate? |
|.net|asp.net|visual-studio|database|linq-to-sql|datacontext| |
In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create [DataContext][1] [classes][2] (which is usually done using the designer in VS 2008). From the UI perspective, the DataContext is a design of the sections of your database that you would like to expose to through LinqToSql and is integral in setting up the ORM features of LinqToSql.
My question is: I am setting up a project that uses a large database where all tables are interconnected in some way through Foreign Keys. My first inclination is to make one huge DataContext class that models the entire datbase. That way I could in theory (though I don't know if this would be needed in practice) use the Foreign Key connections that are generated through LinqToSql to easily go between related objects in my code, insert related objects, etc.
However, after giving it some thought, I am now thinking that it may make more sense to create multiple DataContext classes, each one relating to a specific namespace or logical interrelated section within my database. My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources. Additionally, it is easier to create and manage smaller DataContext files than one big one. The thing that I would lose is that there would be some distant sections of the database that would not be navigable through LinqToSql (even though a chain of relationships connects them in the actual database). Additionally, there would be some table classes that would exist in more than one DataContext.
Any thoughts or experience on whether multiple DataContexts (corresponding to DB namespaces) are appropriate in place of (or in addition to) one very large DataContext class (corresponding to the whole DB)?
[1]: http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx
[2]: http://dotnetslackers.com/articles/csharp/InsideTheLINQToSQLDataContextClass.aspx |
In order to fully use LinqToSql in an ASP.net 3.5 application, it is necessary to create [DataContext][1] [classes][2] (which is usually done using the designer in VS 2008). From the UI perspective, the DataContext is a design of the sections of your database that you would like to expose to through LinqToSql and is integral in setting up the ORM features of LinqToSql.
My question is: I am setting up a project that uses a large database where all tables are interconnected in some way through Foreign Keys. My first inclination is to make one huge DataContext class that models the entire database. That way I could in theory (though I don't know if this would be needed in practice) use the Foreign Key connections that are generated through LinqToSql to easily go between related objects in my code, insert related objects, etc.
However, after giving it some thought, I am now thinking that it may make more sense to create multiple DataContext classes, each one relating to a specific namespace or logical interrelated section within my database. My main concern is that instantiating and disposing one huge DataContext class all the time for individual operations that relate to specific areas of the Database would be impose an unnecessary imposition on application resources. Additionally, it is easier to create and manage smaller DataContext files than one big one. The thing that I would lose is that there would be some distant sections of the database that would not be navigable through LinqToSql (even though a chain of relationships connects them in the actual database). Additionally, there would be some table classes that would exist in more than one DataContext.
Any thoughts or experience on whether multiple DataContexts (corresponding to DB namespaces) are appropriate in place of (or in addition to) one very large DataContext class (corresponding to the whole DB)?
[1]: http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx
[2]: http://dotnetslackers.com/articles/csharp/InsideTheLINQToSQLDataContextClass.aspx |
CPU throttling in C++ |
|c++|cpu|throttling| |
I was just wandering if there is an elegant way to set the maximum CPU load for a particular thread doing intensive calculations. Right now I have located the most time consuming loop in the thread (it does only compression) and use GetTickCount() and Sleep() with hardcoded values. It makes sure that the loop continues for a certain period of time and than sleeps for a certain minimal time. It more or less does the job i.e. guarantees that the thread will not use more than 50% of CPU. However behavior is dependent on the number of CPU cores (huge disadvantage) and simply ugly (smaller disadvantage :)). Any ideas? |
I can't think of any cross platform way of what you want (or any guaranteed way full stop) but as you are using GetTickCount perhaps you aren't interested in cross platform :)
I'd use interprocess communications and set the intensive processes nice levels to get what you require but I'm not sure that's appropriate for your situation.
EDIT:
I agree with [Bernard][1] which is why I think a process rather than a thread might be more appropriate but it just might not suit your purposes.
[1]: http://stackoverflow.com/questions/1982/#1984 |
The list [] is dynamic and flexible but that flexibility comes at a speed cost.
The tupel () is fixed (immutable) and therefore faster. |
The [list][1] [1,2,3] is dynamic and flexible but that flexibility comes at a speed cost.
The [tuple][2] (1,2,3) is fixed (immutable) and therefore faster.
EDIT:
fixed spelling and added links to diveintopython.org
[1]: http://diveintopython.org/native_data_types/lists.html
[2]: http://diveintopython.org/native_data_types/tuples.html |
If you want lisp to look like Ruby use Ruby.
It's possible to use Ruby (and Python) in a very lisp like way which is one of the main reasons they have gained acceptance so quickly. |
@sparkes
Sometimes LISP is the clear language choice, namely Emacs extensions. I'm sure I could use Ruby to extend Emacs if I wanted to, but Emacs was designed to be extended with LISP, so it seems to make sense to use it in that situation. |
databinding in C# - any solution to the "illegal cross thread call" ? |
|c#|data-binding| |
<p>when you data bind in C#, the thread that changes the data causes the control to change too. but if this thread is not the one on which the control was created, youll get the above exceptions. </p>
<p>surfed the net - no good answer. </p>
<p>anyone ?</p> |
Most Efficient Way to Test Object Type |
|c#|.net|double|int| |
I have values stored as strings in a DataTable where each value could really represent an int, double, or string (they were all converted to strings during an import process from an external data source). I need to test and see what type each value really is.
What is more efficient for the application (or is there no practical difference)?
1. Try to convert to int (and then double). If conversion works, the return true. If an exception is thrown, return false.
2. Regular expressions designed to match the pattern of an int or double
3. Some other method? |
<p>would use double.TryParse , has performance benefits.</p> |
As I don't have a test case to go from I can't guarantee this solution, but it seems to me that a scenario similar to the one used to update progress bars in different threads (use a delegate) would be suitable here.
public delegate void DataBindDelegate();
public DataBindDelegate BindData = new DataBindDelegate(DoDataBind);
public void DoDataBind()
{
DataBind();
}
If the data binding needs to be done by a particular thread, then let that thread do the work! |
You should be able to do something like:
if (control.InvokeRequired)
{
control.Invoke(delegateWithMyCode);
}
else
{
delegateWithMyCode();
}
InvokeRequired is a property on Controls to see if you are on the correct thread, then Invoke will invoke the delegate on the correct thread. |
You should be able to do something like:
if (control.InvokeRequired)
{
control.Invoke(delegateWithMyCode);
}
else
{
delegateWithMyCode();
}
InvokeRequired is a property on Controls to see if you are on the correct thread, then Invoke will invoke the delegate on the correct thread.
UPDATE: Actually, at my last job we did something like this:
private void SomeEventHandler(Object someParam)
{
if (this.InvokeRequired)
{
this.Invoke(new SomeEventHandlerDelegate(SomeEventHandler), someParam);
}
// Regular handling code
}
which removes the need for the else block and kind of tightens up the code. |
I'd personally use int.tryparse, then double.tryparse. Performance on those methods is quite fast. They both return a Boolean. If both fail then you have a string, per how you defined your data. |
On linux, you can change the scheduling priority of a thread with nice(). |
I would say, don't worry so much about such micro performance. It is much better to just get something to work, and then make it as clear and concise and easy to read as possible. The worst thing you can do is sacrifice readability for an insignificant amount of performance.
In the end, the best way to deal with performance issues is to save them for when you have data that indicates there is an actual performance problem... otherwise you will spend a lot of time micro-optimizing and actually cause higher maintenance costs for later on.
If you find this parsing situation is really the bottleneck in your application, THEN is the time to try and figure out what the fastest way to solve the problem is. I think Jeff (and many others) have blogged about this sort of thing a lot. |
If the thread call is "illegal" (i.e. the DataBind call affects controls that were not created in the thread it is being called from) then you need to create a delegate so that even if the decision / preparation for the DataBind is not done in the control-creating thread, any resultant modification of them (i.e. DataBind()) will be.
You would call my code from the worker thread like so:
this.BindData.Invoke();
This would then cause the original thread to do the binding, which (presuming it is the thread that created the controls) should work. |
This is more or less the perfect use case for [SVK][1]. SVK is a command line front end for subversion that works with an entire local copy of the repository. So your commits, updates, etc. work on the local repository and you can then sync with a master. I would generally recommend SVK over plain subversion anyway as it makes a lot of things nicer. No .svn folders, better branching and merging, better conflict resolution.
[1]: http://http://svk.bestpractical.com/view/HomePage |
One way of deciding whether or not to use nested classes is to think whether or not this class plays a supporting role or it's own part.
If it exists solely for the purpose of helping another class then I generally make it a nested class. There are a whole load of caveats to that, some of which seem contradictory but it all comes down to experience and gut-feeling. |
sounds like a case where you could use the [strategy pattern][1]
[1]: http://en.wikipedia.org/wiki/Strategy_pattern |
Also make sure you don't miss the [dnrTV webcast show][1] that Carl Franklin (the man behind .NET rocks) publishes. Even if it's a not a podcast and requires a more attention while watching it it's really informative and if you're into .NET and Microsoft related techniques you'll learn a lot.
[1]: http://www.dnrtv.com/default.aspx |
Here is my own contribution for the [Java programming language][1].
first some code:
public void swap(int x, int y)
{
int tmp = x;
x = y;
y = tmp;
}
calling this method will result in this:
int pi = 3;
int everything = 42;
swap(pi, everything);
System.out.println("pi: " + pi);
System.out.println("everything: " + everything);
"Output:
pi: 3
everything: 42"
even using 'real' objects will show a similar result:
public class MyObj {
private String msg;
private int number;
//getters and setters
public String getMsg() {
return this.msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getNumber() {
return this.number;
}
public void setNumber(int number) {
this.number = number;
}
//constructor
public MyObj(String msg, int number) {
setMsg(msg);
setNumber(number);
}
}
public static void swap(MyObj x, MyObj y)
{
MyObj tmp = x;
x = y;
y = tmp;
}
public static void main(String args[]) {
MyObj x = new MyObj("Hello world", 1);
MyObj y = new MyObj("Goodbye Cruel World", -1);
swap(x, y);
System.out.println(x.getMsg() + " -- "+ x.getNumber());
System.out.println(y.getMsg() + " -- "+ y.getNumber());
}
"Output:
Hello world -- 1
Goodbye Cruel World -- -1"
thus it is clear that Java passes its parameters **by value**, as the value for *pi* and *everything* and the *MyObj objects* aren't swapped.
be aware that "by value" is the *only way* in java to pass parameters to a method. (for example a language like c++ allows the developer to pass a parameter by reference using '**&**' after the parameter's type)
now the **tricky part**, or at least the part that will confuse most of the new java developers: (borrowed from [javaworld][2])
Original author: Tony Sintes
public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
"Output
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0"
*tricky* successfully changes the value of pnt1!
This would imply that Objects are passed by reference, this is not the case!
A correct statement would be: **the *Object references* are passed by value.**
more from Tony Sintes:
> The method successfully alters the
> value of pnt1, even though it is
> passed by value; however, a swap of
> pnt1 and pnt2 fails! This is the major
> source of confusion. In the main()
> method, pnt1 and pnt2 are nothing more
> than object references. When you pass
> pnt1 and pnt2 to the tricky() method,
> Java passes the references by value
> just like any other parameter. This
> means the references passed to the
> method are actually copies of the
> original references. Figure 1 below
> shows two references pointing to the
> same object after Java passes an
> object to a method.
![figure 1][3]
**Conclusion** or a long story short:
- Java passes it parameters **by value**
- *"by value"* is the **only way** in java to pass a parameter to a method
- using *methods from the object* given as parameter **will alter** the object as the references point to the original objects. (if that method itself alters some values)
useful links:
- [http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html][2]
- [http://www.ibm.com/developerworks/java/library/j-passbyval/][4]
- [http://www.ibm.com/developerworks/library/j-praxis/pr1.html][5]
- [http://javadude.com/articles/passbyvalue.htm][6]
[1]: http://en.wikipedia.org/wiki/Java_(programming_language)
[2]: http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
[3]: http://www.javaworld.com/javaworld/javaqa/2000-05/images/03-qa-0512-pass2b.gif
[4]: http://www.ibm.com/developerworks/java/library/j-passbyval/
[5]: http://www.ibm.com/developerworks/library/j-praxis/pr1.html
[6]: http://javadude.com/articles/passbyvalue.htm |
**by value**
- is slower than by reference since the system has to copy the parameter
- used for input only
**by reference**
- faster since only a pointer is passed
- used for input **and** output
- can be very dangerous if used in conjunction with global variables |
I am pretty sure this is one of the things due to change in python 3.0 with perhaps bin() to go with hex() and oct().
At the moment AFAIK eval('01010101101') does what you'd expect it to.
EDIT:
checked eval appears to work correctly :) |
I am pretty sure this is one of the things due to change in python 3.0 with perhaps bin() to go with hex() and oct().
At the moment AFAIK eval('01010101101') does what you'd expect it to.
EDIT:
checked eval appears to work correctly :)
EDITED AGAIN:
it does work, as long as you start with a magic '0' try it yourself. |
I am pretty sure this is one of the things due to change in python 3.0 with perhaps bin() to go with hex() and oct().
At the moment AFAIK eval('01010101101') does what you'd expect it to.
EDIT:
not working :)
lbrandy's answer is correct in all cases. |
I am pretty sure this is one of the things due to change in python 3.0 with perhaps bin() to go with hex() and oct().
EDIT:
lbrandy's answer is correct in all cases. |
Subversion makes it easy (some think too easy) to create a new branch using the svn copy command.
$ svn copy svn+ssh://host.example.com/repos/project/trunk \
svn+ssh://host.example.com/repos/project/branch \
-m "Creating a branch of project" |
I think you're looking for GetModuleFileName.
[http://www.swissdelphicenter.ch/torry/showcode.php?id=143][1]:
{
If you are working on a DLL and are interested in the filename of the
DLL rather than the filename of the application, then you can use this function:
}
function GetModuleName: string;
var
szFileName: array[0..MAX_PATH] of Char;
begin
FillChar(szFileName, SizeOf(szFileName), #0);
GetModuleFileName(hInstance, szFileName, MAX_PATH);
Result := szFileName;
end;
Also, look at [http://delphi.newswhat.com/geoxml/forumhistorythread?groupname=borland.public.delphi.internet.isapi-webbroker&messageid=3fbe1256@newsgroups.borland.com][2] which contains pretty much the same code but some additional information that may or may not be useful.
Untested though, been some time since I worked with Delphi :)
[1]: http://www.swissdelphicenter.ch/torry/showcode.php?id=143
[2]: http://delphi.newswhat.com/geoxml/forumhistorythread?groupname=borland.public.delphi.internet.isapi-webbroker&messageid=3fbe1256@newsgroups.borland.com |
This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on [AOP in .NET][1]. The general idea is that you'd extract the cross-functional concern (i.e. Retry for x hours) into a separate class and then you'd annotate any methods that need to modify their behaviour in that way. Here's how it might look (with a nice extension method on Int32)
[RetryFor( 10.Hours() )]
public void DeleteArchive()
{
//.. code to just delete the archive
}
[1]: http://blogs.msdn.com/simonince/archive/2008/06/24/aspect-oriented-interception.aspx |
Monitor a specific RSS |
|rss| |
For all the RSS feeds I subscribe to I use [Google Reader][1] which I love. I do however have a couple of specific RSS feeds that I'd like to be notified as soon as when they get updated (say for example a RSS feed for a forum I like to monitor and respond to as quick as possible).
Are there any tools out there for this kind of monitoring and that has some kind of alert functionality (a prompt window for example)?
I've tried [Simbolic RSS Alert][2] but I found it a bit buggy and couldn't get it to alert my as often as I liked.
Suggestions? Different experience of Simbolic?
[1]: http://www.google.com/reader/
[2]: http://www.simbolic.net/software/RSSAlert/ |
You do the unit testing by mocking out the database connection. This way, you can build scenarios where specific queries in the flow of a method call succeed or fail. I usually build my mock expectations so that the actual query text is ignored, because I really want to test the fault tolerance of the method and how it handles itself -- the specifics of the SQL are irrelevant to that end.
Obviously this means your test won't actually verify that the method *works*, because the SQL may be wrong. This is where integration tests kick in. For that, I expect someone else will have a more thorough answer, as I'm just beginning to get to grips with those myself. |
In my experience with LINQ to SQL and LINQ to Entities a DataContext is synonymous to a connection to the database. So if you were to use multiple data stores you would need to use multiple DataContexts. My gut reaction is you wouldn't notice to much of a slow down with a DataContext that encompasses a large number of tables. If you did however you could always split the database logically at points where you can isolate tables that don't have any relationship to other sets of tables and create multiple contexts. |
Don't forget there is also **pass by name**, and **pass by value-result**.
Pass by value-result is similar to pass by value, with the added aspect that the value is set in the original variable that was passed as the parameter. It can, to some extent, avoid interference with global variables. It is apparently better in partitioned memory, where a pass by reference could cause a page fault ([Reference][1]).
Pass by name means that the values are only calculated when they are actually used, rather than at the start of the procedure. Algol used pass-by-name, but an interesting side effect is that is it very difficult to write a swap procedure ([Reference][2]). Also, the expression passed by name is re-evaluated each time it is accessed, which can also have side effects.
[1]: http://logos.cs.uic.edu/476/notes/PassByRefOrValResult.html
[2]: http://www.cs.sfu.ca/~cameron/Teaching/383/PassByName.html |
The solution is to use the TempData property to store the desired Request components.
For instance:
public ActionResult Send()
{
TempData["form"] = Request.Form;
return this.RedirectToAction(a => a.Form());
}
Then in your "Form" action you can go:
public ActionResult Form()
{
... /* Declare viewData etc. */
if (TempData["form"] != null)
{
viewData.Form.SetValues((System.Collections.Specialized.NameValueCollection)TempData["form"]);
viewData.Form.Validate();
}
return View("Form", viewData);
} |
The solution is to use the TempData property to store the desired Request components.
For instance:
public ActionResult Send()
{
TempData["form"] = Request.Form;
return this.RedirectToAction(a => a.Form());
}
Then in your "Form" action you can go:
public ActionResult Form()
{
/* Declare viewData etc. */
if (TempData["form"] != null)
{
/* Cast TempData["form"] to
System.Collections.Specialized.NameValueCollection
and use it */
}
return View("Form", viewData);
} |
The solution is to use the TempData property to store the desired Request components.
For instance:
public ActionResult Send()
{
TempData["form"] = Request.Form;
return this.RedirectToAction(a => a.Form());
}
Then in your "Form" action you can go:
public ActionResult Form()
{
/* Declare viewData etc. */
if (TempData["form"] != null)
{
/* Cast TempData["form"] to
System.Collections.Specialized.NameValueCollection
and use it */
}
return View("Form", viewData);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.