Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a custom control that I made. It inherits from `System.Windows.Forms.Control`, and has several new properties that I have added. Is it possible to show my properties (TextOn and TextOff for example) instead of the default "Text" property.
My control works fine, I'd just like to de-clutter the property window. | You could either override them (if they can be overriden) and apply the [`Browsable`](http://msdn.microsoft.com/en-us/library/system.componentmodel.browsableattribute.aspx) attribute, specifying `false`, or create a new version of the property and apply the same attribute (this second approach doesn't always appear to work so YMMV).
Also, you can use a custom [`TypeConverter`](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx) for your type and override the [`GetProperties`](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.getproperties.aspx) method to control what properties get displayed for your type. This approach is more robust to the underlying base classes changing but can take more effort, depending on what you want to achieve.
I often use a combination of the [`Browsable`](http://msdn.microsoft.com/en-us/library/system.componentmodel.browsableattribute.aspx) attribute and a custom [`TypeConverter`](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx). | Override the property and add `[Browsable(false)]`.
You might also want to add `[EditorBrowsable(EditorBrowsableState.Never)]`, which will hide the property in IntelliSense in the code editor. Note that it will only be hidden in a separate solution from the original control. | How do I hide some of the default control properties at design-time (C#)? | [
"",
"c#",
".net",
"winforms",
"user-controls",
""
] |
I have a self-referential MySQL table with a recursive parent\_id:
```
CREATE TABLE `recursive` (
`id` int(11) NOT NULL auto_increment,
`parent_id` int(11) default NULL,
`name` varchar(100) NOT NULL,
PRIMARY KEY (`id`),
KEY `data_categorysource_parent_id` (`parent_id`),
CONSTRAINT `parent_id_refs_id_627b4293`
FOREIGN KEY (`parent_id`) REFERENCES `data_categorysource` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
```
During testing, I want to empty it but TRUNCATE fails:
```
TRUNCATE `recursive`
/* SQL Error: Cannot delete or update a parent row: a foreign key
constraint fails...
```
I currently have to manually delete all records, starting at the bottom of the tree working upwards. This gets onerous even with small trees.
Is there an easy way around this? I can't `DROP` the table and re-create it easily as other tables reference it (I have already truncated those so there should be no data integrity issues there). | Why not:
```
UPDATE 'recursive' SET 'parent_id' = NULL WHERE 'parent_id' IS NOT NULL;
DELETE FROM 'recursive';
```
? | If you just want to empty the whole thing for testing purposes use:
```
SET FOREIGN_KEY_CHECKS = 0;
// Execute Query
SET FOREIGN_KEY_CHECKS = 1;
```
This totally bypasses any foreign key checks. | What is the best way to empty a self-referential MySQL table? | [
"",
"sql",
"mysql",
"truncate",
"self-reference",
""
] |
In simulation of a lan-messenger in c# I am using the loopback address just for starters to check the functionality of the code.However after sending a few messages, I am getting a socket exception while using the end-connect method and then a socket exception while sending the data. Is there any reason behind this exception.
```
private void button1_Click(object sender, EventArgs e)
{
HideCaret(this.textBox1.Handle);
StringBuilder sb = new StringBuilder(this.textBox1.Text);
str = this.textBox2.Text;
Socket newsock = new Socket(AddressFamily.InterNetwork,socketType.Stream, ProtocolType.Tcp);
IPEndPoint ip = new IPEndPoint(localaddress, 5555);
newsock.BeginConnect(ip, new AsyncCallback(connected), newsock);
if (str != "")
{
sb.AppendLine(this.textBox2.Text);
this.textBox1.Text = sb.ToString();
this.textBox2.Text = "\0";
send = Encoding.ASCII.GetBytes(str);
try
{
newsock.BeginSend(send, 0, send.Length, SocketFlags.None, new AsyncCallback(sent), newsock);
}
catch (ArgumentException)
{
MessageBox.Show("arguments incorrect in begin-send call", "Error", MessageBoxButtons.OK);
}
catch (SocketException)
{
MessageBox.Show("error in accessing socket while sending", "Error", MessageBoxButtons.OK);
}
catch (ObjectDisposedException)
{
MessageBox.Show("socket closed while sending", "Error", MessageBoxButtons.OK);
}
catch (Exception)
{
MessageBox.Show("error while sending", "Error", MessageBoxButtons.OK);
}
}
}
```
Please help | It's possibly because you're not waiting for the socket to be connected before sending data. You have two options:
1. Send the data asynchronously from your `connected` callback method.
2. Send the data synchronously by blocking this thread until connected.
You accomplish #1 by combining the data to send and the socket into a new class, then passing that as `state` in your call to [`BeginConnect`](http://msdn.microsoft.com/en-us/library/tad07yt6.aspx). Then move your send code to the callback method.
You accomplish #2 by setting up a [`System.Threading.ManualResetEvent`](http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx) and calling [`WaitOne`](http://msdn.microsoft.com/en-us/library/58195swd.aspx) after [`BeginConnect`](http://msdn.microsoft.com/en-us/library/tad07yt6.aspx). Then call [`EndConnect`](http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.endconnect.aspx) in your `connected` callback method, followed by a [`Set`](http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle.set.aspx) on your [`ManualResetEvent`](http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx). Then proceed to send as you have above.
---
You'll also probably learn more if you find out what kind of `SocketException` you're getting.
From the MSDN Documentation:
> If you receive a `SocketException`,
> use the `SocketException.ErrorCode`
> property to obtain the specific error
> code. After you have obtained this
> code, refer to the Windows Sockets
> version 2 API error code documentation
> in the MSDN library for a detailed
> description of the error. | Do you have a separate thread reading from the socket? If not, your socket buffers are probably filling up. | Socket Programming | [
"",
"c#",
".net",
"sockets",
""
] |
I have followed the Accepted Answer's instructions from [this post](https://stackoverflow.com/questions/92100/is-it-possible-to-set-code-behind-a-resource-dictionary-in-wpf-for-event-handli) as regards creating a code behind file for a Resource Dictionary, and it worked...so now I can attach events to controls in the generic.xml file.
But now I want to be able to call the `DragMove()` method from an event in there and since there aren't any references to the window hosting the dictionary at the time, I don't know how to call this `DragMove()` method.
So, from a Resource Dictionary Code behind file, is there any way I can make a reference to the window that will currently be hosting that Resource Dictionary?
---
**[Update] (Temporary Solution)**
As a simple (yet stupid) workaround, I have currently done the following:
Since I can reference the `Application.Current.MainWindow` from the `Generic.xaml.cs` code-behind, I now have this in the `Generic.xaml.cs`:
```
private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Application.Current.MainWindow.DragMove();
}
```
And then I'm attaching `PreviewMouseLeftButtonDown` handler to each `Window` I have, like such:
```
private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Application.Current.MainWindow = this;
}
```
It, well, it works...and until someone can come up with the proper way on how to do this, It should serve me well enough. | There is no way I know of doing this. However, if you're trying to determine the `Window` given a specific resource, you could use a `RelativeSource`:
```
<SolidColorBrush x:Key="MyBrush" Color="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Converter={StaticResource WindowToColorConverter}"/>
```
And if you're doing it from code, you can use [Window.GetWindow()](http://msdn.microsoft.com/en-us/library/system.windows.window.getwindow.aspx). You just need a `DependencyObject` hosted in that `Window`. | From architectural point of view I would say you are about to break the paradigm. It might be a bad decision providing Resource Dictionary with notion of UI that consumes it and giving some logic other than providing resources.
You might want some Adapter between UI and resource dictionary, or Controller if this is really needed to wire Resource Dictionary but again you shouldn't inject any logic in a resource container... | WPF: Referencing the Window from a Custom Control | [
"",
"c#",
"wpf",
"events",
""
] |
For about 2 weeks now, I have been unable to run any UnitTests (built in VS unit tests) for a project. Previously everything worked fine. The error message is:
*Could not load file or assembly 'C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\MyProjectName.XmlSerializers.dll" or one of its dependencies.*
The project references System.Xml.Serialization and uses the XmlSerializer class; just like many other classes/projects I've written. For some reason, only this project is affected. It builds fine, runs fine, I just can't run my unit tests.
I've checked the directory, and all the dlls in that directory are Microsoft dlls. The dll that it is looking for obviously is not a Microsoft dll.
Anyone have any ideas?
**Edit:**
It apparently has something to do with using the XmlSerializer and it generating that file automatically instead of using sgen.exe. Here is a link to the MSDN [article](http://msdn.microsoft.com/en-us/library/bk3w6240.aspx). From what I've been able to find, it has something to do with using the serializer with generics. None of the sources I've found seem to offer any way to make it actually work. | **Solution**
As it turns out, the problem was with VMWare. I installed the latest version of VMWare, and it installed it's tools to debug in a VM. Something it installed or changed caused this problem. When I uninstalled VMWare, the problem went away. So, I reinstalled VMWare without installing it's debugging capabilities and the problem did not come back.
**Workaround**:
I still have no idea why this problem suddenly started occurring, but I found a hack to make it work.
I had to go to project properties => Build Events and add this line to the Post-build event command line:
```
"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sgen.exe" "$(TargetPath)" /force
```
This forces VS to generate the file. I then had to copy that file manually to the directory it was looking for it in:
```
"C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies"
```
Now it I can run my tests and step through them. The problems I have now are 1) I have to remember to copy the dll to that directory every time I change something in the classes that I am serializing, and 2) I now get a ThreadInterruptedException when a test finishes running; thus 3) I can only run one test at a time.
Not a good solution, but at least I can limp through. Unfortunately, redoing everything, as Nikita Borodulin suggested, is not an option. | First enable loader logging (using `FUSLOGVW.exe` from the SDK) to confirm what is not being found.
Then use Reflector on all your assemblies to find the one that is trying to load the non-existent assembly. If you find no such assembly it must be being loaded dynamically, in which case attaching to AppDomain.AssemblyResolve should allow you to identify where. | Strange dll error message | [
"",
"c#",
"unit-testing",
"dll",
""
] |
We have an existing "legacy" app written in C++/powerbuilder running on Unix with it's own Sybase databases. For complex organizational(existing apps have to go through lot of red-tape to be modified) and code reasons(no re-factoring has been done in yrs so the code is spaghetti), so it's difficult to get modifications done to this application. Hence I am considering writing a new modern, maybe grails, based web app to do some "admin" type things directly into the database. For example to add users, or to add "constraint rows".
What does the software community think of this approach of doing a run-around of the existing app like this? Good idea? Tips and hints? | Good idea? No.
Sometimes necessary? Yes.
Living in a world where you sometimes have to do things you know aren't a good idea? Priceless.
In general, you should always follow best practices. For everything else, there's kludges. | There is always a debate between a single monolithic app and several more focused apps. I don't think it's necessarily a bad idea to separate things - you make things more modular, reduce dependecies, etc.. The thing to avoid is duplication of functionality. If you split off an adminstration app separately, make sure to remove that functionality from the old app, or else you will have an unmaintained set of adminstration tools that will likely come back to haunt you. | Doing a run-around of existing application to make database changes, good idea? | [
"",
"c++",
"architecture",
"grails",
"refactoring",
""
] |
currently using PHP5 with htmlMimeMail 5 (<http://www.phpguru.org/static/mime.mail.html>) to send HTML e-mail communications. Have been having issues with a number of recipients seeing random characters replaced with equals signs e.g.:
"Good mor=ing. Our school is sending our newsletter= and information through a company called..."
Have set e-mail text, HTML, and header encoding to UTF-8. The template files loaded by PHP for the e-mail (just include()'d text/HTML with a few php tags in them) are both encoded in UTF-8.
The interesting thing is that I can't duplicate the problem on any of my e-mail clients, and can't find any information by searching yahoo/googlies that would point me at the problem!! | Try sending with 8-bit encoding:
```
$message->setTextEncoding(new EightBitEncoding());
$message->setHTMLEncoding(new EightBitEncoding());
``` | I had a similar issue, but mine was a little different. Since I stumbled upon this thread looking for the answer and it helped me find it, I thought I may as well post this related answer here.
In my case special characters were getting messed up in emails even through the actual mb\_detect\_encoding of the text strings being sent was "UTF-8" and if I echoed them they looked fine.
So I had to us the function
```
$message->setTextCharset('UTF-8')
```
and
```
$message->setHTMLCharset('UTF-8')
``` | E-mails sent through php5+htmlMimeMail are being received with random characters replaced with = | [
"",
"php",
"email",
"unicode",
"outlook",
"mime",
""
] |
I have this javascript function that block special characters...
```
function validaTexto(texto)
{
!(/^[A-zÑñ0-9]*$/i).test(texto.value) ? texto.value = texto.value.replace(/[^A-zÑñ0-9]/ig, '') : null;
}
```
The problem is that this function doesn't allow me to type blank spaces... how can I customize this function to allow me some other things, such as blank spaces, "," , "." , ";" and so on?
Thanks!! | change the regex to this:
```
!(/[^A-zÑñ0-9 ,\.;]*$/i)
```
also, the function is quite redundant in that it checks the string twice, basically saying "Does the string contain any of these characters? Yes? Ok, so search the string for these same characters and remove them. Just change it to this:
```
function validaTexto(texto) {
texto.value.replace(/[^a-zñ0-9 ,\.;]/ig, '');
}
``` | ```
function validaTexto(texto) {
texto.value.replace(/[^A-z0-9 ,\.;]/ig, '');
}
```
Referenes (with examples):
* <http://www.regular-expressions.info/>
* <http://regexlib.com/> | How can I customize this javascript function? | [
"",
"javascript",
""
] |
I have the following code in accessing a database via nhibernate:
```
ISessionFactory factory =
new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory();
using (ISession session = factory.OpenSession())
{
ICriteria sc = session.CreateCriteria(typeof(Site));
siteList = sc.List();
session.Close();
}
factory.Close();
```
I wonder whether it is possible to wrap it in this way:
```
using (var factory= new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory())
{
var session = factory.OpenSession();
ICriteria sc = session.CreateCriteria(typeof(Site));
siteList = sc.List();
}
```
As far as I understand, all the connection inside the using() block will be automatically closed. So I guess that the second statement is fully equivalent to the first.
Am I right? | This is what you usually do:
```
using (ISession session = factory.OpenSession()) {
ICriteria sc = session.CreateCriteria(typeof(Site));
siteList = sc.List();
}
```
However you open build your factory just once - at the start of application. You should not really bother by closing it (unless some specific cases) since it's the application end that cleans it up.
Your factory usually resides in one well defined place - as a singleton.
And to help you understand - using is just c# construct which equals to following:
```
try {
ISession session = sf.OpenSession();
.....
} finally {
session.Dispose();
}
``` | Your 2nd code example has at least one bad practice: you're building your SessionFactory, and afterwards you destroy it. So, I assume that you build your SessionFactory each time you need to have a session ? | Wrap Transaction Inside Using-- Need to Close it manually? | [
"",
"c#",
"nhibernate",
""
] |
I'm using a well known template to allow binary constants
```
template< unsigned long long N >
struct binary
{
enum { value = (N % 10) + 2 * binary< N / 10 > :: value } ;
};
template<>
struct binary< 0 >
{
enum { value = 0 } ;
};
```
So you can do something like binary<101011011>::value. Unfortunately this has a limit of 20 digits for a unsigned long long.
Does anyone have a better solution? | Does this work if you have a leading zero on your binary value? A leading zero makes the constant octal rather than decimal.
Which leads to a way to squeeze a couple more digits out of this solution - always start your binary constant with a zero! Then replace the 10's in your template with 8's. | The approaches I've always used, though not as elegant as yours:
1/ Just use hex. After a while, you just get to know which hex digits represent which bit patterns.
2/ Use constants and OR or ADD them. For example (may need qualifiers on the bit patterns to make them unsigned or long):
```
#define b0 0x00000001
#define b1 0x00000002
: : :
#define b31 0x80000000
unsigned long x = b2 | b7
```
3/ If performance isn't critical and readability is important, you can just do it at runtime with a function such as "x = fromBin("101011011");".
4/ As a sneaky solution, you could write a pre-pre-processor that goes through your \*.cppme files and creates the \*.cpp ones by replacing all "0b101011011"-type strings with their equivalent "0x15b" strings). I wouldn't do this lightly since there's all sorts of tricky combinations of syntax you may have to worry about. But it would allow you to write your string as you want to without having to worry about the vagaries of the compiler, and you could limit the syntax trickiness by careful coding.
Of course, the next step after that would be patching GCC to recognize "0b" constants but that may be an overkill :-) | C++ binary constant/literal | [
"",
"c++",
"templates",
"binary",
"constants",
""
] |
An associate has created a schema that uses an `ENUM()` column for the primary key on a lookup table. The table turns a product code "FB" into it's name "Foo Bar".
This primary key is then used as a foreign key elsewhere. And at the moment, the FK is also an `ENUM()`.
I think this is not a good idea. This means that to join these two tables, we end up with four lookups. The two tables, plus the two `ENUM()`. Am I correct?
I'd prefer to have the FKs be `CHAR(2)` to reduce the lookups. I'd also prefer that the PKs were also `CHAR(2)` to reduce it completely.
The benefit of the `ENUM()`s is to get constraints on the values. I wish there was something like: `CHAR(2) ALLOW('FB', 'AB', 'CD')` that we could use for both the PK and FK columns.
What is:
1. Best Practice
2. Your preference
This concept is used elsewhere too. What if the `ENUM()`'s values are longer? `ENUM('Ding, dong, dell', 'Baa baa black sheep')`. Now the `ENUM()` is useful from a space point-of-view. Should I only care about this if there are several million rows using the values? In which case, the `ENUM()` saves storage space. | ENUM should be used to define a possible range of values for a given field. This also implies that you may have multiple rows which have the same value for this perticular field.
I would not recommend using an ENUM for a primary key type of foreign key type.
Using an ENUM for a primary key means that adding a new key would involve modifying the table since the ENUM has to be modified before you can insert a new key.
I am guessing that your associate is trying to limit who can insert a new row and that number of rows is limited. I think that this should be achieved through proper permission settings either at the database level or at the application and not through using an ENUM for the primary key.
IMHO, using an ENUM for the primary key type violates the [KISS principle](http://en.wikipedia.org/wiki/KISS_principle). | but when you only trapped with differently 10 or less rows that wont be a problem
### e.g's
```
CREATE TABLE `grade`(
`grade` ENUM('A','B','C','D','E','F') PRIMARY KEY,
`description` VARCHAR(50) NOT NULL
)
```
This table it is more than diffecult to get a **DML** | Should I use an ENUM for primary and foreign keys? | [
"",
"sql",
"mysql",
"enums",
""
] |
I am creating an application that is essentially a financial alerts site. I am a basic level Java programmer, and I have created some of the logic for alerts in Java.
I want to be able to have pop-ups appear on the desktop whenever something "interesting" happens (interesting depends on %change, liquidity and a few other simple factors).
What is the best combo of technology to implement something like this? | I would use the [java.awt.SystemTray](http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/systemtray/) in Java SE 6. It's cross-platform and pretty easy to use.
Although some people hate the balloon notifications in Windows, they're the least obtrusive popups, since they can be ignored by the user or easily dismissed. Most importantly, they can't be missed by the user who has been away from the computer, because balloons (at least in Windows XP/Vista) use system idle timers to determine when's the right time to disappear.
Some prefer more traditional toast notifications, similar to those shown by Outlook - they show up and slowly fade out, giving the user some time to interact with them if needed. | I had the same [problem](https://stackoverflow.com/questions/629388/how-to-notify-the-user-of-important-events-for-a-desktop-application) and finally solved it using an undecorated, alwaysOnTop window.
And thanks to [this blog entry](http://www.curious-creature.org/2007/09/28/translucent-shaped-windows-extreme-gui-makeover/) I found the [TimingFramework](https://timingframework.dev.java.net/), and now it even is translucent, fades in and out, goes 100% opaque on mouse over etc. In conjunction with the SystemTray and TrayIcon the behavior is nearly as that of Outlook.
Oh, I have to note, that other than the [second](http://www.curious-creature.org/2007/09/28/translucent-shaped-windows-extreme-gui-makeover/) link, I do the fading out with
```
AWTUtilities.setWindowOpacity(window, op);
``` | Recommended technology choice for desktop application | [
"",
"java",
"popup",
"desktop-application",
""
] |
I have the following piece of code to write data to an XML file.
```
private void WriteResidentData()
{
int count = 1;
status = "Writing XML files";
foreach (Site site in sites)
{
try
{
//Create the XML file
StreamWriter writer = new StreamWriter(path + "\\sites\\" + site.title + ".xml");
writer.WriteLine("<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>");
writer.WriteLine("<customer_list>");
foreach (Resident res in site.GetCustomers())
{
bw.ReportProgress((count / customers) * 100);
writer.WriteLine("\t<customer>");
writer.WriteLine("\t\t<customer_reference>" + res.reference + "</customer_reference>");
writer.WriteLine("\t\t<customer_name>" + res.name + "</customer_name>");
writer.WriteLine("\t\t<customer_address>" + res.address + "</customer_address>");
writer.WriteLine("\t\t<payment_method>" + res.method + "</payment_method>");
writer.WriteLine("\t\t<payment_cycle>" + res.cycle + "</payment_cycle>");
writer.WriteLine("\t\t<registered>" + CheckWebStatus(res.reference) + "</registered>");
writer.WriteLine("\t</customer>");
count++;
}
writer.WriteLine("</customer_list>");
writer.Close();
}
catch (Exception ex)
{
lastException = ex;
}
}
}
```
It's using the same BackgroundWorker that gets the data from the database. My progress bar properly displays the progress whilst it is reading from the database. However, after zeroing the progress bar for the XML writing it simply sits at 0 even though the process is completing correctly.
Can anyone suggest why? | I think that should be (count\*100)/customers, assuming you wanted a percentage complete. | Could it be that (count / customers) is truncated to zero (division between two integers)? | Progress Bar not updating | [
"",
"c#",
".net",
"progress-bar",
"backgroundworker",
""
] |
What is a decent IDE for developing JavaScript, I'll be writing both client side stuff and writing for Rhino. Ideally It needs to run on Mac OSX, although something that runs on Windows too would be nice.
**ADDITIONAL:**
Having had a play with both js2 and Aptana, I think I'll be continuing to use Aptana. Mainly because I find emacs a bit hard to get my head round, although I did think that the error hi-lighting in js2 was better than that in Aptana.
I'm still looking for a way to visually debug my js code that is running atop Rhino... | Aptana IDE, absolutely. Stable, great syntax support for all the major javascript libraries, very good css and html editors. Also good support for php, air, ruby on rails and iPhone app development (I never tested this one).
Aptana can also connect to remote site via ftp (sftp in the pro edition) and to svn and cvs repositories.
It's based on Eclipse, so it's not exactly a lightweight application. But it's really, really good. You can also use it as an Eclipse plugin if you develop java wab app, but when I tested it in this version, about 1 year ago, it was not stable. Much better to use the standalone version. | If you're familiar with Emacs Steve Yegge's [`js2-mode`](https://web.archive.org/web/20160117163316/https://code.google.com/p/js2-mode/) could be worth a look. | Decent JavaScript IDE | [
"",
"javascript",
"ide",
"rhino",
""
] |
I'm trying out pylint to check my source code for conventions. Somehow some variable names are matched with the regex for constants (`const-rgx`) instead of the variable name regex (`variable-rgx`). How to match the variable name with `variable-rgx`? Or should I extend `const-rgx` with my `variable-rgx` stuff?
e.g.
`C0103: 31: Invalid name "settings" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$)` | > Somehow some variable names are matched with the regex for constants (const-rgx) instead of the variable name regex (variable-rgx).
Are those variables declared on module level? Maybe that's why they are treated as constants (at least that's how they should be declared, according to PEP-8). | I just disable that warning because I don't follow those naming conventions.
To do that, add this line to the top of you module:
```
# pylint: disable-msg=C0103
```
If you want to disable that globally, then add it to the pylint command:
```
python lint.py --disable-msg=C0103 ...
``` | python code convention using pylint | [
"",
"python",
"conventions",
"pylint",
""
] |
A normal regexp to allow letters only would be *"[a-zA-Z]"* but I'm from, Sweden so I would have to change that into *"[a-zåäöA-ZÅÄÖ]"*. But suppose I don't know what letters are used in the alphabet.
Is there a way to automatically know what chars are are valid in a given locale/language or should I just make a blacklist of chars that I (think I) know I don't want? | You can use \pL to match any 'letter', which will support all letters in all languages. You can narrow it down to specific languages using 'named blocks'. More information can be found on the [Character Classes](http://msdn.microsoft.com/en-us/library/20bw873z.aspx) documentation on MSDN.
My recommendation would be to put the regular expression (or at least the "letter" part) into a localised resource, which you can then pull out based on the current locale and form into the larger pattern. | What about \p{name} ?
> Matches any character in the named character class specified by {name}.
> Supported names are Unicode groups and block ranges. For example, Ll, Nd, Z,
> IsGreek, IsBoxDrawing.
I don't know enough about unicode, but maybe your characters fit a unicode class? | Regular expression to catch letters beyond a-z | [
"",
"c#",
"regex",
""
] |
I have Java JDBC application running against an Oracle 10g Database. I set up a PreparedStatement to execute a query, and then call ps.executeQuery() to run it. Occasionally the query takes a long time, and I need to kill it. I have another thread access that PreparedStatement object, and call cancel() on it.
My question is, does this actually kill the query in the database? Or does it just sever it from the client, and the query is still running somewhere in the bowels of Oracle?
Thanks! | The answer is that it's a quality-of-implementation issue. If you look at the [javadoc](http://java.sun.com/j2se/1.5.0/docs/api/java/sql/Statement.html#cancel()) for Statement.cancel(), it says it'll happen "if both the DBMS and driver support aborting an SQL statement".
In my experience with various versions of Oracle JDBC drivers, Statement.cancel() seems to do what you'd want. The query seems to stop executing promptly when cancelled. | Please note that what I say below is based on observations and inferences of Oracle in use, and is not based on any deep understanding of Oracle's internals. None of it should be considered authoritative.
What ninesided said in their first paragraph is correct. However, beware the test suggested. Not all long-running oracle queries are the same. It seems that queries are evaluated over two phases, first a phase that combines up sufficient data to know how to return the rows in the right order, and second a phase that returns the rows filling in the gaps that it didn't compute in the first phase. The division of work between the two phases is also affected by the settings of the cost-based optimizer. e.g. First-rows vs All-rows.
Now, if the query is in phase 1, the cancel request seems at best to be queued up to be applied at the end of phase 1, which means that the query continues operating.
In phase 2, rows are returned in bunches, and after each bunch, the cancel command can take effect, so assuming the driver supports the command, the cancel request will result in the query being killed.
The specification for the JDBC cancel command does not seem to say what should happen if the query does not stop running, and therefore the command may wait for confirmation of the kill, or may timeout and return with the query still running. | When I call PreparedStatement.cancel() in a JDBC application, does it actually kill it in an Oracle database? | [
"",
"sql",
"oracle",
"jdbc",
""
] |
I guess the question says it all, but, what happens if someone closes a c++ console app? As in, clicks the "x" in the top corner. Does it instantly close? Does it throw some sort of exception? Is it undefined behavior? | Closing a c++ console app with the "x" in the top corner throws an `CTRL_CLOSE_EVENT` which you could catch and process if you set a control handler using the [SetConsoleCtrlHandler](http://msdn.microsoft.com/en-us/library/ms686016(VS.85).aspx) function. In there you could override the close functionality and perform whatever you wished to do, and then optionally still perform the default behavior. | I imagine that the console process just gets unceremoniously killed by the OS. If you want to trap this event and do something it looks like the [SetConsoleCtrlHandler](http://msdn.microsoft.com/en-us/library/ms686016(VS.85).aspx) function is the way to do it.
See also:
* [How to handle a ctrl-break signal in a command line interface](https://stackoverflow.com/questions/181413/how-to-handle-a-ctrl-break-signal-in-a-command-line-interface)
* [Console Event Handling](http://www.codeproject.com/KB/winsdk/console_event_handling.aspx?display=PrintAll) | What happens when you close a c++ console application | [
"",
"c++",
"winapi",
"console-application",
""
] |
I am interested in using the ASP.NET Cache to decrease load times. How do I go about this? Where do I start? And how exactly does caching work? | As applications grow it is quite normal to leverage caching as a way to gain scalability and keep consistent server response times. Caching works by storing data in memory to drastically decrease access times. To get started I would look at ASP.NET caching.
There are 3 types of general Caching techniques in ASP.NET web apps:
* Page Output Caching(Page Level)
* Page Partial-Page Output(Specific Elements
of the page)
* Programmatic or Data Caching
**Output Caching**
Page level output caching caches the html of a page so that each time ASP.NET page requested it checks the output cache first. You can vary these requests by input parameters([VaryByParam](http://msdn.microsoft.com/en-us/library/system.web.ui.outputcacheparameters.varybyparam.aspx)) so the the page will only be cached for users where ID=1 if a requests come in where ID=2 asp.net cache is smart enough to know it needs to re-render the page.
**Partial-Page Caching**
a lot of times it wont make sense to cache the entire page in these circumstances you can use partial Page caching. This is usually used with user controls and is set the same way as page level only adding the OutputCache declarative inside the usercontrol.
**Data Caching**
You can store objects or values that are commonly used throughout the application. It can be as easy to as:
```
Cache["myobject"] = person;
```
**Enterprise Level Caching**
It is worth mention that there are many Enterprise level caching architectures that have come about to leverage the effectiveness caching. [Memcache](http://sourceforge.net/projects/memcacheddotnet/) for .net and [Velocity(now App Fabric)](http://msdn.microsoft.com/en-gb/windowsserver/ee695849.aspx) are a couple.
**In General**
You can't really make blanket statements on what you should and shouldn't cache because every application is different. However, you can make a few generalizations that hold true **MOST** of time. Static elements like images and content are OK to cache. Even a dynamic page that is getting hammered is worth caching for 5-10 seconds, it will make a world of difference to your web server. | Your best bet might be to check out a couple of the caching videos on [www.asp.net/learn/videos](http://www.asp.net/learn/videos), specifically: [How Do I Make Use of Caching?](http://www.asp.net/learn/videos/video-42.aspx) and [How do I Make Greater use of Caching ?](http://www.asp.net/learn/videos/video-41.aspx)
I always find them helpful. | How does the ASP.NET Cache work? | [
"",
"c#",
"asp.net",
"caching",
""
] |
I'm looking for a command line argument parser, such as "Command line parser" from <http://www.sellsbrothers.com/tools/Genghis/> .
Features I'm looking for:
* Auto-generation of usage
* Should able to check required and optional parameters
* Parameters should support IEnumerable with separator support
* Should support flag parameters
* Would be nice to support combining parameters such as "/fx" == "/f /x"
* Would be nice to not force for a space after a parameter such as "/ftest.txt" == "/f test.txt"
P.S :
*"Command line parser" is quite good, I really like the design of it but there is no documentation, no new updates and I couldn't figure out to do certain stuff such as how to check for required parameters.* | My personal favourite 3rd party commandline parsing library is [Command Line Parser](https://github.com/commandlineparser/commandline) and I assume this is the one you are referring to. The most recent release was less than 2 months ago and there are regular commits. If you want a more mature offering you could check out the console library in the mono project (sorry I can't seem to find a direct link to the namespace at the moment, but its a part of the mono framework) | Have a look at ndesk.options.
It is called [Mono.Options](https://github.com/mono/mono/tree/master/mcs/class/Mono.Options/) now. | Looking for a Command Line Argument Parser for .NET | [
"",
"c#",
".net",
"command-line",
"arguments",
""
] |
**Update**: the clearest explanation I have found on the web as I have been struggling through this can be found [here](http://aspalliance.com/articleViewer.aspx?aId=135&pId=).
Maybe I just don't understand the model of runat server terribly well. It appears the following code is always executing the if block. If the code is running on the server side I guess I can understand that it has to be stateless.
I am a seasoned non-web programmer but it appears counter intuitive to me. Will I need to create some sort of session object or pass the current state along in the URL or what?
```
<script runat="server">
DateTime begin;
DateTime end;
int iSelectedStart = 0;
int iSelectedEnd = 0;
int iPutName = 0;
protected void Button1_Click(object sender, EventArgs e)
{
if (iPutName == 0)
{
iPutName = 1;
Label1.Text = TextBox1.Text + " you will be slecting your start and end dates.";
``` | It looks like part of your code got cut off, but here's the basic thing with web programming -- it's stateless. Unless, that is, you do something (use ViewState, Session, etc.) to add some state into the mix.
In your case, it looks like you want to maintain some state through refreshes of the page. Put the values you want to preserve in ViewState to keep them across postbacks to the same page. If you want to hold values across pages on your site, use Session. If you want to maintain values across visits to the site, put them in a database and tie them to a login or cookie. | The important thing to remember here is that the web is stateless. Each request from a person's browser is completely separate from all previous requests. What's happening with your code is that the class is being instantiated from scratch each time the client requests a page. That includes clicking Button1.
If you want values to persist between requests, you have to store it in a location where it can be retrieved later. The Session object provides this for you.
Basically, you'll need to store the iPutName variable in the session somehow. Probably the nicest way is to encapsulate it in a property:
```
protected int iPutName
{
get {
if (Session["iPutName"] == null)
Session["iPutName"] == 0;
return Session["iPutName"];
}
set { Session["iPutName"] = value; }
}
```
**Edit:** The ViewState object will work as well (as long as ViewState is turned on on the page). This encodes the value in a hidden field in the HTML and decodes it when it comes back.
**Edit (again):** Apologies for repeated edits, but I should clear this up. What Jonathan and Emil have said is correct. You should probably be using ViewState for this rather than Session unless you want this value to remain accessible between pages. Note that this does require that [ViewState is turned on](http://msdn.microsoft.com/en-us/library/ms972976.aspx) and it will result in a larger payload being sent to the client. | Beginner how do you maintain state in an ASP C# Web Page | [
"",
"c#",
"asp.net",
"visual-studio",
""
] |
How can I capture multiple key downs in C# when working in a [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) form?
I just can't seem to get both the up arrow and right arrow at the same time. | I think you'll be best off when you use the GetKeyboardState API function.
```
[DllImport ("user32.dll")]
public static extern int GetKeyboardState( byte[] keystate );
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
byte[] keys = new byte[256];
GetKeyboardState (keys);
if ((keys[(int)Keys.Up] & keys[(int)Keys.Right] & 128 ) == 128)
{
Console.WriteLine ("Up Arrow key and Right Arrow key down.");
}
}
```
In the KeyDown event, you just ask for the 'state' of the keyboard.
The GetKeyboardState will populate the byte array that you give, and every element in this array represents the state of a key.
You can access each keystate by using the numerical value of each virtual key code. When the byte for that key is set to 129 or 128, it means that the key is down (pressed). If the value for that key is 1 or 0, the key is up (not pressed). The value 1 is meant for toggled key state (for example, caps lock state).
For details see the [Microsoft documentation for GetKeyboardState](http://msdn.microsoft.com/en-us/library/windows/desktop/ms646299(v=vs.85).aspx). | A little proof-of-concept code for you, assuming `Form1` contains `label1`:
```
private List<Keys> pressedKeys = new List<Keys>();
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
pressedKeys.Add(e.KeyCode);
printPressedKeys();
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
pressedKeys.Remove(e.KeyCode);
printPressedKeys();
}
private void printPressedKeys()
{
label1.Text = string.Empty;
foreach (var key in pressedKeys)
{
label1.Text += key.ToString() + Environment.NewLine;
}
}
``` | Capture multiple key downs in C# | [
"",
"c#",
"winforms",
""
] |
I'm trying to create an auto-clicker in Java(only language I know and I just learned Threads). I want to have the applet open in it's own window(not on a webpage), and I want to be able to start and stop the program with the spacebar without the window being selected so that I can use the auto-clicker on another program and be able to stop it without alt-f4ing a bunch of stuff.
Is there anything you can refer me to that can help me along with this? Or do you have any suggestions? | This might be out of the scope of a Java applet. In fact, global keyboard hooks are definitely out of the scope of simply using Java, but I can help you get moving in the right direction.
However, you have some hope. I'll point you into the direction of [JNI (Java Native Interface)](http://java.sun.com/docs/books/jni/), which will allow you to use native libraries. Now, since you want to stay in the Java world, I suggest not directly using JNI because you'll have to write some confusing native code (typically C, C++). There are several wrappers for JNI that allow you to use the functions but the native implementations are abstracted away, but a lot of these cost money.
---
So the best solution for you, I think, is [JNA (Java Native Access)](https://github.com/twall/jna/). This allows you to directly call native libraries from within Java. (NOTE: The implementation not will be cross platform. You have to make separate implementations for Windows, Linux, etc.) There's a good example for Windows keyboard hooks in the examples on the project website.
As for opening it's own window not in a webpage, do you want the applet to not run within the browser but in its own separate process, or just be in a separate window and still rely on the browser window being open?
* If you want to simply launch a new window and still require the browser to be open, then here's a good example:
```
final Frame window = new Frame("This is the Frame's Title Bar!");
window.add(new Label("This is the Frame."));
window.setSize(300,200);
window.setVisible(true);
window.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
window.dispose();
}
});
```
* If you want the applet to spawn a new process and run without the need of the browser, look into [JavaFX](http://www.sun.com/software/javafx/). | Late answer but hopefully helpful :)
You can using JNA, it's a cakewalk!!
1. get JNA (jna.jar)
2. create your own mapping for User32 (User32.dll) in the form
```
public interface User32 extends StdCallLibrary {
User32 INSTANCE = (User32) Native.loadLibrary("User32", User32.class, Options.UNICODE_OPTIONS);
// dwWakeMask Constants
public static final int QS_ALLEVENTS = 0x04BF;
public static final int QS_ALLINPUT = 0x04FF;
public static final int QS_ALLPOSTMESSAGE = 0x0100;
public static final int QS_HOTKEY = 0x0080;
public static final int QS_INPUT = 0x407;
public static final int QS_KEY = 0x0001;
public static final int QS_MOUSE = 0x0006;
public static final int QS_MOUSEBUTTON = 0x0004;
public static final int QS_MOUSEMOVE = 0x0002;
public static final int QS_PAINT = 0x0020;
public static final int QS_POSTMESSAGE = 0x0008;
public static final int QS_RAWINPUT = 0x0400;
public static final int QS_SENDMESSAGE = 0x0040;
public static final int QS_TIMER = 0x0010;
public static final int INFINITE = 0xFFFFFFFF;
/*
DWORD WINAPI MsgWaitForMultipleObjects(
__in DWORD nCount,
__in const HANDLE *pHandles,
__in BOOL bWaitAll,
__in DWORD dwMilliseconds,
__in DWORD dwWakeMask
);*/
int MsgWaitForMultipleObjects(int nCount, Pointer pHandles, boolean bWaitAll, int dwMilliSeconds, int dwWakeMask);
/* fsModifiers vaues */
public static final int MOD_ALT = 0x0001;
public static final int MOD_CONTROL = 0x0002;
public static final int MOD_NOREPEAT = 0x4000;
public static final int MOD_SHIFT = 0x0004;
public static final int MOD_WIN = 0x0008;
/* BOOL WINAPI RegisterHotKey(
__in_opt HWND hWnd,
__in int id,
__in UINT fsModifiers,
__in UINT vk
);
*/
boolean RegisterHotKey(Pointer hWnd, int id, int fsModifiers, int vk);
}
```
3. Just check out the following pages to get a clear idea of how things work under the hood:
h\*\*p://msdn.microsoft.com/en-us/library/ms646309%28VS.85%29.aspx
h\*\*p://msdn.microsoft.com/en-us/library/ms684242%28VS.85%29.aspx
1. Check this page to see what are the key constants you can register a callback for
h\*\*p://msdn.microsoft.com/en-us/library/dd375731%28v=VS.85%29.aspx
1. Create a test program like this:
```
User32 user32 = User32.INSTANCE;
boolean res = user32.RegisterHotKey(Pointer.NULL, 9999, User32.MOD_ALT | User32.MOD_CONTROL, WINUSER.VK_LEFT);
if(!res)
System.out.println("Couldn't register hotkey");
System.out.println("Starting and waiting");
user32.MsgWaitForMultipleObjects(0, Pointer.NULL, true, User32.INFINITE, User32.QS_HOTKEY);
System.out.println("Ending");
```
User32.INFINITE is an undocumented constant with value 0xFFFFFFFF
Sorry about the http links renamed into h\*\*p :) Stackoverflow rules
Stefano | Java Keylistener without window being open? | [
"",
"java",
"keylistener",
""
] |
I am somewhat new to transactional databases and have come across an issue I am trying to understand.
I have created a simple demonstration where a database connection is stored inside each of the 5 threads created by cherrypy. I have a method that displays a table of timestamps stored in the database and a button to add a new record of time stamps.
the table has 2 fields, one for the datetime.datetime.now() timestamp passed by python and one for the database timestamp set to default NOW().
```
CREATE TABLE test (given_time timestamp,
default_time timestamp DEFAULT NOW());
```
I have 2 methods that interact with the database. The first will create a new cursor, insert a new given\_timestamp, commit the cursor, and return to the index page. The second method will create a new cursor, select the 10 most recent timestamps and return those to the caller.
```
import sys
import datetime
import psycopg2
import cherrypy
def connect(thread_index):
# Create a connection and store it in the current thread
cherrypy.thread_data.db = psycopg2.connect('dbname=timestamps')
# Tell CherryPy to call "connect" for each thread, when it starts up
cherrypy.engine.subscribe('start_thread', connect)
class Root:
@cherrypy.expose
def index(self):
html = []
html.append("<html><body>")
html.append("<table border=1><thead>")
html.append("<tr><td>Given Time</td><td>Default Time</td></tr>")
html.append("</thead><tbody>")
for given, default in self.get_timestamps():
html.append("<tr><td>%s<td>%s" % (given, default))
html.append("</tbody>")
html.append("</table>")
html.append("<form action='add_timestamp' method='post'>")
html.append("<input type='submit' value='Add Timestamp'/>")
html.append("</form>")
html.append("</body></html>")
return "\n".join(html)
@cherrypy.expose
def add_timestamp(self):
c = cherrypy.thread_data.db.cursor()
now = datetime.datetime.now()
c.execute("insert into test (given_time) values ('%s')" % now)
c.connection.commit()
c.close()
raise cherrypy.HTTPRedirect('/')
def get_timestamps(self):
c = cherrypy.thread_data.db.cursor()
c.execute("select * from test order by given_time desc limit 10")
records = c.fetchall()
c.close()
return records
if __name__ == '__main__':
cherrypy.config.update({'server.socket_host': '0.0.0.0',
'server.socket_port': 8081,
'server.thread_pool': 5,
'tools.log_headers.on': False,
})
cherrypy.quickstart(Root())
```
I would expect the given\_time and default\_time timestamps to be only a few microseconds off from each other. However I am getting some strange behavior. If I add timestamps every few seconds, the default\_time is not a few microseconds off from the given\_time, but is usually a few microseconds off from the *previous* given\_time.
```
Given Time Default Time
2009-03-18 09:31:30.725017 2009-03-18 09:31:25.218871
2009-03-18 09:31:25.198022 2009-03-18 09:31:17.642010
2009-03-18 09:31:17.622439 2009-03-18 09:31:08.266720
2009-03-18 09:31:08.246084 2009-03-18 09:31:01.970120
2009-03-18 09:31:01.950780 2009-03-18 09:30:53.571090
2009-03-18 09:30:53.550952 2009-03-18 09:30:47.260795
2009-03-18 09:30:47.239150 2009-03-18 09:30:41.177318
2009-03-18 09:30:41.151950 2009-03-18 09:30:36.005037
2009-03-18 09:30:35.983541 2009-03-18 09:30:31.666679
2009-03-18 09:30:31.649717 2009-03-18 09:30:28.319693
```
Yet, if I add a new timestamp about once a minute, both the given\_time and default\_time are only a few microseconds off as expected. However, after submitting the 6th timestamp (the number of threads + 1) the default\_time is a few microseconds off from the first given\_time timestamp.
```
Given Time Default Time
2009-03-18 09:38:15.906788 2009-03-18 09:33:58.839075
2009-03-18 09:37:19.520227 2009-03-18 09:37:19.520293
2009-03-18 09:36:04.744987 2009-03-18 09:36:04.745039
2009-03-18 09:35:05.958962 2009-03-18 09:35:05.959053
2009-03-18 09:34:10.961227 2009-03-18 09:34:10.961298
2009-03-18 09:33:58.822138 2009-03-18 09:33:55.423485
```
Even though I am explicitly closing the cursor after each use, it appears that the previous cursor is still being reused. How is that possible if I am closing the cursor after I'm done with it and creating a new cursor each time? Can someone please explain what is going on here?
**Closer to an answer:**
I've added a cursor.connection.commit() to the get\_timestamps method and that now gives me accurate data with the timestamps. Can anyone explain why I could need to call cursor.connection.commit() when all I am doing is a select? I am guessing that every time I get a cursor, a transaction begins (or continues with an existing transaction unit it gets committed). Is there a better way to do this or am I stuck committing every time I get a cursor regardless of what I do with that cursor? | To address the question posed by your most recent edits:
In PostgreSQL, `NOW()` is *not* the current time, but the time *at the start of the current transaction*. Psycopg2 is probably starting a transaction implicitly for you, and since the transaction is never closed (by a commit or otherwise), the timestamp gets 'stuck' and becomes stale.
Possible fixes:
* Commit frequently (silly if you're only doing SELECTs)
* Set up Psycopg2 to use different behavior for automatically creating transactions (probably tricky to get right, and *will* affect other parts of your app)
* Use a different timestamp function, like `statement_timestamp()` (not SQL-standard-compliant, but otherwise perfect for this scenario)
From [the manual, section 9.9.4](http://www.postgresql.org/docs/8.3/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT), emphasis added:
> PostgreSQL provides a number of
> functions that return values related
> to the current date and time. These
> SQL-standard functions all return
> values based on the start time of the
> current transaction:
>
> * `CURRENT_DATE`
> * `CURRENT_TIME`
> * `CURRENT_TIMESTAMP`
> * `CURRENT_TIME(precision)`
> * `CURRENT_TIMESTAMP(precision)`
> * `LOCALTIME` `LOCALTIMESTAMP`
> * `LOCALTIME(precision)`
> * `LOCALTIMESTAMP(precision)`
>
> `CURRENT_TIME` and `CURRENT_TIMESTAMP`
> deliver values with time zone;
> `LOCALTIME` and `LOCALTIMESTAMP`
> deliver values without time zone.
>
> `CURRENT_TIME`, `CURRENT_TIMESTAMP`,
> `LOCALTIME`, and `LOCALTIMESTAMP` can
> optionally be given a precision
> parameter, which causes the result to
> be rounded to that many fractional
> digits in the seconds field. Without a
> precision parameter, the result is
> given to the full available precision.
>
> ...
>
> Since **these functions return the
> start time of the current transaction,
> their values do not change during the
> transaction**. This is considered a
> feature: the intent is to allow a
> single transaction to have a
> consistent notion of the "current"
> time, so that multiple modifications
> within the same transaction bear the
> same time stamp.
>
> *Note:* Other database systems might advance these values more frequently.
>
> PostgreSQL also provides functions
> that return the start time of the
> current statement, as well as the
> actual current time at the instant the
> function is called. The complete list
> of non-SQL-standard time functions is:
>
> * `now()`
> * `transaction_timestamp()`
> * `statement_timestamp()`
> * `clock_timestamp()`
> * `timeofday()`
>
> `now()` is a traditional PostgreSQL
> equivalent to `CURRENT_TIMESTAMP`.
> `transaction_timestamp()` is likewise
> equivalent to `CURRENT_TIMESTAMP`, but
> is named to clearly reflect what it
> returns. `statement_timestamp()`
> returns the start time of the current
> statement (more specifically, the time
> of receipt of the latest command
> message from the client).
> `statement_timestamp()` and
> `transaction_timestamp()` return the
> same value during the first command of
> a transaction, but might differ during
> subsequent commands.
> `clock_timestamp()` returns the actual
> current time, and therefore its value
> changes even within a single SQL
> command. `timeofday()` is a historical
> PostgreSQL function. Like
> `clock_timestamp()`, it returns the
> actual current time, but as a
> formatted text string rather than a
> timestamp with time zone value. | Try calling c.close() as described in the module documentation: <http://tools.cherrypy.org/wiki/Databases>
```
def add_timestamp(self):
c = cherrypy.thread_data.db.cursor()
now = datetime.datetime.now()
c.execute("insert into test (given_time) values ('%s')" % now)
c.connection.commit()
c.close()
raise cherrypy.HTTPRedirect('/')
def get_timestamps(self):
c = cherrypy.thread_data.db.cursor()
c.execute("select * from test order by given_time desc limit 10")
records = c.fetchall()
c.close()
return records
``` | python postgres cursor timestamp issue | [
"",
"python",
"postgresql",
"cherrypy",
""
] |
I'm developing a small programming language based mostly of the C99 standard and I've already written a fairly decent lexer in java and now I'm looking to generate a Java Parser from the grammar. I know there's [Bison](http://www.gnu.org/software/bison/), but that seems to only generate C code. I'm looking for a application that will allow me to input my grammar and create a full parser class in java code. Reading other SO posts on related topics, I've found ANTLR, but I'm wondering if anyone in the SO knows about a better tool?
thanks! | Another couple to look at are [JavaCC](https://javacc.dev.java.net/) and [SableCC](http://sablecc.org/) (it has been a long time since I looked at SableCC). | I've been quite impressed by [BNFC](http://www.cs.chalmers.se/Cs/Research/Language-technology/BNFC/), which is able to generate parsers in Java as well as in C, C++, C#, F#, Haskell, and OCaml. | What's the best tool for generating a parser in Java for my own language grammar? | [
"",
"java",
"parsing",
"programming-languages",
"antlr",
""
] |
I'm trying to read data in from a binary file and then store in a data structure for later use. The issue is I don't want to have to identify exactly what type it is when I'm just reading it in and storing it. I just want to store the information regarding what type of data it is and how much data of this certain type there is (information easily obtained in the first couple bytes of this data)
But how can I read in just a certain amount of data, disregarding what type it is and still easily be able to cast (or something similar) that data into a readable form later?
My first idea would be to use characters, since all the data I will be looking at will be in byte units.
But if I did something like this:
```
ifstream fileStream;
fileStream.open("fileName.tiff", ios::binary);
//if I had to read in 4 bytes of data
char memory[4];
fileStream.read((char *)&memory, 4);
```
But how could I cast these 4 bytes if I later I wanted to read this and knew it was a double?
What's the best way to read in data of an unknown type but know size for later use?
fireStream. | You could copy it to the known data structure which makes life easier later on:
```
double x;
memcpy (&x,memory,sizeof(double));
```
or you could just refer to it as a cast value:
```
if (*((double*)(memory)) == 4.0) {
// blah blah blah
}
```
I believe a `char*` is the best way to read it in, since the size of a char is guaranteed to be 1 unit (not necessarily a byte, but all other data types are defined in terms of that unit, so that, if sizeof(double) == 27, you know that it will fit into a char[27]). So, if you have a known size, that's the easiest way to do it. | I think a `reinterpret_cast` will give you what you need. If you have a `char *` to the bytes you can do the following:
```
double * x = reinterpret_cast<double *>(dataPtr);
```
Check out [Type Casting on cplusplus.com](http://www.cplusplus.com/doc/tutorial/typecasting.html) for a more detailed description of `reinterpret_cast`. | How to read in specific sizes and store data of an unknown type in c++? | [
"",
"c++",
"casting",
""
] |
In the past I've saved RGB images (generated from physical simulations) as 8-bits/channel PPM or PNG or JPEG.
Now I want to preserve the dynamic range of the simulation output, which means saving a floating point image and then treating conversion to 8-bits/channel as a post-processing step (so I can tweak the conversion to 8-bit without running the lengthy simulation again).
Has a "standard" floating point image format emerged ?
Good free supporting libraries/viewers/manipulation tools, preferably available in Debian, would be a bonus. | Have you looked into Radiance RGBE (.hdr) and [OpenEXR](http://en.wikipedia.org/wiki/OpenEXR) (.exr). RGBE has some [source code here](http://www.graphics.cornell.edu/online/formats/rgbe/). NVIDIA and ATI both support EXR data in their graphics cards. There are source code and binaries from the [OpenEXR download page](http://www.openexr.com/downloads.html). ILM created OpenEXR and it has wide support. OpenEXR has support for 16 and 32 bit floating point per channel, and is what most people use these days, unless they've written their own format.
* The [Pixel Image Editor](http://www.kanzelsberger.com/pixel/?p=70) for linux has EXR support for editing, too.
* [pfstools](http://pfstools.sourceforge.net/) is also necessary if you're going to work with HDR on linux. Its a set of command line programs for reading, writing and manipulating HDR and has Qt and OpenGL viewers.
* Theres also jpeg2exr for linux
* Heres some other [debian packages](http://packages.debian.org/search?keywords=openexr) for OpenEXR viewers.
* Based on this, it looks like theres also a [Gimp plugin](http://grafpup.org/news/?p=103) somewhere. | For future reference, also rather widespread is the [TIFF](https://en.wikipedia.org/wiki/TIFF) format. You can use the free and open-source [LibTIFF](http://www.libtiff.org/) for I/O. | Which floating-point image format should I use? | [
"",
"c++",
"graphics",
"rendering",
"file-format",
"hdrimages",
""
] |
I need to store my users' name/password somewhere (preferably the Registry) so my .Net application can use them to log in to some remote service on behalf of the user. I know it's possible to store values in the registry as "secrets", which means their encrypted using the Windows domain user token or something. In other words, I don't want to have to deal with the encryption myself.
To clarify: I can't store hashes of the password or salt them or anything. These credentials are for a 3rd party system and the **only** way for me to be able to login to this system on behalf of my users is to somehow keep their credentials and be able to restore them.
So anyway, I remember vaguely there's such a place in the registry, but the details are murky. And I need to do it in C# (though if it's simple registry access it shouldn't matter).
**Edit:** One more thing, it should persist between Windows user sessions (IOW it doesn't help me if the password in unreadable after the user logs off and on). | You're probably thinking of the Data Protection API. Search MSDN or [read some blogs](http://blogs.msdn.com/shawnfa/archive/2004/05/05/126825.aspx) and see if that'll work for you. | You can try using System.Security.Cryptography.ProtectedData, which can encrypt them using a per user key. [http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx.](http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx)
It's not completely secure, since code running as the user could decrypt the data. | Keeping passwords in the registry as "secrets" | [
"",
"c#",
".net",
"encryption",
"registry",
"passwords",
""
] |
I've got lots of text that I need to output, which includes all sorts of characters from many languages. Sometimes I need to output the text in character encodings other than Unicode (eg, Shift-JIS, or ISO-8859-2), in order to match the page it's going to.
If the text has characters that the encoding can't handle (eg, Japanese characters in ISO-8859-2 encoded output) I end up with odd characters in the output. I can escape them, but I'd rather do that only if it's really necessary.
So, my question is this: Is there a way I can tell ahead of time if an encoding can handle all the characters in my string?
EDIT:
I think the EncoderFallback is probably the right answer to the question I asked. Unfortunately it doesn't seem to work in my particular situation. My thought was to convert the characters to their HTML entity equivalents (eg, モ instead of モ). However, the encoder only converts the first such character it finds, and if I set the Response.ContentEncoding it never calls my EncoderFallback at all. | You can write your own EncoderFallback class assign that to the encoder before encoding.
Using this approach you need do nothing in advanced (which likely would be simply processing the output string looking for problems).
Instead your Fallback class need only handle replacements where the encoding does not have a value for a character. | Try to encode the string with an Encoding whose [EncoderFallback](http://msdn.microsoft.com/en-us/library/system.text.encoding.encoderfallback.aspx) is set to [EncoderExceptionFallback](http://msdn.microsoft.com/en-us/library/system.text.encoderexceptionfallback.aspx). eg.:
```
Encoding e= Encoding.GetEncoding(932, new EncoderExceptionFallback(), new DecoderExceptionFallback());
```
Then catch [EncoderFallbackException](http://msdn.microsoft.com/en-us/library/system.text.encoderfallbackexception.aspx) when you GetBytes(). | .NET: How do I tell if an encoding supports all the chars in my string? | [
"",
"c#",
".net",
"text",
"encoding",
"character-encoding",
""
] |
For logging purposes
```
__LINE__
__FILE__
```
were my friends in C/C++. In Java to get that information I had to throw an exception and catch it. Why are these old standbys so neglected in the modern programming languages? There is something magical about their simplicity. | It is uglier, but you can do something like this in C# using the [StackTrace](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stacktrace) and [StackFrame](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.stackframe) classes:
```
StackTrace st = new StackTrace(new StackFrame(true));
Console.WriteLine(" Stack trace for current level: {0}", st.ToString());
StackFrame sf = st.GetFrame(0);
Console.WriteLine(" File: {0}", sf.GetFileName());
Console.WriteLine(" Method: {0}", sf.GetMethod().Name);
Console.WriteLine(" Line Number: {0}", sf.GetFileLineNumber());
Console.WriteLine(" Column Number: {0}", sf.GetFileColumnNumber());
```
Of course, this comes with some overhead. | [Caller Information](http://msdn.microsoft.com/en-us/library/hh534540%28v=vs.110%29.aspx) has been added to .NET 4.5. This will be compiled, a big improvement over having to examine the stack trace manually.
```
public void Log(string message,
[CallerFilePath] string filePath = "",
[CallerLineNumber] int lineNumber = 0)
{
// Do logging
}
```
Simply call it in this manner. The compiler will fill in the file name and line number for you:
```
logger.Log("Hello!");
``` | Do __LINE__ __FILE__ equivalents exist in C#? | [
"",
"c#",
"logging",
""
] |
I have two obects, A & B for this discussion. I can join these objects (tables) via a common relationship or foreign key. I am using linq to do this join and I only want to return ObjectA in my result set; however, I would like to update a property of ObejctA with data from ObjectB during the join so that the ObjectAs I get out of my LINQ query are "slightly" different from their original state in the storage medium of choice.
Here is my query, you can see that I would just like to be able to do something like objectA.SomeProperty = objectB.AValueIWantBadly
I know I could do a new in my select and spin up new OBjectAs, but I would like to avoid that if possible and simply update a field.
```
return from objectA in GetObjectAs()
join objectB in GetObjectBs()
on objectA.Id equals objectB.AId
// update object A with object B data before selecting it
select objectA;
``` | Add an update method to your ClassA
```
class ClassA {
public ClassA UpdateWithB(ClassB objectB) {
// Do the update
return this;
}
}
```
then use
```
return from objectA in GetObjectAs()
join objectB in GetObjectBs()
on objectA.Id equals objectB.AId
// update object A with object B data before selecting it
select objectA.UpdateWithB(objectB);
```
**EDIT**:
Or use a local lambda function like:
```
Func<ClassA, ClassB, ClassA> f = ((a,b)=> { a.DoSomethingWithB(b); return a;});
return from objectA in GetObjectAs()
join objectB in GetObjectBs()
on objectA.Id equals objectB.AId
select f(objectA , objectA );
``` | From the word "tables", it sounds like you are getting this data from a database. In which case; no: you can't do this. The closest you can do would to select the objects and the extra columns, and update the properties afterwards:
```
var qry = from objectA in GetObjectAs()
join objectB in GetObjectBs()
on objectA.Id equals objectB.AId
select new { A = objectA,
objectB.SomeProp, objectB.SomeOtherProp };
foreach(var item in qry) {
item.A.SomeProp = item.SomeProp;
item.A.SomeOtherProp = item.SomeOtherProp;
// perhaps "yield return item.A;" here
}
```
If you were doing LINQ-to-Objects, there are perhaps some hacky ways you could do it with fluent APIs - not pretty, though. (edit - like [this other reply](https://stackoverflow.com/questions/709560/linq-in-line-property-update-during-join/709579#709579)) | LINQ In Line Property Update During Join | [
"",
"c#",
"linq",
""
] |
I'm sure there must be a much better way of doing this. I'm trying to do a count operation on a Flags enum. Before I was itterating over all the possible values and counting the succesful AND operations.
e.g.
```
[Flags]
public enum Skills
{
None = 0,
Skill1 = 1,
Skill2 = 2,
Skill3 = 4,
Skill4 = 8,
Skill5 = 16,
Skill6 = 32,
Skill7 = 64,
Skill8 = 128
}
public static int Count(Skills skillsToCount)
{
Skills skill;
for (int i = 0; i < SkillSet.AllSkills.Count; i++)
{
skill = SkillSet.AllSkills[i];
if ((skillsToCount & skill) == skill && skill != Skills.None)
count++;
}
return count;
}
```
I'm sure there must be a better way of doing this though, but must be suffering from a mental block. Can anyone advise a nicer solution? | After looking on the site Assaf suggested I managed to find a slightly different solution that I got working for Int32's.
Here's the code for anyone else:
```
internal static UInt32 Count(this Skills skills)
{
UInt32 v = (UInt32)skills;
v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
UInt32 c = ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
return c;
}
``` | The following code will give you the number of bits that are set for a given number of any type varying in size from byte up to long.
```
public static int GetSetBitCount(long lValue)
{
int iCount = 0;
//Loop the value while there are still bits
while (lValue != 0)
{
//Remove the end bit
lValue = lValue & (lValue - 1);
//Increment the count
iCount++;
}
//Return the count
return iCount;
}
```
This code is very efficient as it only iterates once for each bit rather than once for every possible bit as in the other examples. | Counting the number of flags set on an enumeration | [
"",
"c#",
"enums",
""
] |
How to remove selected items from ListBox when a datasource is assigned to it in C#?
When trying to remove, got error
**"Items collection cannot be modified when the DataSource property is set."**
---
But when i try to remove item from datasource (datatable) ,
it thorws error as "datarow is not in current row collection". | Find that item in the DataSource object and remove it, then re-bind the ListBox.
**EDIT**:
Here's how you delete from a DataTable as your DataSource, regardless of the .NET version.
```
DataRowView rowView = listBox.SelectedItem as DataRowView;
if (null == rowView)
{
return;
}
dt.Rows.Remove(rowView.Row);
```
I haven't tried with anything other than WinForms DataGridViews, but I highly recommend [BindingListView](http://blw.sourceforge.net/), which is both faster than DataTables/Views and allows you to bind generic List<T>s as your DataSource. | Alternatively, use a list that implements IBindingList or inherits from BindingList. When objects are added or removed from a Binding List, any controls bound to it are automatically notified of the change and will update themselves accordingly. If you are using BindingList and your class also implements INotifyProperty changed, Any changes to class properties will also be updated automatically in the databinding control. For example, if a column in a datagrid(view) is bound to a property, "Name", and you change "Name" in the datasource, the datagrid will automatically update. If you add a new item to the datasource, the datagrid will update automatically. Binding List also supports notification in the other direction. If a user edits the "Name" field ina datagrid, the bound object will be updated automatically. Going off topic slightly, if you go a little further and impliment "SupportsSortingCore" and the associated methods in BindingList, you can add automatic sorting to your data. Clicking on a columnm header will automatically sort the list and display the header sort direction arrow. | How to remove selected items from ListBox when a DataSource is assigned to it in C#? | [
"",
"c#",
""
] |
I don't know, but I feel that IllegalStateException is causing undo headache. If I have a request say a JSP or some other servlet and need to associate a filter with that request. I can't do any other modifications to the output to the client if the response has already been committed?
For example, I see in JSP code that sets the mimetype to response.setContent("html") and then I have a filter associated with the JSP that needs to set the mimetype to something
else. setContent("image") or "xhtml". But I get an IllegalStateException?
Is there a way to clear the previous response that has been committed or is there something to avoid this issue.
This is on websphere. | I think you need to rethink how you're preparing and returning your responses. You can't write to the response (which *may* write to the client) and then change your mind.
Leaving aside the question of why your solution has to change the return type, I would write to some dummy container object with the return date + type, and make this mutable. Only once your servlet has completed all its work would you then write this object (type+content) to the outputstream.
(to clarify, I don't think servlet filters are the right approach for this. They will intercept the request, and the response, but the response population is the responsibility of the servlet) | I agree with the other posters that this is ugly but you can create an HttpServletResponseWrapper in your filter that would hijack the output and pass that wrapper to the chain instead of the original response object. | Avoiding IllegalStateException in Java/Servlet web stack | [
"",
"java",
"jsp",
"servlets",
"jakarta-ee",
""
] |
Is it possible to programmatically start an application from Java and then send commands to it and receive the program's output?
I'm trying to realize this scenario:
I want to access a website that uses lots of javascript and special html + css features -> the website isn't properly displayed in swt.browser or any of the other of the available Browser Widgets. But the website can be displayed without any problems in firefox. So I want to run a hidden instance of firefox, load the website and get the data. (It would be nice if FF can be embedded in a JFrame or so..)
Has anybody got an idea how to realize this?
Any help would really be appreciated!
EDIT: The website loads some Javascript that does some html magic and loads some pictures. When I only read the html from the website I see nothing more than some JavaScript calls. But when the website is loaded in a Browser, it displays some images overlayed with text. That's what I'm trying to show the user of my app. | To start Firefox from within the application, you could use:
```
Runtime runtime = Runtime.getRuntime();
try {
String path = "/path/to/firefox";
Process process = runtime.exec(path + " " + url);
} catch (IOException e) {
// ...
}
```
To manipulate processes once they have started, one can often use *process.getInputStream()* and *process.getOutputStream()*, but that would not help you in the case of Firefox.
You should probably look into ways of solving your specific problem other than trying to interact directly between your application and a browser instance. Consider either moving the whole interface into a Java gui, or doing a web app from the ground up -- not half and half. | See this [article](http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html) - it will teach you how to start a process, read its output and write to its input stream.
However this solution may be not be the best for your problem. What kind of data do you need to get from the Web Page? Would it be better to read the html with an HTTP GET and then parse it with an Html parser? | Java: "Control" External Application | [
"",
"java",
"firefox",
""
] |
I am maintaining an old VB6 application, and would like to include SQL scripts directly in part of the project. The VB6 application should then extract the text of this script and execute it on the server.
The reasons for this approach are various - among others, we want to deliver only an updated executable rather than a complete update/installation package. Hence, the SQL scripts need to be compiled into the application just like a resource file. And, obviously, one has to be able to get at the content from code, in order to send it to the database server.
Does anyone have a good way to do this? | The simplest solution is to just create a VB module with the scripts as strings.
If you want to use a resource file instead, you can do that too. You can associate a resfile with a VB project (I don't remember how to do this directly in the VB IDE but the VBP file supports a [ResFile32 parameter](http://www.vbrezq.com/perform.php)).
EDIT: It seems like the issue here is mostly about formatting -- you don't want to store SQL queries as one long string, but formatting the query nicely inside VB is tedious because you have to add quotes, add string concatenation operators to join the lines together, etc.
I would recommend placing the SQL in a text file and formatting it in whatever way you like. Write a script that will take the text and convert it into a VB module. The build process would be modified to always apply this script first before compiling the application.
For scripting, use your favorite scripting language; if you don't have a favorite scripting language, this is an easy enough task that you could do it in VB, C#, or any other language. If it were me, I'd probably use awk (gawk) or Python. | If you want to use a resource (.RES) to store your SQL, go to the menu:
Add-ins > Add-in Manager...
and select *VB 6 Resource Editor*. Configure the add-in to be loaded and to load at startup.
From the editor add-in, VB provides a simple interface to add resource strings. You will refer to these using the provided constant values. To load the strings at runtime, use the *LoadResString* function:
```
Public Const SQL_INSERT As Integer = 101
Dim strSQL As String
strSQL = LoadResString(SQL_INSERT)
```
(replace "101" with the constant value of the string you wish to load) | Include sql scripts in a VB6 application | [
"",
"sql",
"vb6",
""
] |
I have created a class like so:
```
function MyClass()
{
var myInt = 1;
}
MyClass.prototype.EventHandler = function(e)
{
alert(this.myInt);
}
```
Unfortunately, the `this` is the triggered event (in my case an `<a>` tag), and I can't access the class properties.
Any suggestions? | It depends on how you are giving your event handler when registering the event.
The following code
```
element.addEventListener("click", myObject.EventHandler);
```
will not do what you want.
Javascript does not handle delegates like C# would for example, so myObject.EventHandler is not the EventHandler method called for myObject.
If you want to call a method on an object as an event handler, the best is to wrap it into a function.
```
element.addEventListener("click", function(event)
{
myObject.EventHandler(event);
});
``` | "vars" declared in the constructor function will not be available on other public functions, they are considered as "*private members*".
You could use `this.myInt = 1` to make the member public, and available to all the class methods:
```
function MyClass(){
this.myInt = 1; // Public member
}
MyClass.prototype.EventHandler = function(e){
alert(this.myInt);
}
```
or you could have a "*privileged*" method, to access the "*private*" member on the constructor scope:
```
function MyClass(){
var myInt = 1; // Private member
this.getMyInt = function(){ // Public getter
return myInt;
}
}
MyClass.prototype.EventHandler = function(e){
alert(this.getMyInt());
}
```
Recommended lecture: [Private Members in JavaScript](http://www.crockford.com/javascript/private.html) (Douglas Crockford) | Class method can't access properties | [
"",
"javascript",
"class",
"dom-events",
""
] |
I am just reviewing some code I wrote to communicate with the serial port in C# on CF2.0.
I am not using DataReceived event since it's not reliable. [MSDN states that:](http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx)
> The DataReceived event is not
> gauranteed to be raised for every byte
> received. Use the BytesToRead property
> to determine how much data is left to
> be read in the buffer.
I poll the port with read() and have a delegate that processes the data when it is read. I also read somewhere that "polling is bad"(no explanation given).
Any ideas why polling might be bad? aside from the usual threading cautions - I have a separate thread (background thread) that polls the port, the thread is exited after the data is read, all tested and works well. | The way I read that, you might get one event for multiple bytes, rather than one event per byte. I would still expect to get an event when data is ready, and not have it "skip" some bytes entirely.
I've always used this event, and have not had any trouble with it. | Conventional wisdom has it that "polling is bad" because it often ends up being a CPU-bound process. If blocking I/O is used instead, then the CPU is available for other processes until the event happens.
That said, it is usually possible to set things up so that a poll waits for a (short) timeout before returning when no characters are available. If a suitable timeout is chosen, then your simple polling loop uses significantly less CPU time, and other processes also get to run.
I haven't used serial ports from C# at all, but I am going to hazard a guess that what the documentation meant by
> The DataReceived event is not guaranteed to be raised for every byte received. Use
> the BytesToRead property to determine how much data is left to be read in the buffer.
is that you can't expect to get one event per character. It might under some circumstances deliver the event with more than one character available. Simply retrieve all the available characters in your event handler, and all will be well.
**Edit:** Doing a blocking call on a reader thread might be the best answer overall. It isn't polling per se since the thread is blocked until characters arrive. You might need to tune the buffer sizes and some of the serial port settings if you need to process the data as it arrives rather than in fixed sized chunks. | Serial port communication: polling serial port vs using serial port DataReceived event | [
"",
"c#",
"multithreading",
"serial-port",
""
] |
If I derive a class from IDictionary, how can I be certain that any given V has not changed after it is added to the underlying collection? | There's many ways, but it depends...
If the value type added to the dictionary contains a "Changed" type of event, subscribe to it.
If the value type doesn't contain such an event, but you control the source code, add the event and subscribe to it.
If the value type doesn't contain such an event, and you don't control the source code, consider maintaining a shadow copy of the values with cloned values or something, and do comparisons.
I'm afraid that in the last case there, where you don't control the type and it doesn't contain events, you're left with no choice but to somehow make a record of the current state of each value, and later on compare to that state to see if it has changed. | I would implement [INotifyPropertyChanged](http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx) on the class that you intend to be contained in your IDictionary, if it's a reference type. On "Add" of item subscribe to the PropertyChanged event, ensure you unsubscribe when you remove items; otherwise you'll 'leak' the reference to the contained object instance (it won't be collected). Something like this:
```
public event EventHandler<CollectionItemPropertyChangedEventArgs> CollectionItemPropertyChanged;
public void Add(object key, object item)
{
INotifyPropertyChanged notify = item as INotifyPropertyChanged;
if(notify != null)
{
notify.PropertyChanged += OnCollectionItemPropertyChanged;
}
}
private void OnCollectionItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if(this.CollectionItemPropertyChanged != null)
{
CollectionItemPropertyChanged eventArgs = new CollectionItemPropertyChanged();
eventArgs.Item = sender;
eventArgs.Property = e.PropertyName;
this.this.CollectionItemPropertyChanged(this, eventArgs);
}
}
``` | Detecting if a value contained in a Dictionary has changed | [
"",
"c#",
".net",
""
] |
Is there a pattern where I can inherit enum from another enum in C++??
Something like that:
```
enum eBase
{
one=1, two, three
};
enum eDerived: public eBase
{
four=4, five, six
};
``` | Not possible. There is no inheritance with enums.
You can instead use classes with named const ints.
Example:
```
class Colors
{
public:
static const int RED = 1;
static const int GREEN = 2;
};
class RGB : public Colors
{
static const int BLUE = 10;
};
class FourColors : public Colors
{
public:
static const int ORANGE = 100;
static const int PURPLE = 101;
};
``` | ```
#include <iostream>
#include <ostream>
class Enum
{
public:
enum
{
One = 1,
Two,
Last
};
};
class EnumDeriv : public Enum
{
public:
enum
{
Three = Enum::Last,
Four,
Five
};
};
int main()
{
std::cout << EnumDeriv::One << std::endl;
std::cout << EnumDeriv::Four << std::endl;
return 0;
}
``` | Base enum class inheritance | [
"",
"c++",
"enums",
""
] |
I have a class that is mapped to a table using NHibernate. The problem is that only some of the properties are mapped to columns in the table. This is fine because the only columns we use for display are mapped, however I was wondering if there is any way to query against other columns in the table that aren't mapped to properties in my class.
For example we have a table with the following columns:
```
Customer
-----------
CustomerId
Name
DateCreated
```
and we have an object
```
public class Customer
{
public virtual int CustomerId {get;set;}
public virtual string name {get;set;}
}
```
and `name` and `customerId` are mapped however `DateCreated` is not because we never display it anywhere. We would like to query the `Customer` table for customers that were created by a certain date. Is there any way to do this **without** mapping the `DateCreated`? Also it would be preferable to do this using the criteria API. | Ayende Rahien posted an article which describes specifying `access="noop"` in the mapping to specify query-only properties. See [NHibernate – query only properties](http://ayende.com/Blog/archive/2009/06/10/nhibernate-ndash-query-only-properties.aspx "NHibernate – query only properties"). I have not tried this myself. | Is using a plain SQL query out of the question? I'm not able to test it right now, but I would imagine that you could query on unmapped fields, as long as your query returns something that Hibernate can map to an object. (sorry if this was already ruled out as an option)
EDIT: This seems to work:
```
ISQLQuery query = session.CreateSQLQuery(
"select c.* " +
"from Customer c " +
"where c.CreateDate > :CreateDate");
query.SetDateTime("CreateDate", new DateTime(2009, 3, 14));
query.AddEntity(typeof(Customer));
IList<Customer> results = query.List<Customer>();
``` | Query Unmapped Columns in NHibernate | [
"",
"c#",
"nhibernate",
"nhibernate-mapping",
""
] |
**Is there any way to wait for termination of a thread, but still intercept signals?**
Consider the following **C** program:
```
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
void* server_thread(void* dummy) {
sleep(10);
printf("Served\n");
return NULL;
}
void* kill_thread(void* dummy) {
sleep(1); // Let the main thread join
printf("Killing\n");
kill(getpid(), SIGUSR1);
return NULL;
}
void handler(int signum) {
printf("Handling %d\n", signum);
exit(42);
}
int main() {
pthread_t servth;
pthread_t killth;
signal(SIGUSR1, handler);
pthread_create(&servth, NULL, server_thread, NULL);
pthread_create(&killth, NULL, kill_thread, NULL);
pthread_join(servth, NULL);
printf("Main thread finished\n");
return 0;
}
```
It ends after one second and prints:
```
Killing
Handling 10
```
In contrast, here's my attempt to write it in **Python**:
```
#!/usr/bin/env python
import signal, time, threading, os, sys
def handler(signum, frame):
print("Handling " + str(signum) + ", frame:" + str(frame))
exit(42)
signal.signal(signal.SIGUSR1, handler)
def server_thread():
time.sleep(10)
print("Served")
servth = threading.Thread(target=server_thread)
servth.start()
def kill_thread():
time.sleep(1) # Let the main thread join
print("Killing")
os.kill(os.getpid(), signal.SIGUSR1)
killth = threading.Thread(target=kill_thread)
killth.start()
servth.join()
print("Main thread finished")
```
It prints:
```
Killing
Served
Handling 10, frame:<frame object at 0x12649c0>
```
**How do I make it behave like the C version?** | Jarret Hardie already [mentioned it](https://stackoverflow.com/questions/631441/interruptible-thread-join-in-python/631605#631605): According to [Guido van Rossum](http://bugs.python.org/msg56947), there's no better way as of now: As stated in the [documentation](http://docs.python.org/library/threading.html#threading.Thread.join), `join(None)` blocks (and that means no signals). The alternative - calling with a huge timeout (`join(2**31)` or so) and checking `isAlive` looks great. However, the way Python handles timers is disastrous, as seen when running the python test program with `servth.join(100)` instead of `servth.join()`:
```
select(0, NULL, NULL, NULL, {0, 1000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 2000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 4000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 8000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 16000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 32000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 50000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 50000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 50000}) = 0 (Timeout)
--- Skipped 15 equal lines ---
select(0, NULL, NULL, NULL, {0, 50000}Killing
```
I.e., Python wakes up every 50 ms, leading to a single application keeping the CPU from sleeping. | Threads in Python are somewhat strange beasts given the global interpreter lock. You may not be able to achieve what you want without resorting to a join timeout and isAlive as eliben suggests.
There are two spots in the docs that give the reason for this (and possibly more).
The first:
From <http://docs.python.org/library/signal.html#module-signal>:
> Some care must be taken if both
> signals and threads are used in the
> same program. The fundamental thing to
> remember in using signals and threads
> simultaneously is: always perform
> signal() operations in the main thread
> of execution. Any thread can perform
> an alarm(), getsignal(), pause(),
> setitimer() or getitimer(); only the
> main thread can set a new signal
> handler, and the main thread will be
> the only one to receive signals (this
> is enforced by the Python signal
> module, even if the underlying thread
> implementation supports sending
> signals to individual threads). This
> means that signals can’t be used as a
> means of inter-thread communication.
> Use locks instead.
The second, from <http://docs.python.org/library/thread.html#module-thread>:
> Threads interact strangely with interrupts: the KeyboardInterrupt exception will be
> received by an arbitrary thread. (When the signal module is available, interrupts
> always go to the main thread.)
**EDIT:** There was a decent discussion of the mechanics of this on the python bug tracker here: <http://bugs.python.org/issue1167930>. Of course, it ends with Guido saying: " That's unlikely to go away, so you'll just have to live
with this. As you've discovered, specifying a timeout solves the issue
(sort of)." YMMV :-) | Interruptible thread join in Python | [
"",
"python",
"multithreading",
""
] |
Lets take an example in C#
```
public class Foo
{
public Foo() { }
public Foo(int j) { }
}
public class Bar : Foo
{
}
```
Now, All the public members of Foo is accessible in Bar except the constructor.
I cannot do something like
```
Bar bb = new Bar(1);
```
Why the constructors are not inheritable?
***UPDATE***
I do understand we can chain constructors, but I would like to know why the above construct is not valid. I am sure there should be a valid reason for it. | Constructors are not inheritable because it might cause weird and unintended behavior. More specifically, if you added a new constructor to a base class, all derived classes get an instance of that constructor. That's a bad thing in some cases, because maybe your base class specifies parameters that don't make sense for your derived classes.
A commonly given example for this is that in many languages, the base class for all objects (commonly called "Object") has a constructor with no parameters. If constructors were inherited, this would mean that all objects have a parameterless constructor, and there's no way to say "I want people who make an instance of this class to provide parameters X, Y and Z, otherwise their code shouldn't compile." For many classes, it's important that certain parameters be defined for their proper function, and making constructors non-heritable is part of the way that class authors can guarantee that some parameters are always defined.
Edit to respond to comments: Ramesh points out that if constructors were inherited as he would like them to be, he could always override base class constructors using privately declared constructors in each derived class. That is certainly true, but there it a logistical problem with this strategy. It requires that writers of derived classes have to watch base classes closely and add a private constructor if they want block inheritance of the base class constructor. Not only is this a lot of work for people writing derived classes, this kind of implicit dependency across classes is exactly the sort of thing that can cause weird behavior.
Ramesh - it's not that what you describe would be impossible to add to a language. In general it's not done because that sort of behavior could confuse people and lead to a lot of extra debugging and code writing.
Quintin Robinson provides some very worthwhile responses to this question in the comments that are definitely worth reading. | They are (via chaining), you would have to chain the constructor in your derived object.. IE:
```
public class Foo
{
public Foo() { }
public Foo(int j) { }
}
public class Bar : Foo
{
public Bar() : base() { }
public Bar(int j) : base(j) { }
}
```
The constructors in the derived objects will then chain the calls do the constructors in the base objects.
[This article](http://weblogs.asp.net/scottcate/archive/2005/11/23/431412.aspx) provides some more examples if you want further reading. | Constructors and Inheritance | [
"",
"c#",
"oop",
"inheritance",
""
] |
I am using a Python script to **find and replace** certain strings in text files of a given directory. I am using the `fileinput` module to ease the find-and-replace operation, i.e., the file is read, text replaced and written back to the same file.
The code looks as follows:
```
import fileinput
def fixFile(fileName):
# Open file for in-place replace
for line in fileinput.FileInput(fileName, inplace=1):
line = line.replace("findStr", "replaceStr")
print line # Put back line into file
```
The problem is that the written files have:
1. One blank line inserted after *every* line.
2. Ctrl-M character at the end of *every* line.
How do I prevent these extra appendages from getting inserted into the files? | Your newlines are coming from the print function
use:
```
import sys
sys.stdout.write ('some stuff')
```
and your line breaks will go away | Use
```
print line,
```
or
```
file.write(line)
```
to fix extra newlines.
As of [Ctrl]-[M] - that is probably caused by input files in DOS encoding. | Python: Prevent fileinput from adding newline characters | [
"",
"python",
"file-io",
""
] |
How can I overload the STL implementation for methods like find, erase and insert to take varying parameters? I tried to look up the overloading of STL methods but couldn't find any help. | You can't overload the methods of a class without editing the code of that class.
Write your own free functions that act as helpers; they would take the relevant container class as the first parameter.
You can inherit from a class and add methods that way, but the std container classes are not designed to be inherited from. | You are not allowed to add overloads in the std namespace. Only specialization of functions and algorithms for your own data types are allowed. If you do want a different find, erase, insert... implement a wrapper (out of the std namespace) and use it.
And I would not recommend it either... What kind of overloads do you want to provide? | Overloading C++ STL methods | [
"",
"c++",
"stl",
"overloading",
""
] |
I am trying to efficiently make a copy of a vector. I see two possible approaches:
```
std::vector<int> copyVecFast1(const std::vector<int>& original)
{
std::vector<int> newVec;
newVec.reserve(original.size());
std::copy(original.begin(), original.end(), std::back_inserter(newVec));
return newVec;
}
std::vector<int> copyVecFast2(std::vector<int>& original)
{
std::vector<int> newVec;
newVec.swap(original);
return newVec;
}
```
Which of these is preferred, and why? I am looking for the most efficient solution that will avoid unnecessary copying. | Your second example does not work if you send the argument by reference. Did you mean
```
void copyVecFast(vec<int> original) // no reference
{
vector<int> new_;
new_.swap(original);
}
```
That would work, but an easier way is
```
vector<int> new_(original);
``` | They aren't the same though, are they? *One is a copy, the other is a swap*. Hence the function names.
My favourite is:
```
a = b;
```
Where `a` and `b` are vectors. | Is it more efficient to copy a vector by reserving and copying, or by creating and swapping? | [
"",
"c++",
"algorithm",
"vector",
"stl",
""
] |
I've read plenty of articles about tuning GC in Java and have often wondered how many people *really* use some of the more advanced features.
I've always avoided tuning where possible and concentrated on writing the simplest possible code I can (Brian Goetz's advice) - this seems to have worked well for me so far.
Are these tuning strategies resilient to change across VM versions or do they require constant re-assessment?
The one tuning that I have made use of is the -server flag. | Part of my current job is the care and feeding of a large java application that was designed to run with a large amount of memory (currently around 8 Gb), mostly due to ongoing calculations with lots of cached data. I did the initial deployment with the standard GC setup , mostly because there wasn't a simple way to simulate the production environment running at full tilt.
In stages, over the next few months, I've customized the GC settings. Generally, the biggest available knob seems to be adjusting the frequency and magnitude of incremental gc - the biggest improvement has been in trading off large periodic gc for smaller and more frequent ones. But we've definitely been able to see performance improvements.
I'm not going to post my specific settings because a) they're specific to our setup, and b) because I don't have them handy :). But in general, what I've found is
* there's been a lot of work done in
tuning the default gc settings.
*Almost* always the defaults work better than any tweaks I would make.
* At least for me, the situations where
gc tuning was actually worthwhile
were extreme enough that it was
unreasonable to attempt to simulate
them, so I had to do it
experimentally and incrementally.
[Here's](https://stackoverflow.com/questions/202502/appropriate-tomcat-5-5-start-up-parameters-to-tune-jvm-for-extremely-high-demand/202555#202555) a good reference from a prev. stackoverflow discussion. | The vast majority of developers will never have to (or want to) tune GC. I have worked with people who have had to tune it and here is the advice:
> Before you attempt to tune the garbage
> collector make 100% sure you have
> verified, with a profiler. what is
> going on. Once you start tuning make
> sure you verify, with a profiler, that
> it had a positive effect.
You should also revisit the changes with each version of the VM you run on (different VMs will have different tuning strategies).
I once helped someone with an GC issue that turned out to be them not closing JDBC result sets (or some issue like that). This caused memory to never be freed (his code held onto them for some reason). Fixing that issue made the program go from 20 minutes to something like 30 seconds or a couple of minutes. The memory usage went way down as well. | Has anyone found Garbage Collection tuning to be useful? | [
"",
"java",
"garbage-collection",
"performance",
""
] |
Can anyone tell me the best way to decode binary data with variable length bit strings in java?
For example:
> The binary data is 10101000 11100010 01100001 01010111 01110001 01010110
>
> I might need to find the first match of any of the following 01, 100, 110, 1110, 1010...
>
> In this case the match would be 1010. I then need to do the same for the remainder of the binary data. The bit strings can be up to 16 bits long and cross the byte boundaries.
Basically, I'm trying to Huffman decode jpegs using the bit strings I created from the Huffman tables in the headers. I can do it, only it's very messy, I'm turning everything, binary data included, into Stringbuffers first and I know that isn't the right way.
Before I loaded everything in string buffers I tried using just numbers in binary but of course I can't ignore the leading 0s in a code like 00011. I'm sure there must be some clever way using bit wise operators and the like to do this, but I've been staring at pages explaining bit masks and leftwise shifts etc and I still don't have a clue!
Thanks a lot for any help!
EDIT:
Thanks for all the suggestions. I've gone with the binary tree approach as it seems to be the standard way with Huffman stuff. Makes sense really as Huffman codes are created using trees. I'll also look into to storing the binary data I need to search in a big integer. Don't know how to mark multiple answers as correct, but thanks all the same. | Since you are decoding Huffman encoded-data, you should create a binary tree, where leaves hold the decoded bit string as data, and the bits of each Huffman code are the path to the corresponding data. The bits of the Huffman code are accessed with bit-shift and bit-mask operations. When you get to a leaf, you output the data at that leaf and go back to the root of the tree. It's very fast and efficient. | You might use a state machine consuming zeros and ones. The state machine would have final states for all the patterns that you want to detect. Whenever it enters one of the final states, is sends a message to you with the matched pattern and goes back to the initial state.
Finally you would have only one state machine in form of a DAG which contains all your patterns.
To implement it use the state pattern (<http://en.wikipedia.org/wiki/State_pattern>) or any other implementation of a state machine. | How best to search binary data for variable length bit strings? | [
"",
"java",
"jpeg",
"huffman-code",
""
] |
```
function outputscores($mysqlquery,$reverse=false)
{
while($row = mysql_fetch_array($mysqlquery))
{
echo '<img src="img/date.png" /> ' . date("j M Y",strtotime($row['timestamp'])) . '
<img src="img/time.png" /> ' . date("H:i:s",strtotime($row['timestamp'])) . '
<img src="img/star.png" /> '.$row['score'].$_GET["scoretype"].'<br />';
}
}
```
I need to reverse the array if $reverse is set to true, but PHP says that the `mysql_fetch_array`'s output is not a valid array. Neither is $mysqlquery itself.
Is there any help?
Wow I've asked so many questions today .\_.
**EDIT**
```
$result = mysql_query("SELECT * FROM $gid LIMIT 25") or throwerror(mysql_error());
outputscores($result);
```
**EDIT2**
Another possible call:
```
$result = mysql_query("SELECT * FROM ".$gid.",users WHERE users.lastcheck < ".$gid.".timestamp") or throwerror(mysql_error());
outputscores($result);
``` | Edit: Change your sql query to this:
```
$mysqlquery="SELECT * FROM $gid";
```
Change your function to this:
```
function outputscores($mysqlquery,$reverse=false)
{
if ($reverse==true)
$mysqlquery.=" ORDER BY id DESC LIMIT 25";
else
$mysqlQuery.=" LIMIT 25";
$result=mysql_query($mysqlquery);
while($row = mysql_fetch_array($result))
{
//Do output here
}
}
```
Here, by adding the words `ORDER BY id DESC` you will make the records be ordered in descending order of the 'id' column in your table. By typing `ASC` instead of `DESC` you can have them ordered in ascending order. Also, you can replace 'id' with any other column from your table, for example `timestamp`, `score`, etc.
Edit: Alternatively, you could also make a different function for adding the `LIMIT` and `ORDER BY` clause to the query. Then you could do something like this:
```
$reverse=false;//or true
$mysqlquery=addOrderBy("SELECT * FROM $gid",$reverse);
outputScores($mysqlquery);
``` | You are propably trying to reverse the whole resultset, try something like this:
```
function outputscores($mysqlres,$reverse=false)
{
$results = array();
while($row = mysql_fetch_array($mysqlres)){
print('I found a result: <pre>'.print_r($row, false).'</pre>'); //debugging purposes
$results[] = $row;
}
if($reverse) { $results = array_reverse($results); }
foreach($results as $row)
{
echo '<img src="img/date.png" /> ' . date("j M Y",strtotime($row['timestamp'])) . '
<img src="img/time.png" /> ' . date("H:i:s",strtotime($row['timestamp'])) . '
<img src="img/star.png" /> '.$row['score'].$_GET["scoretype"].'<br />';
}
}
```
Oh yes indeed as soulmerge says, you should feed the function a mysql resource and not an actual query. Thus like this:
```
$query = "SELECT field FROM table";
$res = mysql_query($query);
output_scores($res, true);
```
In regard to your comment, make sure your query is actually returning results, test it in phpMyAdmin or something or add a simple print in the while loop as I did above. | Reversing mysql_fetch_array() | [
"",
"php",
"mysql",
""
] |
I can't seem to figure this one out. I have the following XML file:
```
<?xml version="1.0" encoding="UTF-8"?>
<targets>
<showcases>
<building name="Big Blue" />
<building name="Shiny Red" />
<building name="Mellow Yellow" />
</showcases>
</targets>
```
I need to be able to test whether or not a `<building>` node exists with a given name. Everything I seem to find on Google tells me to do something like the following:
```
$xdoc->getElementsByTagName('building')->item(0)->getAttributeNode('name')
```
... but if I understand that correctly, doesn't that only test the first `<building>` node? `item(0)`? Do I need to use XQuery for this?
I'd appreciate some help! Thanks! | I'd suggest the following (PHP using ext/simplexml and XPath):
```
$name = 'Shiny Red';
$xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?>
<targets>
<showcases>
<building name="Big Blue" />
<building name="Shiny Red" />
<building name="Mellow Yellow" />
</showcases>
</targets>');
$nodes = $xml->xpath(sprintf('/targets/showcases/building[@name="%s"]', $name);
if (!empty($nodes)) {
printf('At least one building named "%s" found', $name);
} else {
printf('No building named "%s" found', $name);
}
``` | Okay, looks like XPath was what I wanted. Here's what I came up with that does what I want:
```
<?php
$xmlDocument = new DOMDocument();
$nameToFind = "Shiny Red";
if ($xmlDocument->load('file.xml')) {
if (checkIfBuildingExists($xmlDocument, $nameToFind)) {
echo "Found a red building!";
}
}
function checkIfBuildingExists($xdoc, $name) {
$result = false;
$xpath = new DOMXPath($xdoc);
$nodeList = $xpath->query('/targets/showcases/building', $xdoc);
foreach ($nodeList as $node) {
if ($node->getAttribute('name') == $name) {
$result = true;
}
}
return $result;
}
?>
``` | PHP: Check if XML node exists with attribute | [
"",
"php",
"xml",
"xpath",
""
] |
According to MSDN SQL BOL (Books Online) page on [Deterministic and Nondeterministic Functions](http://msdn.microsoft.com/en-us/library/ms178091.aspx), non-deterministic functions can be used "*in a deterministic manner*"
> The following functions are not always deterministic, but can be used in indexed views or indexes on computed columns when they are specified in a deterministic manner.
What does it mean by non-deterministic functions can be used **in a deterministic manner**?
Can someone illustrate **how** that can be done? and **where** you would do so? | the BOL actually states:
> The following functions are **not
> always deterministic**, but can be
> used in indexed views or indexes on
> computed columns when they are
> specified in a deterministic manner.
and then below it states what conditions must be met to make them deterministic.
E.g.
> CAST - Deterministic unless used with
> datetime, smalldatetime, or
> sql\_variant
In other words you need to meet those condition to use them in *deterministic manner*
For example when you create a table
```
CREATE TABLE [dbo].[deterministicTest](
[intDate] [int] NULL,
[dateDateTime] [datetime] NULL,
[castIntToDateTime] AS (CONVERT([datetime],[intDate],0)),
[castDateTimeToInt] AS (CONVERT([int],[dateDateTime],0)),
[castIntToVarchar] AS (CONVERT([varchar],[intDate],0))
) ON [PRIMARY]
```
you can apply index on castIntToVarchar but if you try to add index to castDateTimeToInt or castIntToDateTime you will get the following error:
*Column 'castDateTimeToInt'(castIntToDateTime) in table 'dbo.deterministicTest' cannot be used in an index or statistics or as a partition key because it is non-deterministic.*
So the dateTime cannot be used neither as a source nor the target format of the CONVERT function if you want to stay deterministic | That a function is deterministic means that it is guaranteed always to return the same output value for the same input arguments.
Using a non-deterministic function in a deterministic manner I assume means that you ensure that the range of arguments you will pass to the function is such that the return value will be deterministic, ie. dependent only opon those arguments.
What this implies in practice depends on what the function does and in what way it is non-deterministic. | What does it mean by "Non-deterministic User-Defined functions can be used in a deterministic manner"? | [
"",
"sql",
"sql-server",
"user-defined-functions",
"deterministic",
"non-deterministic",
""
] |
I'm using C# in Visual Studio 2008 with .NET 3.5.
I have a generic dictionary that maps types of events to a generic list of subscribers. A subscriber can be subscribed to more than one event.
```
private static Dictionary<EventType, List<ISubscriber>> _subscriptions;
```
To remove a subscriber from the subscription list, I can use either of these two options.
Option 1:
```
ISubscriber subscriber; // defined elsewhere
foreach (EventType event in _subscriptions.Keys) {
if (_subscriptions[event].Contains(subscriber)) {
_subscriptions[event].Remove(subscriber);
}
}
```
Option 2:
```
ISubscriber subscriber; // defined elsewhere
foreach (EventType event in _subscriptions.Keys) {
_subscriptions[event].Remove(subscriber);
}
```
I have two questions.
First, notice that Option 1 checks for existence before removing the item, while Option 2 uses a brute force removal since Remove() does not throw an exception. Of these two, which is the preferred, "best-practice" way to do this?
Second, is there another, "cleaner," more elegant way to do this, perhaps with a lambda expression or using a LINQ extension? I'm still getting acclimated to these two features.
Thanks.
## EDIT
Just to clarify, I realize that the choice between Options 1 and 2 is a choice of speed (Option 2) versus maintainability (Option 1). In this particular case, I'm not necessarily trying to optimize the code, although that is certainly a worthy consideration. What I'm trying to understand is if there is a generally well-established practice for doing this. If not, which option would you use in your own code? | Option 1 will be slower than Option 2. Lambda expressions and LINQ will be slower. I would use `HashSet<>` instead of `List<>`.
If you need confirmation about item removal, then `Contains` has to be used.
EDITED:
Since there is a high probabilty of using your code inside `lock` statement, and best practice is to reduce time of execution inside `lock`, it may be useful to apply Option 2. It looks like there is no best practice to use or not-use `Contains` with `Remove`. | The Remove() method 'approches O(1)' and is OK when a key does not exist.
But otherwise: when in doubt, measure. Getting some timings isn't that difficult... | Best Practice - Removing item from generic collection in C# | [
"",
"c#",
"generics",
".net-3.5",
""
] |
Need to move some code from MySql to TSql. I have a couple of calls to INET\_ATON which converts a string which resembles an IPAddress into a number. Is there a T-SQL equivalent? | An abuse of the parsname function:
```
create function INET_ATON (@addr varchar(15))
returns bigint
with schemabinding
as
begin
return
cast(parsename(@addr, 4) as bigint) * 16777216 +
cast(parsename(@addr, 3) as bigint) * 65536 +
cast(parsename(@addr, 2) as bigint) * 256 +
cast(parsename(@addr, 1) as bigint)
end
```
That "short form address" thing is not supported here though. | Here's a function to convert an IP address to a string:
```
CREATE FUNCTION dbo.IpToString
(@ip_str VarChar(15))
returns BigInt
as
begin
declare @i int
declare @dot_pos int
declare @current_part VarChar(15)
declare @result BigInt
set @result = 0
set @i = 0
while Len(@ip_str) > 0
begin
set @i = @i + 1
set @dot_pos = CharIndex('.', @ip_str)
if @dot_pos > 0
begin
set @current_part = Left(@ip_str, @dot_pos - 1)
set @ip_str = SubString(@ip_str, @dot_pos + 1, 15)
end
else
begin
set @current_part = @ip_str
set @ip_str = ''
end
if Len(@current_part) > 3 Return(Null)
if IsNumeric(@current_part) = 0 Return (Null)
if not cast(@current_part as int) between 0 and 255 Return (Null)
set @result = 256 * @result + Cast(@current_part as BigInt)
end
if @i = 4 Return(@result)
Return(Null)
end
```
After creating the function, you can call it like:
```
select dbo.IpToString('1.2.3.4')
``` | Porting from MySql to T-Sql. Any INET_ATON() equivalent? | [
"",
"sql",
"mysql",
"t-sql",
""
] |
I'm trying to execute two SQL statements in one mysql\_query.
```
$mySql = mysql_query("SELECT itemid, points FROM items WHERE id='1' UPDATE accounts SET userpoints = '1000'");
```
Is this possible? Thanks! | You can only execute one query in `mysql_query` (even if you seperate the queries with the semicolon terminator).
You have to call them seperately (although [this guy](http://www.dev-explorer.com/articles/multiple-mysql-queries) has a method to automate that). | If you use mysqli you can use [`mysqli_multi_query()`](http://us.php.net/manual/en/mysqli.multi-query.php) | INSERT Statement after a SELECT in mysql_query | [
"",
"php",
"mysql",
""
] |
I’m looking for XML Diff class or library. There are my requirements:
- open source :)
- object model for output (\*)
- rather fast (for 4mb XML)
I'm trying to use MS XML Diff and Patch Tools, but I wanna get a list of objects with differences of 2 XML files (instead HTML markup).
---
UPD: Thanks for all of your responses. I implemented my own solution; it’s not too hard with Linq2Xml :)
UPD2: Sorry guys, but i can't post my solution here now (i actually haven't got it because i have changed my work recently). Also my solution have some specific parts, so it can't suit common problems any way. The main advice is to use Linq2Xml, implement your logic and have fun :) | I did some research on this topic.
[Tool or library for comparing xml files](https://stackoverflow.com/questions/547399/tool-or-library-for-comparing-xml-files) | Not quite sure from you post if you are tring to do this in code or not.
But if you are just after a nice programe to view the two documents side by side and see the difreances and make changes to them i would recomend [Beyond Compare 3](http://www.scootersoftware.com/). | Free C# XML Diff library or class | [
"",
"c#",
"xml",
"diff",
""
] |
I'm very much **not** a javascript/html/css person.
Even so I find myself in the position of having to do a webpage. It's static the only thing you can do on it is click on flags to change dispay-language based on a cookie.
If the cookie says "this" I write text in one language, and if the cookie says "that" I write in another language. This works perfectly but I have to use **lots** of document.write statements and it's ugly and cumbersome.
Right now I type the text I want and use a macro in emacs to fold the text at about
80 chars and put `document.write("` in the beginning of each line and `");` at the end. I then paste it into the web page in a `if(cookie_this) { } else { }`.
There must be a better way to do it... Please?
**Edit**:
I was looking workaround for the limitations in document.write
Constraints:
* No server side magic, that means no ruby/php/perl
* One page only, or rather only one visible url
* The solution should be simpler than the working one I have | Expanding on [artlung's answer](https://stackoverflow.com/questions/648602/how-write-to-page-without-document-write-length-limitation/648637#648637):
You can display or hide things given a `lang` attribute (or any other criteria, such as a class name). In jQuery and HTML:
```
<p>Language:
<select id="languageSelector">
<option value="en">English</option>
<option value="es">Español</option>
</select>
</p>
<div lang="en-us">
Hello
</div>
<div lang="es">
Hola
</div>
<script type="text/javascript">
var defaultLanguage = 'en';
var validLanguages = ['en', 'es'];
function setLanguage(lang, setCookie) {
if(!$.inArray(languages, lang))
lang = defaultLang;
if(typeof(setCookie) != 'undefined' && setCookie) {
$.cookie('language', lang);
}
// Hide all things which can be hidden due to language.
$('*[lang]').filter(function() { return $.inArray(languages, $(this).attr('lang')); }).hide();
// Show currently selected language.
$('*[lang^=' + lang + ']).show();
}
$(function() {
var lang = $.cookie('language'); // use jQuery.cookie plugin
setLanguage(lang);
$('#languageSelector').change(function() {
setLanguage($(this).val(), true);
});
});
</script>
``` | jQuery can do this with I lot less ease, but you could create an element then set that elements innerHTML property. You may have to change your call slightly so that you append the child element. See [createElement](http://www.google.com/search?q=document.createElement) function for more info. For example
```
<script type="text/javascript">
function writeElement(language, elementId) {
var newElement = document.createElement("span");
if (language = "this") {
newElement.innerHTML = "text for this";
}
else {
newElement.innerHTML = "text for that";
}
var element = document.getElementById(elementId);
element.appendChild(newElement);
}
</script>
```
**Usage**
```
<span id="data1"></span>
<script type="text/javascript">
writeElement("this", "data1")
</script>
```
Add a comment if you can support jQuery and you want a sample of that instead. | How write to page without document.write length limitation | [
"",
"javascript",
"html",
""
] |
Hi I am developing using the SharePoint namespace and I ran into the following error when I try to retrieve a Title field from the list items.
> Value does not fall within the expected range
I know however that the field exists because I printed out all the fields.
```
string value = (string)listItem[listItem.Fields["Title"].Id];
Console.WriteLine("Title = " + value);
```
**Update:** To what extent does the View that was used to retrieve the list items play a role in what fields will be available? This code fails with the same exception:
```
SPListItemCollection items = list.GetItems(list.DefaultView);
foreach (SPListItem listItem in items)
{
try
{
Console.WriteLine("Title = " + listItem.Title);
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
}
```
In both cases the list.DefaultView property was used to retrieve the list items. | I had this issue because the column was not part of the default view. Instead of relying on the view, query for the specific columns directly when creating the SPListItemCollection.
```
SPList cityList = web.Lists[cityListName];
SPListItemCollection items = cityList.GetItems("Title","LocCode");
foreach (SPListItem item in items)
{
cityName = item["Title"].ToString().Trim();
cityCode = item["LocCode"].ToString().Trim();
}
``` | I don't know if your error is solved or not. But I was facing the same issue and I found the solution to the problem.
You have to go to:
Central Administration > Application Management > Manage Web Applications
select the Web Application in use and choose:
“General Settings > Resource Throttling” via the Ribbon.
In that scroll down and look for "`List View Lookup Threshold`" in that by default value is `8` increase the value till the error is gone.
[Reference Link](http://sharepointjoint.com/2012/09/value-does-not-fall-within-the-expected-range/) | SharePoint ListItem Error: "Value does not fall within the expected range" | [
"",
"c#",
"sharepoint",
"sharepoint-2007",
""
] |
Is it ok to name my database tables that are already keywords? For my case, I am trying to name the table that will hold my users. I've named it **User** but it is showing up as pink in SQL Server Management Studio so I am assuming its an existing System Table or Keyword. Thanks for your advice.
Official list of reserved keywords: [Reserved Keywords (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms189822%28v=sql.105%29.aspx) | repeat this three times:
DO NOT DO IT, I WILL NOT USE RESERVED WORDS!
you'll thank me! | You can create tables with the same name as keywords. If you "quote" the table name it should work. The default quotes in SQL server are square brackets: []
```
CREATE TABLE [dbo].[user](
[id] [bigint] NOT NULL,
[name] [varchar](20) NOT NULL
) ON [PRIMARY]
``` | Creating table names that are reserved words/keywords in MS SQL Server | [
"",
"sql",
"sql-server",
""
] |
Consider the following code:
```
UInt32 val = 1;
UInt32 shift31 = val << 31; // shift31 == 0x80000000
UInt32 shift32 = val << 32; // shift32 == 0x00000001
UInt32 shift33 = val << 33; // shift33 == 0x00000002
UInt32 shift33a = (UInt32)((UInt64)val << 33); // shift33a == 0x00000000
```
It doesn't generate a warning (about using a shift greater than 32) so it must be an expected behavior.
The code that actually gets put out to the generated assembly (or at least Reflector's interpretation of the code) is
```
uint val = 1;
uint shift31 = val << 0x1f;
uint shift32 = val;
uint shift33 = val << 1;
uint shift33a = val << 0x21;
```
The IL (again, using Reflector) is
```
L_0000: nop
L_0001: ldc.i4.1
L_0002: stloc.0
L_0003: ldloc.0
L_0004: ldc.i4.s 0x1f
L_0006: shl
L_0007: stloc.1
L_0008: ldloc.0
L_0009: stloc.2
L_000a: ldloc.0
L_000b: ldc.i4.1
L_000c: shl
L_000d: stloc.3
L_000e: ldloc.0
L_000f: conv.u8
L_0010: ldc.i4.s 0x21
L_0012: shl
L_0013: conv.u4
L_0014: stloc.s shift33a
```
I understand **what** is going on (it's described in [MSDN](http://msdn.microsoft.com/en-us/library/aa691377.aspx)); when the code is compiled, only the lower 5 bits are being used when shifting a 32-bit value... I'm curious as to **why** this happens.
(The way `shift33a` comes out also makes me think that something isn't quite right with Reflector, as their c# presentation of the IL will compile to something different)
**The question(s):**
* **Why** are only the lower 5 bits of "the value to shift by" used?
* If "it doesn't make sense to shift more than 31 bits", why isn't there a warning?
* Is this a backwards compatilbility thing (i.e. is this what programmers "expect" to happen)?
* Am I correct that the underlying IL can do shifts of more than 31 bits (as in `L_0010: ldc.i4.s 0x21`) but the compiler is trimming the values? | It basically boils down to the way the x86 handles the arithmetic shift opcodes: it only uses the bottom 5 bits of the shift count. See the [80386 programming guide](http://pdos.csail.mit.edu/6.828/2008/readings/i386/SAL.htm), for example. In C/C++, it's technically undefined behavior to do a bit shift by more than 31 bits (for a 32-bit integer), going with the C philosophy of "you don't pay for what you don't need". From section 6.5.7, paragraph 3 of the C99 standard:
> The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. If the value of the right operand is negative or is
> greater than or equal to the width of the promoted left operand, the behavior is undefined.
This allows compilers to omit a single shift instruction on x86 for shifts. 64-bit shifts cannot be done in one instruction on x86. They use the [SHLD](http://pdos.csail.mit.edu/6.828/2008/readings/i386/SHLD.htm)/[SHRD](http://pdos.csail.mit.edu/6.828/2008/readings/i386/SHRD.htm) instructions plus some additional logic. On x86\_64, 64-bit shifts can be done in one instruction.
For example, gcc 3.4.4 emits the following assembly for a 64-bit left-shift by an arbitrary amount (compiled with `-O3 -fomit-frame-pointer`):
```
uint64_t lshift(uint64_t x, int r)
{
return x << r;
}
_lshift:
movl 12(%esp), %ecx
movl 4(%esp), %eax
movl 8(%esp), %edx
shldl %cl,%eax, %edx
sall %cl, %eax
testb $32, %cl
je L5
movl %eax, %edx
xorl %eax, %eax
L5:
ret
```
Now, I'm not very familiar with C#, but I'm guessing it has a similar philosophy -- design the language to allow it to be implemented as efficiently as possible. By specifying that shift operations only use the bottom 5/6 bits of the shift count, it permits the JIT compiler to compile the shifts as optimally as possible. 32-bit shifts, as well as 64-bit shifts on 64-bit systems, can get JIT compiled into a single opcode.
If C# were ported to a platform that had different behavior for its native shift opcodes, then this would actually incur an extra performance hit -- the JIT compiler would have to ensure that the standard is respected, so it would have to add extra logic to make sure only the bottom 5/6 bits of the shift count were used. | Unit32 overflows at 32 bits, that is defined in the spec. What are you expecting?
The CLR does not define a left shift with overflow detection operator(1). If you need that kind of facility you need to check for yourself.
(1) The C# compiler might cast it to long, but I am not sure. | Why use only the lower five bits of the shift operand when shifting a 32-bit value? (e.g. (UInt32)1 << 33 == 2) | [
"",
"c#",
"bit-shift",
""
] |
Every time I do anything, and my while(1) gets called in my main function, my file gets cleared. It's driving me crazy. I've tried EVERYTHING. I try to put my ofstream out("data.dat"); outside the while(1) statement so it isn't called everytime but then nothing is written to the file like the ofstream isn't even working!
I've tried to make the ofstream static, so it isn't called over and over again like:
```
static ofstream open("data.dat");
```
That doesn't work.
And like I said, when I put the ofstream OUTSIDE the while statement, nothing is written to the file. Like:
```
ofstream out("data.dat");
while (1)
{
string line = "";
cout << "There are currently " << structList.size() << " items in memory.";
cout << endl << endl;
cout << "Commands: " << endl;
cout << "1: Add a new record " << endl;
cout << "2: Display a record " << endl;
cout << "3: Edit a current record " << endl;
cout << "4: Delete a record " << endl;
cout << "5: Save current information " << endl;
cout << "6: Exit the program " << endl;
cout << endl;
cout << "Enter a command 1-6: ";
getline(cin , line);
int rValue = atoi(line.c_str());
system("cls");
switch (rValue)
{
case 1:
structList = addItem(structList);
break;
case 2:
displayRecord(structList);
break;
case 3:
structList = editRecord(structList);
break;
case 4:
deleteRecord(structList);
break;
case 5:
if (!structList.size()) { cout << "There are no items to save! Enter one first!" << endl << endl; system("pause"); system("cls"); break; }
writeVector(out , structList);
break;
case 6:
return 0;
default:
cout << "Command invalid. You can only enter a command number 1 - 6. Try again. " << endl;
}
out.close();
}
```
And can someone tell me why my check to prevent reading of a empty file won't work?
**My Check:**
```
bool checkFileEmpty()
{
ifstream in("data.dat");
if (in.peek() == in.eofbit)
{
return true;
}
return false;
}
```
I am so sick and tired of my program crashing on startup over and over again because my vector is getting set to a size of 200 million. I've tried a BUNCH of stuff for this... none of it works... Please GOD someone help me with both of these! I've been up for 18 hours working on this ( all night yes ) and i'm ALMOST done. I'm begging you....
**My Code:**
```
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace System;
using namespace std;
#pragma hdrstop
bool isValidChoice(int size, int choice);
bool checkFileEmpty();
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec);
template<typename T>
vector<T> readVector(ifstream &in);
template<typename T>
vector<T> addItem(vector<T> &vec);
template<typename T>
void printItemDescriptions(vector<T> &vec);
template<typename T>
int displayRecord(vector<T> &vec);
template<typename T>
vector<T> editRecord(vector<T> &vec);
template<typename T>
vector<T> deleteRecord(vector<T> &vec);
struct InventoryItem {
string Description;
int Quantity;
int wholesaleCost;
int retailCost;
string dateAdded;
} ;
int main(void)
{
cout << "Welcome to the Inventory Manager extreme! [Version 1.0]" << endl;
ifstream in("data.dat");
if (in.is_open()) { cout << "File \'data.dat\' has been opened successfully." << endl; } else { cout << "Error opening data.dat" << endl;}
cout << "Loading data..." << endl;
vector<InventoryItem> structList = readVector<InventoryItem>( in );
cout <<"Load complete." << endl << endl;
in.close();
while (1)
{
string line = "";
cout << "There are currently " << structList.size() << " items in memory.";
cout << endl << endl;
cout << "Commands: " << endl;
cout << "1: Add a new record " << endl;
cout << "2: Display a record " << endl;
cout << "3: Edit a current record " << endl;
cout << "4: Delete a record " << endl;
cout << "5: Save current information " << endl;
cout << "6: Exit the program " << endl;
cout << endl;
cout << "Enter a command 1-6: ";
getline(cin , line);
int rValue = atoi(line.c_str());
system("cls");
ofstream out("data.dat");
switch (rValue)
{
case 1:
structList = addItem(structList);
break;
case 2:
displayRecord(structList);
break;
case 3:
structList = editRecord(structList);
break;
case 4:
deleteRecord(structList);
break;
case 5:
if (!structList.size()) { cout << "There are no items to save! Enter one first!" << endl << endl; system("pause"); system("cls"); break; }
writeVector(out , structList);
break;
case 6:
return 0;
default:
cout << "Command invalid. You can only enter a command number 1 - 6. Try again. " << endl;
}
out.close();
}
system("pause");
return 0;
}
template<typename T>
void writeVector(ofstream &out, const vector<T> &vec)
{
out << vec.size();
for(vector<T>::const_iterator i = vec.begin(); i != vec.end(); i++)
{
out << *i;
}
cout << "Save completed!" << endl << endl;
}
ostream &operator<<(ostream &out, const InventoryItem &i)
{
out << i.Description << ' ';
out << i.Quantity << ' ';
out << i.wholesaleCost << ' ' << i.retailCost << ' ';
out << i.dateAdded << ' ';
return out;
}
istream &operator>>(istream &in, InventoryItem &i)
{
in >> i.Description;
in >> i.Quantity;
in >> i.wholesaleCost >> i.retailCost;
in >> i.dateAdded;
return in;
}
template<typename T>
vector<T> readVector(ifstream &in)
{
size_t size;
if (checkFileEmpty())
{
size = 0;
} else {
in >> size;
}
vector<T> vec;
vec.reserve(size);
for(unsigned int i = 0; i < size; i++)
{
T tmp;
in >> tmp;
vec.push_back(tmp);
}
return vec;
}
template<typename T>
vector<T> addItem(vector<T> &vec)
{
system("cls");
string word;
unsigned int number;
InventoryItem newItem;
cout << "-Add a new item-" << endl << endl;
cout << "Enter the description for the item: ";
getline (cin , word);
newItem.Description = word;
cout << endl;
cout << "Enter the quantity on hand for the item: ";
getline (cin , word);
number = atoi(word.c_str());
newItem.Quantity = number;
cout << endl;
cout << "Enter the Retail Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
newItem.retailCost = number;
cout << endl;
cout << "Enter the Wholesale Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
newItem.wholesaleCost = number;
cout << endl;
cout << "Enter current date: ";
getline (cin , word);
newItem.dateAdded = word;
vec.push_back(newItem);
return vec;
}
template<typename T>
void printItemDescriptions(vector<T> &vec)
{
int size = vec.size();
if (size)
{
cout << "---------------------------------" << endl;
cout << "| ~ Item Descriptions ~ |" << endl;
cout << "---------------------------------" << endl;
cout << "*********************************" << endl;
for (int i = 0 ; i < size ; i++)
{
cout << "(" << i+1 << ")" << ": " << vec[i].Description << endl;
}
cout << "*********************************" << endl << endl;
}
}
template<typename T>
int displayRecord(vector<T> &vec)
{
string word = "";
string quit = "quit";
int choice = 1;
int size = vec.size();
if (size)
{
printItemDescriptions(vec);
cout << endl;
while (1)
{
cout << "Type \"exit\" to return to the Main Menu." << endl << endl;
cout << "Enter \"list\" to re-display the items." << endl << endl;
cout << endl;
cout << "Pick the number of the item you would like to display: ";
getline (cin , word);
if (convertToLower(word) == "exit") { system("cls"); return 0; }
if (convertToLower(word) == "list") { system("cls"); displayRecord(vec); }
choice = atoi(word.c_str());
choice -= 1;
if (isValidChoice(size, choice))
{
system("cls");
cout << endl << "[Item (" << choice << ") details] " << endl << endl;
cout << "******************" << endl;
cout << "* Description * " << vec[choice].Description << endl;
cout << "******************" << endl << endl;
cout << "******************" << endl;
cout << "*Quantity On Hand* " << vec[choice].Quantity << endl;
cout << "******************" << endl << endl;
cout << "******************" << endl;
cout << "* Wholesale Cost * " << vec[choice].wholesaleCost << endl;
cout << "****************** " << endl << endl;
cout << "******************" << endl;
cout << "* Retail Cost * " << vec[choice].retailCost << endl;
cout << "****************** " << endl << endl;
cout << "******************" << endl;
cout << "* Data Added * " << vec[choice].dateAdded << endl;
cout << "****************** " << endl << endl;
} else { system("cls"); cout << "That item doesn't exist!" << endl; cout << "Pick another item or enter \"list\" to see available items." << endl << endl; }
}
} else { cout << "There are currently no items to display." << endl << endl; system("pause"); system("cls"); return 0; }
return 1;
}
bool isValidChoice(int size, int choice)
{
for (int i = 0 ; i <= size ; i++)
{
if (choice == i) { return true; }
}
return false;
}
string convertToLower(string word)
{
for (unsigned int i = 0 ; i < word.size() ; i++)
{
word[i] = tolower(word[i]);
}
return word;
}
bool checkFileEmpty()
{
ifstream in("data.dat");
if (in.peek() == in.eofbit)
{
return true;
}
return false;
}
template<typename T>
vector<T> editRecord(vector<T> &vec)
{
string word;
int choice;
printItemDescriptions(vec);
cout << "Choose item to edit: ";
getline ( cin, word );
choice = atoi(word.c_str());
system("cls");
unsigned int number;
InventoryItem newItem;
cout << "-Edit an item-" << endl << endl;
cout << "Enter the description for the item: ";
getline (cin , word);
vec[choice-1].Description = word;
cout << endl;
cout << "Enter the quantity on hand for the item: ";
getline (cin , word);
number = atoi(word.c_str());
vec[choice-1].Quantity = number;
cout << endl;
cout << "Enter the Retail Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
vec[choice-1].retailCost = number;
cout << endl;
cout << "Enter the Wholesale Cost for the item: ";
getline (cin , word);
number = atoi(word.c_str());
vec[choice-1].wholesaleCost = number;
cout << endl;
cout << "Enter current date: ";
getline (cin , word);
vec[choice-1].dateAdded = word;
system("cls");
cout << "Item edited successfully! " << endl;
return vec;
}
template<typename T>
vector<T> deleteRecord(vector<T> &vec)
{
if (!vec.size()) { cout << "There are no items to delete!" << endl << endl; return vec; }
printItemDescriptions(vec);
string word;
int choice;
cout << "Choose item to delete: ";
getline( cin, word);
choice = atoi(word.c_str());
vec.erase (vec.begin()+choice-1);
return vec;
}
``` | You'd better move the ofstream openning and closing inside case 5.
Here you create a new file at each while iteration.
```
case 5:
{
ofstream out("data.dat");
writeVector(out , structList);
out.close();
}
break;
``` | ```
ofstream out("data.dat");
```
Opens the file for writing. By default, it will start at the very beginning wiping out anything that was there previously. First, use a different output file than the file you are reading from. | Why won't my ofstream work when I put it outside my while statement? | [
"",
"c++",
"serialization",
"file-io",
"fstream",
""
] |
I frequently have code that looks something like this:
```
if (itm != null)
{
foreach (type x in itm.subItems())
{
//dostuff
}
}
//do more stuff
```
In situations where `//do more stuff` is omitted, it is very easy to avoid the extra foreach loop. By exitting scope using the appropriate command (depending on what is going on, this generally would mean a `return` statement or a `continue statement`).
This type of thing tends to result in arrow code. I currently have a few ways to deal with this:
* Use code like `itm = itm == null ? itm.subItems() : emptyArray`
* Allow arrow code
* Use `goto`
* Use evil scoping hacks (wrapping the whole thing, if statement in all, in a scope and then breaking out of it). In my opinion evil scoping hacks are basically equivalent to `goto` except uglier and harder to read, so I don't consider this a valid solution.
* Refactor some of the chunks into new methods. There are in fact a few cases where this probably **is** a good solution, but mostly it's not appropriate since the null references are mainly error conditions from MS-functions.
Anyone care to offer a response on what approaches are considered preferable? | If you're using C# 3, you could always write an extension method:
```
public static IEnumerable<SubItem> SafeSubItems(this ItemType item)
{
return item == null ? Enumerable.Empty<SubItem> : source.SubItems();
}
```
Then just write:
```
foreach (SubItem x in itm.SafeSubItems())
{
// do stuff
}
// do more stuff
```
The key thing is that extension methods can be called even "on" null references.
What would be nice would be a "null-safe dereferencing" operator, so we could write:
```
// Not valid C# code!
foreach (SubItem x in itm?.SubItems() ?? Enumerable.Empty<SubItem>())
{
}
```
Or just define an `EmptyIfNull` extension method on `IEnumerable<T>` and use
```
// Not valid C# code!
foreach (SubItem x in (itm?.SubItems()).EmptyIfNull())
{
}
``` | You could use the [Coalesce](http://msdn.microsoft.com/en-us/library/ms173224.aspx "Coalesce") operator (coded as a double question mark, ??, .net 2 upwards). This'll return the first non-null value in a list of values, so in this snippet...
```
MyClass o1 = null;
MyClass o2 = new MyClass ();
MyClass o3 = null;
return o1 ?? o2 ?? o3;
```
...o2 would be returned.
So you could re-code your original code sample as
```
foreach (type x in (itm ?? emptyArray).subItems())
{
//dostuff
}
//do more stuff
```
However, personally I don't mind the nesting. It's instantly clear what's going on. I find the Coalesce operator a little harder to read, and that little nest is a small price to pay for clarity. | C# Code Simplification Query: The Null Container and the Foreach Loop | [
"",
"c#",
""
] |
Is there any way for a C++ programmer with 1,5 years of experience to have no idea that null-terminated strings exist as a concept and are widely used in a variety of applications? Is this a sign that he is potentially a bad hire? | What does he use -- `std::string` only? Does he know about string literals? What is his take on string literals?
There's too little detail to tell you if he's a bad hire, but he sounds like he needs a bit more talking to than most. | > Is there any way for a C++ programmer
> with 1,5 years of experience to have
> no idea that NULL-terminated strings
> exist as a concept and are widely used
> in a variety of applications?
No. What have he/she been doing for these 1,5 years?
> Is this a sign that he is potentially
> a bad hire?
Yes. Knowledge of C should be mandatory for a C++ programmer. | Is it acceptable for a C++ programmer to not know how null-terminated strings work? | [
"",
"c++",
"string",
""
] |
I'm searching for existing scripts that will animate a vertical text menu by blurring text and zooming it according to the mouse pointer.
I'm trying to accomplish these actions:
1. OS X-like movement on mouse hover that can 'zoom' the text in and out
2. In an un-focused state, the text would be blurred
3. When a user moved their pointer closer to the text, the text would sharpen.
[Here's a Flash example](http://www.flashden.net/item/vertical-fisheye-menu/19994) that demonstrates some of the effects, but I'd really prefer to use JavaScript and not use 'down', 'up' and 'select' buttons, naturally. | I'm not sure that you can do this in Javascript... | Here is an open source script that I think could work for you (Or at least after minor modifications)
<http://marcgrabanski.com/pages/code/fisheye-menu>
And a tutorial on using it:
<http://simply-basic.com/tools/fisheye-menu-for-your-website/>
Edit:
I realized that the script above probably wouldn't handle text very well. Unfortunately blurring text is not easily done in javascript. It might be possible using the canvas element, but I was unable to find anything in a quick Google search and this would likely not be compatible with older browsers.
Here is another script that has a fisheye effect on text items in a list: <http://aleph-null.tv/article/20080522-1839-265.xml/Text-based-Fish-Eye-Effect>. This is probably closer to what you're looking for, but it's definitely not as smooth and doesn't allow you to blur text like flash does. | Blurring fisheye effect on a vertical text menu | [
"",
"javascript",
"menu",
"blur",
""
] |
I am looking for an easy way to convert some XAML animation to C# code. Is there any tool available to do that?
Thanks!
Wally
This is the code I am trying to convert:
```
<Storyboard x:Key="Storyboard1">
<Rotation3DAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetName="DefaultGroup"
Storyboard.TargetProperty="(Visual3D.Transform).(Transform3DGroup.Children)[2].(RotateTransform3D.Rotation)">
<SplineRotation3DKeyFrame KeyTime="00:00:04.0200000">
<SplineRotation3DKeyFrame.Value>
<AxisAngleRotation3D Angle="144.99999999999997" Axis="1,0,0"/>
</SplineRotation3DKeyFrame.Value>
</SplineRotation3DKeyFrame>
</Rotation3DAnimationUsingKeyFrames>
</Storyboard>
``` | This is the same code in c#:
```
Storyboard storyboard3 = new Storyboard();
storyboard3.AutoReverse = false;
Rotation3DAnimationUsingKeyFrames r3d = new Rotation3DAnimationUsingKeyFrames();
r3d.BeginTime = new TimeSpan(0, 0, 0, 0, 0);
r3d.Duration = new TimeSpan(0,0,0,1,0);
r3d.KeyFrames.Add(new SplineRotation3DKeyFrame(new AxisAngleRotation3D(new Vector3D(1,0,0),1)));
r3d.KeyFrames.Add(new SplineRotation3DKeyFrame(new AxisAngleRotation3D(new Vector3D(1, 0, 0), 37)));
r3d.Name = "r3d";
Storyboard.SetTargetName(r3d, "DefaultGroup");
Storyboard.SetTargetProperty(r3d, new PropertyPath("(Visual3D.Transform).(Transform3DGroup.Children)[2].(RotateTransform3D.Rotation)"));
storyboard3.Children.Add(r3d);
this.BeginStoryboard(storyboard3);
``` | You could use XamlReader.Load("") to parse it. Hope it helps :)
Edit:
```
StoryBoard myStoryBoard = (StoryBoard)XamlReader.Load("code");
``` | Is there any tool to convert from XAML to C# (code behind)? | [
"",
"c#",
"wpf",
"xaml",
""
] |
In Python, I'm used to being able to start a debugger at any point in the code, then poke around at live objects (call methods, that sort of thing). Is there any way, using NetBeans, to do this?
For example, I'd like to be able to break at the line `foo = bar().baz().blamo()` and run `bar()`, `bar().baz()` and `bar().baz().blamo()` to see what they do.
In Python, this is what I would do:
```
...
import pdb; pdb.set_trace()
foo = bar().baz().blamo()
```
Then it would give me a prompt where I could type things:
```
(pdb) bar()
... some objet ...
(pdb) bar() + 42
...
``` | First, set a breakpoint at that line of the code (by clicking in the left margin). Then click "Debug Main Project" (or "Debug single file" in the Debug menu).
Once you hit the breakpoint, you can use the tools in the Debug menu. In particular, "Evaluate Expression" seems to be what you're looking for. | In the debugger use the "Watches" view. In there you can add things to "watch", such as variables or expressions.
So if you had a "foo" object you could do things like watch "foo.bar()" and have it call the method.
I am not aware of any Java debuggers that have a real "scratchpad" sort of thing, but there probably is one. The "Watches" is about as close as you can get in Netbeans that I have found. | Use NetBeans to inspect live Java objects? | [
"",
"java",
"debugging",
"netbeans",
""
] |
What is your preferred scripting language in java world (scripting language on JVM) and way? When do you prefer your scripting language over java (in what situations for example for prototyping)? Do you use it for large projects or for personal projects only? | My favorite is Jython, and I use it by embedding a Jython interpreter in my Java application. It is being used in commercial projects, and it allows to easily customize the application according to the customers' needs without having to compile anything. Just send them the script, and that's it. Some customers might even customize their application themselves. | For me, [Clojure](http://clojure.org/) wins hands down. Being a Lisp, it's concise and dynamically typed, it has enormous expressive power so I can write a lot of functionality in a few lines. And its integration with Java is unsurpassed – I'm only partly joking when I say Clojure is more compatible to Java than Java itself. As a result, the entire breadth of Java libraries, both from the JDK and 3rd party, is fully useable.
Finally, with a little care Clojure code can be as fast as Java code, so I'm not even losing performance. | What is your preferred scripting language in java world (scripting language on JVM) and way? | [
"",
"java",
"scripting-language",
"jvm-languages",
""
] |
I'm writing a game, and I want to model its different states (the Game Maker analogy would be frames, I guess) in a clean, object-oriented way. Previously, I've done it in the following way:
```
class Game
{
enum AppStates
{
APP_STARTING,
APP_TITLE,
APP_NEWGAME,
APP_NEWLEVEL,
APP_PLAYING,
APP_PAUSED,
APP_ENDED
};
typedef AppState(Game::*StateFn)();
typedef std::vector<StateFn> StateFnArray;
void Run()
{
// StateFn's to be registered here
AppState lastState(APP_STARTING);
while(lastState != APP_ENDED)
{
lastState = GetCycle_(lastState);
}
// cleanup
}
protected:
// define StateFn's here
AppState GetCycle_(AppState a)
{
// pick StateFn based on passed variable, call it and return its result.
}
StateFnArray states_;
};
```
This was hardly manageble for a smaller project. All the variables that the states were using were dumped in the Game class, however I'd want to keep object-orientedness to a maximum, only exposing variables that are shared by more than one state. I also want to be able to initialize a new state when switching to it rather than having to do it in the state that's just finishing (as it might have multiple outcomes - APP\_PLAYING can switch to APP\_PAUSED, APP\_GAMEOVER, APP\_NEWLEVEL, etc.).
I thought of something like this (CAUTION! FUZZY STUFF!):
```
struct AppState
{
enum { LAST_STATE = -1; }
typedef int StateID;
typedef std::vector<AppState*> StateArray;
static bool Add(AppState *state, StateID desiredID);
// return false if desiredID is an id already assigned to
static void Execute(StateID state)
{
while(id != LAST_STATE)
{
// bounds check etc.
states_[id]->Execute();
}
}
AppState() {};
virtual ~AppState() {};
virtual StateID Execute() =0; // return the ID for the next state to be executed
protected:
static StageArray stages_;
};
```
The problem here is that the class and instance levels are getting jumbled up (static vs virtual). The states need to inherit from AppState, but - how I'd imagine - most of them would be classes with all-static members, or, at least I won't need more than one instance from one class (TitleState, LevelIntroState, PlayingState, GameOverState, EndSequenceState, EditorState... - pausing would no longer be a state, rather than being taken care of in the states where it makes sense).
How can it be done elegantly and efficiently? | The following article gives a nice, simple way to manage game states:
<http://gamedevgeek.com/tutorials/managing-game-states-in-c/>
Basically, you maintain a stack of game states, and just run the top state. You're right that many states would only have one instance, but this isn't really a problem. Actually, though, many of the states you're talking about could have multiple instances. E.g.:
```
push TitleState
push MenuState
push LevelIntroState
change_to PlayingState
change_to GameOverState
pop (back to MenuState)
```
... and you can start over with a new instance of `LevelIntroState`, and so on. | I'm using some type of [factory pattern](http://en.wikipedia.org/wiki/Factory_pattern) combined with a [state pattern](http://en.wikipedia.org/wiki/State_pattern) in my soon-to-be game.
The code might be a bit messy but I'll try to clean it up.
This is the class you'll derive all states from, like the menu, the game or whatever.
```
class GameState {
public:
virtual ~GameState() { }
virtual void Logic() = 0;
virtual void Render() = 0;
};
```
This class will be your interface for handling the different states. You can dynamically add and id dynamically.
```
class State {
public:
State();
virtual ~State();
void Init();
void Shutdown();
void SetNext( std::string next_state );
void Exit();
bool Logic();
void Render();
protected:
bool Change();
std::string state_id;
std::string next_state;
GameState *current_state;
std::vector<std::string> state_ids;
StateFactory *state_factory;
bool is_init;
};
```
I'm using a functor to handle the creation of different GameState derivatives.
```
class BasicStateFunctor {
public:
virtual GameState *operator ()() = 0;
};
template<class T>
class StateFunctor : public BasicStateFunctor {
public:
StateFunctor() { }
GameState *operator ()() {
return new T;
}
typedef T type;
};
```
Lastly a factory which will store and manage the different states.
```
class StateFactory {
public:
StateFactory();
virtual ~StateFactory();
bool CheckState( std::string id );
GameState *GetState( std::string id );
template<class T> void AddState( std::string id );
private:
typedef std::map<std::string, BasicStateFunctor*>::iterator StateIt;
std::map<std::string, BasicStateFunctor*> state_map;
};
```
In your definition file:
Here I did leave out a lot of stuff, but hopefully you'll get the idea.
```
bool StateFactory::CheckState( std::string id )
{
StateIt it = state_map.find( id );
if( it != state_map.end() )
return true;
else
return false;
}
GameState *StateFactory::GetState( std::string id )
{
StateIt it = state_map.find( id );
if( it != state_map.end() )
{
return (*(*it).second)();
} else {
//handle error here
}
template<class T> void StateFactory::AddState( std::string id )
{
StateFunctor<T> *f = new StateFunctor<T>();
state_map.insert( state_map.end(), std::make_pair( id, f ) );
}
void State::Init()
{
state_factory = new StateFactory();
state_factory->AddState<Game>( "game" );
current_state = state_factory->GetState( "game" );
is_init = true;
}
void State::SetNext( std::string new_state )
{
//if the user doesn't want to exit
if( next_state != "exit" ) {
next_state = new_state;
}
}
bool State::Change()
{
//if the state needs to be changed
if( next_state != "" && next_state != "exit" )
{
//if we're not about to exit( destructor will call delete on current_state ),
//call destructor if it's a valid new state
if( next_state != "exit" && state_factory->CheckState( next_state ) )
{
delete current_state;
current_state = state_factory->GetState( next_state );
}
else if( next_state == "exit" )
{
return true;
}
state_id = next_state;
//set NULL so state doesn't have to be changed
next_state = "";
}
return false;
}
bool State::Logic()
{
current_state->Logic();
return Change();
}
```
And here's how you use it:
Initialize and add the different states, I'm doing it in the Init().
```
State.Init();
//remember, here's the Init() code:
state_factory = new StateFactory();
state_factory->AddState<Game>( "game" );
current_state = state_factory->GetState( "game" );
is_init = true;
```
For the frame function
```
State.Logic(); //Here I'm returning true when I want to quit
```
And for the rendering function
```
State.Render();
```
This may not be perfect but it works fine for me.
To further advance the design you'd want to add Singleton for State and maybe make the StateFactory as a hidden class inside State. | How do you model application states? | [
"",
"c++",
"states",
""
] |
I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries).
```
d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
```
I want to update d1 so it looks like the following:
```
d1={key1:1, key2:[2,'A'], key3:3, key4:4}
```
Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web.
Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries?
I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary.
I can check to see if the two dictionaries have a common key:
```
for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
```
but if they do I can't seem to combine the values into a list.
More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries. | One good place to start is by getting iPython (`easy_install ipython`) then poking around with tab completion, `?` and `dir`:
```
In [2]: dir {}
------> dir({})
Out[2]:
['__class__',
...
'keys',
'pop',
'popitem',
'setdefault',
'update',
'values']
In [3]: {}.update?
Type: dict
Base Class: <type 'dict'>
String Form: {}
Namespace: Interactive
Length: 0
Docstring:
dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
d = {}
for k, v in seq:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
```
(just for example)
Anyway, your problem with checking keys common between the two dictionaries: there are a few things to consider (maybe look at the `set` class?), but here's how I'd do it:
```
common_keys = [k for k in dict1 if k in dict2]
```
(ie, "each key `k` in dict1 if that key is also in dict2")
(note, too, that testing for dictionary membership is an O(1) operation, so this will run in O(|dict1|))
**edit**: alright, so this doesn't solve the problem of merging the two dicts into one with lists... But Lott's answer is good for that, or you could use the `setdefault` method:
```
new = {}
for (k, v) in dict1.items():
new.setdefault(k, []).append(v)
for (k, v) in dict2.items():
new.setdefault(k, []).append(v)
``` | Try this:
```
import collections
merged = collections.defaultdict(list)
for k in d1:
merged[k].append( d1[k] )
for k in d2:
merged[k].append( d2[k] )
```
This may be what you're looking for.
Or possibly this.
```
import collections
merged = collections.defaultdict(set)
for k in d1:
merged[k].add( d1[k] )
for k in d2:
merged[k].add( d2[k] )
``` | Dictionaries in Python | [
"",
"python",
"dictionary",
""
] |
Under a given namespace, I have a set of classes which implement an interface. Let's call it `ISomething`. I have another class (let's call it `CClass`) which knows about `ISomething` but doesn't know about the classes which implement that interface.
I would like that `CClass` to look for all the implementation of `ISomething`, instantiate an instance of it and execute the method.
Does anybody have an idea on how to do that with C# 3.5? | A working code-sample:
```
var instances = from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces().Contains(typeof(ISomething))
&& t.GetConstructor(Type.EmptyTypes) != null
select Activator.CreateInstance(t) as ISomething;
foreach (var instance in instances)
{
instance.Foo(); // where Foo is a method of ISomething
}
```
**Edit** Added a check for a parameterless constructor so that the call to CreateInstance will succeed. | You can get a list of loaded assemblies by using this:
```
Assembly assembly = System.Reflection.AppDomain.CurrentDomain.GetAssemblies()
```
From there, you can get a list of types in the assembly (assuming public types):
```
Type[] types = assembly.GetExportedTypes();
```
Then you can ask each type whether it supports that interface by finding that interface on the object:
```
Type interfaceType = type.GetInterface("ISomething");
```
Not sure if there is a more efficient way of doing this with reflection. | How to find all the classes which implement a given interface? | [
"",
"c#",
"reflection",
""
] |
I decided to use Regex, now I have two problems :)
Given the input string "hello world [2] [200] [%8] [%1c] [%d]",
What would be an approprite pattern to match the instances of "[%8]" "[%1c]" + "[%d]" ? (So a percentage sign, followed by any length alphanumeric, all enclosed in square brackets).
for the "[2]" and [200], I already use
```
Regex.Matches(input, "(\\[)[0-9]*?\\]");
```
Which works fine.
Any help would be appreicated. | The Regex needed to match this pattern of "[%anyLengthAlphaNumeric]" in a string is this "[(%\w+)]"
The leading "[" is escaped with the "\" then you are creating a grouping of characters with the (...). This grouping is defined as %\w+. The \w is a shortcut for all word characters including letters and digits no spaces. The + matches one or more instances of the previous symbol, character or group. Then the trailing "]" is escaped with a "\" and catches the closing bracket.
Here is a basic code example:
```
string input = @"hello world [2] [200] [%8] [%1c] [%d]";
Regex example = new Regex(@"\[(%\w+)\]");
MatchCollection matches = example.Matches(input);
``` | ```
MatchCollection matches = null;
try {
Regex regexObj = new Regex(@"\[[%\w]+\]");
matches = regexObj.Matches(input);
if (matches.Count > 0) {
// Access individual matches using matches.Item[]
} else {
// Match attempt failed
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
``` | Regex help with sample pattern. C# | [
"",
"c#",
"regex",
""
] |
I want to enable a user on a website to upload an image, and write some text over it. Also, they should be able to crop/scale/move the image and text. For that stuff, I can do it in jQuery.
After they've made the image the way they want it, is there a way i can take a screenshot of that image (using PiL) and save it on the server?
What is the best/proper way to do this? | Taking a "screenshot" of the picture is neither the best, nor the proper way to do it. To take a screenshot, you need to execute code on the client machine, which is "not possible" in a website scenario.
Have a look at [lolcat builder](http://mine.icanhascheezburger.com/) (I can't think of a more serious example right now ;). Everytime you click the "Preview" button, the image src is updated with an url containing the text, its style and position. The request is handled by the server which will generate a new picture to display. | I assume you got Python on the server side.
The best way imo is to somehow 'get' all the editing parameters from the client, then re-render it using PIL.
Update: How I will do it
On the server side, you need an url to handle posts.
On the client side, (after each edit, )send a post to that url, with the editing parameters.
I think there is not an easy solution to this.
Maybe if you don't use PIL to render the final image, but only remember the parameters, each view from clients can render itself? | Using PiL to take a screenshot of HTML/CSS | [
"",
"jquery",
"python",
"css",
"xhtml",
"python-imaging-library",
""
] |
I'm trying to decompress about 8000 files in gzip format in Java. My first try was to use GZIPInputStream but the performance was awful.
Anyone know any alternative to decompress gzip archives? I tried ZipInputStream but it's not recognizing the gzip format.
Thank you in advance. | You need to use buffering. Writing small pieces of data is going to be inefficient. The compression implementation is in native code in the Sun JDK. Even if it wasn't the buffered performance should usually exceed reasonable file or network I/O.
```
OutputStream out = new BufferedOutputStream(new GZIPOutputStream(rawOut));
InputStream in = new BufferedInputStream(new GZIPInputStream(rawIn));
```
As native code is used to implement the decompression/compression algorithm, be very careful to close the stream (and not just the underlying stream) after use. I've found having loads of `Deflaters' hanging around is **very** bad for performance.
`ZipInputStream` deals with archives of files, which is a completely different thing from compressing a stream. | When you say that `GZipInputStream`'s performance was awful, could you be more specific? Did you find out whether it was a CPU bottleneck or an I/O bottleneck? Were you using buffering on both input and output? If you could post the code you were using, that would be very helpful.
If you're on a multi-core machine, you could try still using `GZipInputStream` but using multiple threads, one per core, with a shared queue of files still to process. (Any one file would only be processed by a single thread.) That *might* make things worse if you're I/O bound, but it may be worth a try. | Decompress a Gzip archive in Java | [
"",
"java",
"gzip",
"archive",
""
] |
My problem is, that I want to parse binary files of different types with a generic parser which is implemented in JAVA. Maybe describing the file format with a configuration file which is read by the parser or creating Java classes which parse the files according to some sort of parsing rules.
I have searched quite a bit on the internet but found almost nothing on this topic.
What I have found are just things which deal with compiler-generators (Jay, Cojen, etc.) but I don't think that I can use them to generate something for parsing binary files. But I could be wrong on that assumption.
Are there any frameworks which deal especially with easy parsing of binary files or can anyone give me a hint how I could use parser/compiler-generators to do so?
**Update**:
I'm looking for something where I can write a config-file like
```
file:
header: FIXED("MAGIC")
body: content(10)
content:
value1: BYTE
value2: LONG
value3: STRING(10)
```
and it generates automatically something which parses files which start with "MAGIC", followed by ten times the content-package (which itself consists of a byte, a long and a 10-byte string).
**Update2**:
I found something comparable what I'm looking for, "[Construct](http://construct.wikispaces.com/)", but sadly this is a Python-Framework. Maybe this helps someone to get an idea, what I'm looking for. | give a try to [preon](http://preon.sourceforge.net/) | Using [Preon](https://github.com/wspringer/preon):
```
public class File {
@BoundString(match="MAGIC")
private String header;
@BoundList(size="10", type=Body.class)
private List<Body> body;
private static class Body {
@Bound
byte value1;
@Bound
long value2;
@BoundString(size="10")
String value3;
}
}
```
Decoding data:
```
Codec<File> codec = Codecs.create(File.class);
File file = codecs.decode(codec, buffer);
```
Let me know if you are running into problems. | Are there any Java Frameworks for binary file parsing? | [
"",
"java",
"parsing",
"file-io",
"binary-data",
""
] |
Say that I have to following 2 routes in this order:
```
Zip:
url: home/:zip
param: { module: home, action: results }
State:
url: home/:state
param: { module: home, action: results }
```
and I use a route such as:
```
'@State?state=CA'
```
Why does it resolve to the Zip route?
I thought when you specified the route name explicitly: '@State' that it did not parse the entire routing file and just used the specific route you asked for.
I would like to be able to use the same action to display data based on the variable name (zip or state) I don't want to have to create the same action (results) twice just to pass in a different parameter. | You need to add requirements so that it will recognize the different formats
```
Zip:
url: home/:zip
param: { module: home, action: results }
requirements: { zip: \d{5} } # assuming only 5 digit zips
State:
url: home/:state
param: { module: home, action: results }
requirements: { state: [a-zA-Z]{2} }
```
That should fix it, although I agree with you that when you use a route name in a helper it should use the named route. | the problem here is that both routing rules resolves to somewhat same url ( /home/) and when generating links it uses correct named route to generate url.
when you click on that generated url( for example /home/CA) withouth requirements addition it will match the first rule in routing.yml file that matches and that is your "Zip" route.
just to explain what is happening. | Can you force symfony resolve to a specific route? | [
"",
"php",
"routes",
"symfony1",
""
] |
***Creating a call stack diagram***
We have just recently been thrown into a big project that requires us to get into the code (duh).
We are using different methods to get acquainted with it, breakpoints etc. However we found that one method is to make a **call tree** of the application, what is the easiest /fastest way to do this?
By code? Plugins? Manually?
*The project is a C# Windows application.* | **Edit:** I believe the Microsoft's [CLR Profiler](http://www.microsoft.com/downloads/details.aspx?familyid=a362781c-3870-43be-8926-862b40aa0cd0&displaylang=en) is capable of displaying a call tree for a running application. If that is not sufficient I have left the link I posted below in case you would like to start on a custom solution.
---
[Here is a CodeProject article](http://www.codeproject.com/KB/cs/cs_call_tree_prototype.aspx) that might point you in the right direction:
> The download offered here is a Visual
> Studio 2008 C# project for a simple
> utility to list user function call
> trees in C# code.
>
> This call tree lister seems to work OK
> for my style of coding, but will
> likely be unreliable for some other
> styles of coding. It is offered here
> with two thoughts: first, some
> programmers may find it useful as is;
> second, I would be appreciative if
> someone who is up-to-speed on C#
> parsing would upgrade it by
> incorporating an accurate C# parser
> and turn out an improved utility that
> is reliable regardless of coding style
The source code is available for download - perhaps you can use this as a starting point for a custom solution. | With the static analyzer [NDepend](http://www.ndepend.com/Doc_VS_Arch.aspx), you can obtain a *static* method [call graph](http://www.ndepend.com/Doc_VS_Arch.aspx), like the one below. *Disclaimer: I am one of the developers of the tool*

For that you just need to export to the graph the result of a [CQLinq code query](http://www.ndepend.com/Features.aspx#CQL):

Such a code query, can be generated actually for any method, thanks to the right-click menu illustrated below.
 | How to make a "Call stack diagram" | [
"",
"c#",
".net",
"diagram",
""
] |
The Query I'm writing runs fine when looking at the past few days, once I go over a week it crawls (~20min). I am joining 3 tables together. I was wondering what things I should look for to make this run faster. I don't really know what other information is needed for the post.
EDIT: More info: db is Sybase 10. Query:
```
SELECT a.id, a.date, a.time, a.signal, a.noise,
b.signal_strength, b.base_id, b.firmware,
a.site, b.active, a.table_key_id
FROM adminuser.station AS a
JOIN adminuser.base AS b
ON a.id = b.base_id
WHERE a.site = 1234 AND a.date >= '2009-03-20'
```
I also took out the 3rd JOIN and it still runs extremely slow. Should I try another JOIN method? | I don't know Sybase 10 that well, but try running that query for say 10-day period and then 10 times, for each day in a period respectively and compare times. If the time in the first case is much higher, you've probably hit the database cache limits.
The solution is than to simply run queries for shorter periods in a loop (in program, not SQL). It works especially well if table A is partitioned by date. | You can get a lot of information (assuming you're using MSSQL here) by running your query in SQL Server Management Studio with the *Include Actual Execution Plan* option set (in the *Query* menu).
This will show you a diagram of the steps that SQLServer performs in order to execute the query - with relative costs against each step.
The next step is to rework the query a little (try doing it a different way) then run the new version and the old version at the same time. You will get two execution plans, with relative costs not only against each step, but against the two versions of the query! So you can tell objectively if you are making progress.
I do this all the time when debugging/optimizing queries. | Need tips for optimizing SQL Query using a JOIN | [
"",
"sql",
"optimization",
"join",
"sybase",
""
] |
Apart from the google/bigtable scenario, when shouldn't you use a relational database? Why not, and what should you use? (did you learn 'the hard way'?) | In my experience, you shouldn't use a relational database when any one of these criteria are true:
* your data is structured as a hierarchy or a graph (network) of arbitrary depth,
* the typical access pattern emphasizes reading over writing, or
* there’s no requirement for ad-hoc queries.
Deep hierarchies and graphs do not translate well to relational tables. Even with the assistance of proprietary extensions like Oracle's `CONNECT BY`, chasing down trees is a mighty pain using SQL.
Relational databases add a lot of overhead for simple read access. Transactional and referential integrity are powerful, but overkill for some applications. So for read-mostly applications, a file metaphor is good enough.
Finally, you simply don’t need a relational database with its full-blown query language if there are no unexpected queries anticipated. If there are no suits asking questions like "how many 5%-discounted blue widgets did we sell in on the east coast grouped by salesperson?", and there never will be, then you, sir, can live free of DB. | The relational database paradigm makes some assumptions about usage of data.
* A relation consists of an unordered set of rows.
* All rows in a relation have the same set of columns.
* Each column has a fixed name and data type and semantic meaning on all rows.
* Rows in a relation are identified by unique values in primary key column(s).
* etc.
These assumptions support simplicity and structure, at the cost of some flexibility. Not all data management tasks fit into this kind of structure. Entities with complex attributes or variable attributes do not, for instance. If you need flexibility in areas where a relational database solution doesn't support it, you need to use a different kind of solution.
There are other solutions for managing data with different requirements. Semantic Web technology, for example, allows each entity to define its own attributes and to be self-describing, by treating metadata as attributes just like data. This is more flexible than the structure imposed by a relational database, but that flexibility comes with a cost of its own.
Overall, you should use the right tool for each job.
See also my other answer to "[The Next-gen databases](https://stackoverflow.com/questions/282783/the-next-gen-databases/282813#282813)." | When shouldn't you use a relational database? | [
"",
"sql",
"database",
"nosql",
"relational-database",
""
] |
I'm seeking a javascript history framework to handle navigation inside a page when the user selects multiple options which change the page behaviour.
There are multiple artefacts on the page that change the data loading of the page and I'd like to store this as a stacked set of behaviour. In a wider sense, I'd like to add this as a toolkit to my future web projects for the same reasons.
I'm primarily writing in ASP.NET with JQuery but I'm only really worried about JQuery for now. I do write other projects in PHP, Python and Perl (depending on the gig) so it would have to be platform agnostic.
I've been looking on the net and have found a few but only one (covered on OReilly) looked like it would fit the bill. I have started playing with it but I wanted to know what toolkits other people were using and what others would recommend.
So if you have any experience of history frameworks, handling the back button (etc) in Ajax I'd love to hear about what you've used and how it worked out. It would really help me make a final choice on library.
Thanks,
S | I had the similar problem a while ago building a flash only site. We tried:
* [Really Simple History](http://code.google.com/p/reallysimplehistory/) (which had some problems in combination of safari and flash)
* [ExtJS](http://extjs.com) which has a [history component](http://extjs.com/deploy/dev/docs/?class=Ext.History) which worked great for us. ([Demo](http://extjs.com/deploy/dev/examples/history/history.html)) [Beside we have used this framework already for other projects.] | Maybe [this question](https://stackoverflow.com/questions/568719/is-monitoring-location-hash-a-solution-for-history-in-xhr-apps) is usefull to you. In the question I linked to a testpage, where location.hash is used to keep track of the history. I am currently using this method in a testsite and experienced problems with Opera (truncates a location.hash value at the question mark, you'll have to use: `location.href.split(/#/)[1]`) and of course IE (needs an iframe). In IE with iframe the history is saved for the current session only. If you load another page in the same window/tab and use the back button to go back to the AJAX page, the previous history is lost. It's not that big a deal for me, but may be annoying. I understood that IE8s history should behave like expected with location.hash, it even should have a hashchange handler.
I think most of the frameworks use the same technique (monitoring location.hash for changes, using an iframe for IE). I didn't want to use a framework, because I'm using my own home brew small framework and regular frameworks contain too much functionallity I'll never use. | Experiences with Javascript History Frameworks | [
"",
"javascript",
"jquery",
"ajax",
"hashchange",
""
] |
My website is written in Python and currently runs under mod\_python with Apache. Lately I've had to put in a few ugly hacks that make me think it might be worth converting the site to mod\_wsgi. But I've gotten used to using some of mod\_python's utility classes, especially `FieldStorage` and `Session` (and sometimes `Cookie`), and from a scan of [PEP 333](http://www.python.org/dev/peps/pep-0333/), I don't see any equivalents to these. (Not surprising, because I understand that those kinds of utilities don't belong in the WSGI spec)
Question is, are there "standard" (i.e. commonly accepted) replacements for these mod\_python utility classes that I can use in WSGI, or could I/should I write my own?
(FYI: currently using Python 2.5) | Look at [Werkzeug](http://werkzeug.pocoo.org/). You may have to do some rewriting. You will probably be pleased with the results of imposing the WSGI world-view on your application. | You can use FieldStorage in 'cgi' module and the 'Cookie' module. There is no equivalent to Session in Python standard libraries. For WSGI applications you can use [Beaker](http://beaker.groovie.org/) for sessions. | Converting from mod_python to mod_wsgi | [
"",
"python",
"mod-wsgi",
"mod-python",
""
] |
Apache Wicket ( <http://wicket.apache.org/> ) and Apache Tapestry ( <http://wicket.apache.org/> ) are **both component oriented web framework**s - contrary to action based frameworks like Stripes - by the Apache Foundation. Both allow you to build your application from components in Java. *They both look very similar to me*.
What are the differences between those two frameworks? Has someone experience in both? Specifically:
* How is their performance, how much can state handling be customized, *can they be used stateless*?
* What is the difference in their component model?
* What would you choose for which applications?
* How do they integrate with Guice, Spring, JSR 299?
**Edit**: I have read the documentation for both and I have used both. The questions cannot be answered sufficently from reading the documentation, but from the experience from using these for some time, e.g. how to use Wicket in a stateless mode for high performance sites. Thanks. | Some relevant differences as I see them:
* Tapestry uses a semi-static page
structure, where you can work with
conditionals and loops to achieve
dynamic behavior. Wicket is
completely dynamic; you can load
components dynamically, replace them
at runtime, etc. The consequences of
this are that Tapestry is easier to
optimize, and that Wicket is more
flexible in it's use.
* Both frameworks
are roughly equally efficient in
execution, but Wicket relies on
server side storage (by default the
current page in session, and past
pages in a 'second level cache' which
is default a temp file in the file
system). If that bothers you, think
about how many concurrent sessions
you expect to have at peak times and
calculate with say ~100kb per session
(which is probably on the high side).
That means that you can run roughly
support 20k concurrent sessions for
2GB. Say 15k because you need that
memory for other things as well. Of
course, a disadvantage of storing
state is that it'll only work well
with session affinity, so that's a
limitation when using Wicket. The
framework provides you with a means
to implement stateless pages, but if
you're developing fully stateless
applications you might consider a
different framework.
* Wicket's goal is to support static typing to the fullest extent, whereas Tapestry is more about saving lines of code. So with Tapestry your code base is likely smaller, which is good for maintenance, and with Wicket, you much is statically typed, which makes it easier to navigate with an IDE and check with a compiler, which also is good for maintenance. Something to say for both imho.
I have read a few times by now that people think Wicket works through inheritance a lot. I would like to stress that you have a choice. There is a hierarchy of components, but Wicket also supports composition though constructs like IBehavior (on top of which e.g. Wicket's Ajax support is built). On top of that you have things like converters and validators, which you add to components, globally, or even as a cross cutting concern using some of the phase listeners Wicket provides. | **REVISED** after studying Tapestry 5.
**Wicket's goal** is an attempt to make **web development similar to desktop GUI** one. They managed to do it really well at the expense of memory usage ( HTTPSession ).
**Tapestry 5's goal** is to make **very optimized (for CPU and memory)** component oriented web framework.
**The really big pitfall for me** was responses "Wicket supports stateless component!" to the arguments "Wicket is memory hungry". While Wicket indeed supports stateless components they are not "a focus of Wicket development". For example a bug in StatelessForm was not fixed for a very long time - see [StatelessForm - problem with parameters after validation fails](http://www.nabble.com/StatelessForm---problem-with-parameters-after-validation-fails-td22438953.html).
* IMHO using Wicket is a bit eaiser until you are going to optimize/ fine-tune web application parameters
* IMHO Wicket is harder to study if you have programmed web applications and want to think in terms of request processing
* Tapestry 5 automatically **reloads component classes** as soon as you change them. Both frameworks reload component markup.
* Wicket forces **markup/ code separation**, Tapestry 5 just give you this ability. You can also use less verbose syntax in Tapestry 5. As always this freedom requires more cautions to be taken.
* Wicket's core is easier to debug: user components are based on inheritance while Tapestry 5 user components are based on annotations. From the other side that could make transitions to the future versions easier for Tapestry then for Wicket.
Unfortunately [Tapestry 5 tutorial](http://tapestry.apache.org/tapestry5/tutorial1/hilo.html) does not stress that Tapestry code example like 't:loop source="1..10"...' can be a bad practice. So some effort should be put into writing Tapestry usage conventions/ good practices if your team is not very small.
**My recommendations**:
* Use Wicket when your pages structure is very dynamic and you can afford spending 10-200 Kbs of HttpSession memory per user (these are rough numbers).
* Use Tapestry 5 in cases when you need more efficient usage of resources | Difference between Apache Tapestry and Apache Wicket | [
"",
"java",
"wicket",
"web-frameworks",
"tapestry",
""
] |
Is it possible to add a copyright symbol or other "special" symbol in any way in a C# console application? | ```
namespace test {
class test {
public static void Main() {
System.Console.WriteLine("©");
}
}
}
```
works for me flawlessly. Regardless of whether the console window is set to raster fonts or Unicode.
If you want to output Unicode, you should set the console output encoding to UTF-8 or Unicode.
```
System.Console.OutputEncoding = System.Text.Encoding.UTF8;
```
or
```
System.Console.OutputEncoding = System.Text.Encoding.Unicode;
```
And if you want to stay clear from source code encoding issues you should specify the character code point directly:
```
System.Console.WriteLine("\u00a9");
``` | You can copy it from here if you like:
©
(You can hold down ALT, then type 0169, then release the ALT key) | Is it possible to get a copyright symbol in C# Console application? | [
"",
"c#",
"console",
""
] |
I am using Ext.data.Store to call a PHP script which returns a JSON response with some metadata about fields that will be used in a query (unique name, table, field, and user-friendly title). I then loop through each of the Ext.data.Record objects, placing the data I need into an array (`this_column`), push that array onto the end of another array (`columns`), and eventually pass this to an Ext.grid.ColumnModel object.
The problem I am having is - no matter which query I am testing against (I have a number of them, varying in size and complexity), the columns array always works as expected up to `columns[15]`. At `columns[16]`, all indexes from that point and previous are filled with the value of `columns[15]`. This behavior continues until the loop reaches the end of the Ext.data.Store object, when the entire arrays consists of the same value.
Here's some code:
```
columns = [];
this_column = [];
var MetaData = Ext.data.Record.create([
{name: 'id'},
{name: 'table'},
{name: 'field'},
{name: 'title'}
]);
// Query the server for metadata for the query we're about to run
metaDataStore = new Ext.data.Store({
autoLoad: true,
reader: new Ext.data.JsonReader({
totalProperty: 'results',
root: 'fields',
id: 'id'
}, MetaData),
proxy: new Ext.data.HttpProxy({
url: 'index.php/' + type + '/' + slug
}),
listeners: {
'load': function () {
metaDataStore.each(function(r) {
this_column['id'] = r.data['id'];
this_column['header'] = r.data['title'];
this_column['sortable'] = true;
this_column['dataIndex'] = r.data['table'] + '.' + r.data['field'];
// This display valid information, through the entire process
console.info(this_column['id'] + ' : ' + this_column['header'] + ' : ' + this_column['sortable'] + ' : ' + this_column['dataIndex']);
columns.push(this_column);
});
// This goes nuts at columns[15]
console.info(columns);
gridColModel = new Ext.grid.ColumnModel({
columns: columns
});
``` | Okay, since the this\_column array was responding correctly on each run, but the columns array was not, I figure it must be an issue with the push().
After a bit more toying with it, I moved altered the code to reset the this\_column array on each iteration of the loop - seems to have fixed the issue...
```
metaDataStore.each(function(r) {
this_column = [];
this_column['id'] = r.data['id'];
this_column['header'] = r.data['title'];
this_column['sortable'] = true;
this_column['dataIndex'] = r.data['table'] + '.' + r.data['field'];
columns.push(this_column);
});
``` | I see you've already found something that works, but just to offer some advice for the future: this is much easier if you use a json store and column model directly instead of performing intermediate steps by hand.
I'm not sure if you're using a grid or dataview, but the concept is pretty much the same for both of them. If you have to do a bit of data customization, but instead of doing it by hand here you can actually just do it in a prepareData callback function. | Ext.data.Store, Javascript Arrays and Ext.grid.ColumnModel | [
"",
"javascript",
"extjs",
""
] |
How do I convert an integer into a binary string in Python?
```
37 → '100101'
``` | Python's string format method can take a format spec.
```
>>> "{0:b}".format(37)
'100101'
```
[Format spec docs for Python 2](https://docs.python.org/2/library/string.html#formatspec)
[Format spec docs for Python 3](https://docs.python.org/3/library/string.html#formatspec) | If you're looking for [`bin()`](http://docs.python.org/library/functions.html#bin) as an equivalent to `hex()`, it was added in python 2.6.
Example:
```
>>> bin(10)
'0b1010'
``` | Convert int to binary string in Python | [
"",
"python",
"binary",
"string.format",
""
] |
The code below successfully recognizes *internal* classes which are decorated with my custom "Module" attribute, I load the assembly like this:
```
Assembly assembly = Assembly.GetExecutingAssembly();
```
However, when I load in an **external module** and look through its classes, it finds the classes in the external assembly but **does not recognize the custom attributes**:
```
Assembly assembly = Assembly.LoadFrom(@"c:\tests\modules\CustomModules.dll");
```
**What do I have to specify so that C# recognizes custom attributes in external .dlls the same as it does with the internal classes?**
Here is the code that successfully runs through and recognizes internal classes decorated with my "Module" attribute:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace DynamicAssembly2
{
class Program
{
static void Main(string[] args)
{
var modules = from t in GetModules()
select t;
foreach (var module in modules)
{
ModuleAttribute[] moduleAttributes = GetModuleAttributes(module);
Console.WriteLine(module.FullName);
foreach (var moduleAttribute in moduleAttributes)
{
Console.WriteLine(moduleAttribute.Description);
}
}
Console.ReadLine();
}
public static IEnumerable<Type> GetModules()
{
//Assembly assembly = Assembly.LoadFrom(@"c:\tests\modules\CustomModules.dll");
Assembly assembly = Assembly.GetExecutingAssembly();
return GetAssemblyClasses(assembly)
.Where((Type type) => {return IsAModule(type);});
}
public static IEnumerable<Type> GetAssemblyClasses(Assembly assembly)
{
foreach (Type type in assembly.GetTypes())
{
Console.WriteLine(type.FullName);
yield return type;
}
}
public static bool IsAModule(Type type)
{
return GetModuleAttribute(type) != null;
}
public static ModuleAttribute GetModuleAttribute(Type type)
{
ModuleAttribute[] moduleAttributes = GetModuleAttributes(type);
Console.WriteLine(moduleAttributes.Length);
if (moduleAttributes != null && moduleAttributes.Length != 0)
return moduleAttributes[0];
return null;
}
public static ModuleAttribute[] GetModuleAttributes(Type type)
{
return (ModuleAttribute[])type.GetCustomAttributes(typeof(ModuleAttribute), true);
}
}
}
```
Here is my custom Mdoule attribute:
```
using System;
namespace DynamicAssembly2
{
[AttributeUsage(AttributeTargets.Class)]
public class ModuleAttribute : Attribute
{
public string Description { get; set; }
}
}
```
Here is a custom module:
```
namespace DynamicAssembly2
{
[Module(Description="This is the main customer class.")]
class Customers
{
}
}
``` | How many instances of the ModuleAttribute class do you have defined across your assemblies?
It looks like you have one in DynamicAssembly2 and one in CustomModules ... in which case they are different types.
Your code in DynamicAssembly2 should use the attribute class defined in CustomModules (or both assemblies should load the attribute from a 3rd assembly). | I'm pretty sure that it doesn't distinguish... are you sure you are asking for the right attribute? As long as both projects reference the **same** `ModuleAttribute`, then `typeof(ModuleAttribute)` should work. Otherwise you'll need to first find the `Type` of the attribute you want (from `Assembly.GetType()`), and use that when calling `GetCustomAttributes`. | How to make C# recognize custom attributes in external .dll? | [
"",
"c#",
"reflection",
""
] |
I need to remove blank lines (with whitespace or absolutely blank) in PHP. I use this regular expression, but it does not work:
```
$str = ereg_replace('^[ \t]*$\r?\n', '', $str);
$str = preg_replace('^[ \t]*$\r?\n', '', $str);
```
I want a result of:
```
blahblah
blahblah
adsa
sad asdasd
```
will:
```
blahblah
blahblah
adsa
sad asdasd
``` | ```
// New line is required to split non-blank lines
preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);
```
The above regular expression says:
```
/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/
1st Capturing group (^[\r\n]*|[\r\n]+)
1st Alternative: ^[\r\n]*
^ assert position at start of the string
[\r\n]* match a single character present in the list below
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
\r matches a carriage return (ASCII 13)
\n matches a fine-feed (newline) character (ASCII 10)
2nd Alternative: [\r\n]+
[\r\n]+ match a single character present in the list below
Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\r matches a carriage return (ASCII 13)
\n matches a fine-feed (newline) character (ASCII 10)
[\s\t]* match a single character present in the list below
Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
\s match any white space character [\r\n\t\f ]
\tTab (ASCII 9)
[\r\n]+ match a single character present in the list below
Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
\r matches a carriage return (ASCII 13)
\n matches a fine-feed (newline) character (ASCII 10)
``` | Your `ereg-replace()` solution is wrong because the `ereg/eregi` methods are deprecated. Your `preg_replace()` won't even compile, but if you add delimiters and set multiline mode, it will work fine:
```
$str = preg_replace('/^[ \t]*[\r\n]+/m', '', $str);
```
The `m` modifier allows `^` to match the beginning of a logical line rather than just the beginning of the whole string. The start-of-line anchor is necessary because without it the regex would match the newline at the end of every line, not just the blank ones. You don't need the end-of-line anchor (`$`) because you're actively matching the newline characters, but it doesn't hurt.
The [accepted answer](https://stackoverflow.com/a/709684/20938) gets the job done, but it's more complicated than it needs to be. The regex has to match either the beginning of the string (`^[\r\n]*`, multiline mode not set) or at least one newline (`[\r\n]+`), followed by at least one newline (`[\r\n]+`). So, in the special case of a string that starts with one or more blank lines, they'll be replaced with *one* blank line. I'm pretty sure that's not the desired outcome.
But most of the time it replaces two or more consecutive newlines, along with any horizontal whitespace (spaces or tabs) that lies between them, with one linefeed. That's the intent, anyway. The author seems to expect `\s` to match just the space character (`\x20`), when in fact it matches any whitespace character. That's a very common mistake. The actual list varies from one regex flavor to the next, but at minimum you can expect `\s` to match whatever `[ \t\f\r\n]` matches.
Actually, in PHP you have a better option:
```
$str = preg_replace('/^\h*\v+/m', '', $str);
```
`\h` matches any horizontal whitespace character, and `\v` matches vertical whitespace. | How do I remove blank lines from text in PHP? | [
"",
"php",
"regex",
""
] |
I have a number of Inherited User Controls, for each User Control I sometimes have overridden event Handlers for the Buttons on the Control. (To allow for Child specific behaviours to occur)
Is there a way of viewing all the Event Handlers associated with a particular component?
The problem being that on one of the Buttons, the event handler wass being called twice. I believe this was due to the fact that I had assigned the Click Event Handler twice, once in the parent and once in the child User Control. I remove the assignment in the child control and now nothing happens when I click the button (within the VS2008 designer)!
Any and all help will be gratefully received!
**EDIT**
The reason nothing happened is down to a verion control issue .... the child's overidden event handler was incorrect!
But the main point still remains... Im not the only contributer to the codebase, and If I need to see which events are attributed to a component I cant explicitly at the moment. Especially with regards to Timers as we dynamically add and remove events that need t obe 'synchronised' to a single timer. It would be good to see which Events are tagged onto the Tick event?! | You could do a text search on entire solution or current project source code based on what you're looking for.
Search for example: "`controlName.EventName +=`". You'll directly see what has subscribed to this control event. | Using [Resharper](http://www.jetbrains.com/resharper/), I do this using Shift-F12, which shows a tree view of all usages (including usages via an interface). Without Resharper, it is probably simplest to use text search as Tyalis suggests. | Viewing all event handlers associated with a Button? | [
"",
"c#",
"winforms",
"visual-studio-2008",
"event-handling",
""
] |
I'm trying to match a string that may appear over multiple lines. It starts and ends with a specific string:
```
{a}some string
can be multiple lines
{/a}
```
Can I grab everything between `{a}` and `{/a}` with a regex? It seems the . doesn't match new lines, but I've tried the following with no luck:
```
$template = preg_replace( $'/\{a\}([.\n]+)\{\/a\}/', 'X', $template, -1, $count );
echo $count; // prints 0
```
It matches . or \n when they're on their own, but not together! | Use the [`s` modifier](http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php):
```
$template = preg_replace( $'/\{a\}([.\n]+)\{\/a\}/s', 'X', $template, -1, $count );
// ^
echo $count;
``` | I think you've got more problems than just the dot not matching newlines, but let me start with a formatting recommendation. You can use just about any punctuation character as the regex delimiter, not just the slash ('/'). If you use another character, you won't have to escape slashes within the regex. I understand '%' is popular among PHPers; that would make your pattern argument:
```
'%\{a\}([.\n]+)\{/a\}%'
```
Now, the reason that regex didn't work as you intended is because the dot loses its special meaning when it appears inside a character class (the square brackets)--so `[.\n]` just matches a dot or a linefeed. What you were looking for was `(?:.|\n)`, but I would have recommended matching the carriage-return as well as the linefeed:
```
'%\{a\}((?:.|[\r\n])+)\{/a\}%'
```
That's because the word "newline" can refer to the Unix-style "\n", Windows-style "\r\n", or older-Mac-style "\r". Any given web page may contain any of those or a mixture of two or more styles; a mix of "\n" and "\r\n" is very common. But with /s mode (also known as single-line or DOTALL mode), you don't need to worry about that:
```
'%\{a\}(.+)\{/a\}%s'
```
However, there's another problem with the original regex that's still present in this one: the `+` is greedy. That means, if there's more than one `{a}...{/a}` sequence in the text, the first time your regex is applied it will match all of them, from the first `{a}` to the last `{/a}`. The simplest way to fix that is to make the `+` ungreedy (a.k.a, "lazy" or "reluctant") by appending a question mark:
```
'%\{a\}(.+?)\{/a\}%s'
```
Finally, I don't know what to make of the '$' before the opening quote of your pattern argument. I don't do PHP, but that looks like a syntax error to me. If someone could educate me in this matter, I'd appreciate it. | Including new lines in PHP preg_replace function | [
"",
"php",
"regex",
"newline",
""
] |
> See also
> [C++ standard list and default-constructible types](https://stackoverflow.com/questions/695372/c-standard-list-and-default-constructible-types)
Not a major issue, just annoying as I don't want my class to ever be instantiated without the particular arguments.
```
#include <map>
struct MyClass
{
MyClass(int t);
};
int main() {
std::map<int, MyClass> myMap;
myMap[14] = MyClass(42);
}
```
This gives me the following g++ error:
> /usr/include/c++/4.3/bits/stl\_map.h:419: error: no matching function for call to ‘MyClass()’
This compiles fine if I add a default constructor; I am certain it's not caused by incorrect syntax. | This issue comes with operator[]. Quote from SGI documentation:
> `data_type& operator[](const key_type& k)` - Returns a reference to the object
> that is associated with a particular
> key. If the map does not already
> contain such an object, `operator[]`
> inserts the default object
> `data_type()`.
If you don't have default constructor you can use insert/find functions.
Following example works fine:
```
myMap.insert( std::map< int, MyClass >::value_type ( 1, MyClass(1) ) );
myMap.find( 1 )->second;
``` | Yes. Values in STL containers need to maintain copy semantics. IOW, they need to behave like primitive types (e.g. int) which means, among other things, they should be default-constructible.
Without this (and others requirements) it would be needlessly hard to implement the various internal copy/move/swap/compare operations on the data structures with which STL containers are implemented.
Upon reference to the C++ Standard, I see my answer was not accurate. **Default-construction is, in fact, not a requirement**:
From 20.1.4.1:
> The default constructor is not
> required. Certain container class
> member function signatures specify the
> default constructor as a default
> argument. T() must be a well-defined
> expression ...
So, strictly speaking, your value type only needs to be default constructible if you happen to be using a function of the container that uses the default constructor in its signature.
The real requirements (23.1.3) from all values stored in STL containers are `CopyConstructible` and `Assignable`.
There are also other specific requirements for particular containers as well, such as being `Comparable` (e.g. for keys in a map).
---
Incidentally, the following compiles with no error on [comeau](http://www.comeaucomputing.com/tryitout/):
```
#include <map>
class MyClass
{
public:
MyClass(int t);
};
int main()
{
std::map<int, MyClass> myMap;
}
```
So this might be a g++ problem. | Why does the C++ map type argument require an empty constructor when using []? | [
"",
"c++",
"dictionary",
""
] |
I'm currently refactoring a console application whose main responsibility is to generate a report based on values stored in the database.
The way I've been creating the report up til now is as follows:
```
const string format = "<tr><td>{0, 10}</td><td>
{1}</td><td>{2, 8}</td><td>{3}</td><td>{4, -30}</td>
<td>{5}</td><td>{6}</td></tr>";
if(items.Count > 0)
{
builder.AppendLine(
String.Format(format, "Date", "Id", "WorkItemId",
"Account Number", "Name", "Address", "Description"));
}
foreach(Item item in items)
{
builder.AppendLine(String.Format(format, item.StartDate, item.Id,
item.WorkItemId, item.AccountNumber,
String.Format("{0} {1}",
item.FirstName, item.LastName),
item.Address, item.Description));
}
string report = String.Format("<html><table border=\"1\">{0}
</table></html>",
builder.ToString());
```
(The above is just a sample...and sorry about the formatting...I tried to format it so it wouldn't require horizontal scrolling....)
I really don't like that way I've done this. It works and does the job for now...but I just don't think it is maintainable...particularly if the report becomes any more complex in terms of the html that needs to be created. Worse still, other developers on my team are sure to copy and paste my code for their applications that generate an html report and are likely to create a horrible mess. (I've already seen such horrors produced! Imagine a report function that has hundreds of lines of hard coded sql to retrieve the details of the report...its enough to make a grown man cry!)
However, while I don't like this at all...I just can't think of a different way to do it.
Surely there must be a way to do this...I'm certain of it. Not too long ago I was doing the same thing when generating tables in aspx pages until someone kindly showed me that I can just bind the objects to a control and let .NET take care of the rendering. It turned horrible code, similar to the code above, into two or three elegant lines of goodness.
Does anyone know of a similar way of creating the html for this report without hard-coding the html? | Make your app to produce XML file with raw data. Then apply an external XSLT to it which would contain HTML.
More info: <http://msdn.microsoft.com/en-us/library/14689742.aspx> | You could use a template engine like [NVelocity](http://www.castleproject.org/others/nvelocity/) to separate your report view and your code.
There are probably other decent template engines out there... | How do I create an html report without hardcoding the html? | [
"",
"c#",
".net",
"html",
"reporting",
"hard-coding",
""
] |
Is there an existing javascript library for relaying key press events in the browser (or certain divs) into flash? I am hoping there might be a library kind of [like this one for mousewheel events](http://hasseg.org/blog/?p=138) ?
Something like [this](http://www.openjs.com/scripts/events/keyboard_shortcuts/) handles javascript keyboard shortcuts great. I suppose I could just listen for those events and pass the ones I want into flash?
---
**EDIT:** These are great examples, however, if flash has focus, then javascript keystrokes are lost. How can you ensure that all key events go through javascript? | Here's another example using jQuery. You can see some sort of demo [here](http://sorinvasilescu.ro/keycode/). It traces the keypresses from the browser to a textbox.
Your JavaScript would be
```
var altPressed = false;
var ctrlPressed = false;
function getFlashMovie(movieName)
{
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName];
}
function sendCode(code) {
movie = getFlashMovie('keyboard-listener');
movie.keyEvent(code);
}
function activeKey(e) {
e.preventDefault();
if (e.which == 18) altPressed = true;
if (e.which == 17) ctrlPressed = true;
if ((e.which != 18)&&(e.which != 17)) sendCode((altPressed?'alt+':'')+(ctrlPressed?'ctrl+':'')+String.fromCharCode(e.which));
}
function inactiveKey(e) {
if (e.which == 18) altPressed = false;
if (e.which == 17) ctrlPressed = false;
}
$(document).ready(function() {
$(document).keydown(activeKey);
$(document).keyup(inactiveKey);
});
```
Inside the Flash movie, you would have the following code:
```
ExternalInterface.addCallback('keyEvent',keyEvent);
function keyEvent(code:String):void {
// do something with the "code" parameter, that looks like "alt+ctrl+D", may use .split('+'), etc
}
```
You'll need to import [jQuery](http://jquery.com/) in your html file and that's about it. jQuery is cross-browser, so no problems should arise. Tested on Safari, Firefox and Opera (OSX). | Here's an example using [SWFObject](http://blog.deconcept.com/swfobject/) / javascript / AS3 + ExternalInterface
It may use some adaption to work cross-browser. I tried it on FF3(OSX) only.
First a document class containing a simple log field (for traces).
It simply defines an ExternalInterface callback listening to a method call named ***flashLog*** that will handled by the private method ***setMessage(...params)***
```
package
{
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.external.ExternalInterface;
import flash.text.TextField;
public class KeyStroke extends Sprite
{
private var tf:TextField;
public function KeyStroke()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
tf = addChild(new TextField()) as TextField;
tf.autoSize = 'left';
if(ExternalInterface.available)
{
if(ExternalInterface.addCallback("flashLog", setMessage))
{
tf.text = "addCallback() failed :(";
}
else
{
tf.text = "flash waiting";
}
}
else
{
setMessage("ExternalInterface not available!");
}
}
private function setMessage(...params):void
{
tf.text = "message : " + params.toString();
}
}
}
```
Embed the exported SWF via [SWFObject](http://blog.deconcept.com/swfobject/) adding the **allowScriptAccess** attribute, you will also need to give an id so we can locate the SWF further on (in this case '***myMovie***') :
```
var so = new SWFObject('KeyStroke.swf', 'myMovie', '800', '100', '9', '#f0f0f0');
so.addParam("allowScriptAccess","always");
so.write('content');
```
Create a javascript function to handle the key presses :
```
<script type="text/javascript">
function keyPressHandler(e)
{
// Calls the registered callback within the flash movie
getMovie('myMovie').flashLog("Key Down!"+e.charCode)
}
function getMovie(movieName) {
return document.getElementById(movieName);
}
</script>
```
Register the keyPressHandler somehow (there's better ways with prototype etc.) :
```
<body onKeyPress="keyPressHandler(event);" >
```
That should be it. | javascript to actionscript keypress passing utility? | [
"",
"javascript",
"flash",
"actionscript-3",
"actionscript",
""
] |
Where can I find a Qt tutorial in PDF format. I have looked all over google but can't find one. I need to be able to read it offline as I can't always be on the internet. Thanks! | If you're looking for a tutorial or a book, rather than QT docs have a look at this free ebook :
[C++ GUI Programming with Qt 4](http://www.qtrac.eu/marksummerfield.html)
The author has released the first edition with an open license. If you like it You can still buy the printed second edition in amazon. | There is no PDF directly from trolltech that I know of, but all of the docs are under
> Qt\200x.xx\qt\doc\html
where 200x.xx represents the version of the Qt SDK. Mine is 2009.01 for example.
You could use one of many [HTML to PDF](http://www.google.ca/search?hl=en&q=html2pdf&btnG=Google+Search&meta=) converters to achieve what you're looking for. | Qt PDF Tutorial? | [
"",
"c++",
"qt",
""
] |
Is there a sensible way to group Long UTC dates by Day?
I would Mod them by 86400 but that doesn't take leap seconds into account.
Does anyone have any other ideas, I'm using java so I could parse them into Date Objects, but I'm a little worried of the performance overhead of using the date class.
Also is there a more efficient way than comparing the year month and day parts of a Date object? | Does your source data *definitely* include leap seconds to start with? Some APIs do, and some don't - Joda Time (which I'd recommend over the built-in date/time APIs) [doesn't use leap seconds](http://joda-time.sourceforge.net/faq.html#leapseconds), for example. The Java date and time APIs "sometimes" do - they support 60 and 61 as values of "second in minute" but support depends on the operating system (see below). If you have some good sample values, I'd check that first if I were you. Obviously just dividing is rather simpler than anything else.
If you *do* need to create `Date` objects (or `DateTime` in Joda) I would benchmark it before doing anything else. You may well find that the performance is actually perfectly adequate. There's no point in wasting time optimizing something which is okay for your data. Of course, you'll need to decide data size you need to support, and how quick it needs to be first :)
Even the `java.util.Date` support for leap seconds is somewhat indeterminate. From [the docs](http://java.sun.com/javase/6/docs/api/java/util/Date.html):
> Although the Date class is intended to
> reflect coordinated universal time
> (UTC), it may not do so exactly,
> depending on the host environment of
> the Java Virtual Machine. Nearly all
> modern operating systems assume that 1
> day = 24 × 60 × 60 = 86400 seconds in
> all cases. In UTC, however, about once
> every year or two there is an extra
> second, called a "leap second." The
> leap second is always added as the
> last second of the day, and always on
> December 31 or June 30. For example,
> the last minute of the year 1995 was
> 61 seconds long, thanks to an added
> leap second. Most computer clocks are
> not accurate enough to be able to
> reflect the leap-second distinction.
There's a [rather good blog post](http://lpar.ath0.com/2008/09/16/the-fractious-leap-second-debate/) about the mess with Java and leap seconds which you may want to read too. | > I would Mod them by 86400 but that doesn't take leap seconds into account....
I'm pretty sure that that will be fine. The API documentation for `Date` really shouldn't include anything about leap seconds, because the fact is that it emulates a standard Unix time ticker which does NOT include leap seconds in its value.
What it does instead is to have a 59th second that lasts for two seconds by setting the ticker value back by 1 second at the start of a leap second (as the link in the previous post describes).
Therefore you can assume that the value you get from `Date.getTime()` IS made up only of 86400-second days. If you really need to know whether a *particular* day had a leap second, there are several tables available on the Internet (there have only been 23-24 since 1972, and computer dates before that rarely took them into account anyway).
HIH
Winston | Grouping Long UTC dates by Day | [
"",
"java",
"utc",
""
] |
Is there any tool/library that calculate percent of "condition/decision coverage" of python code. I found only coverage.py but it calculates only percent of "statement coverage". | [Coverage.py now includes branch coverage](http://nedbatchelder.com/code/coverage/branch.html).
For the curious: the code is not modified before running. The trace function tracks which lines follow which in the execution, and compare that information with static analysis of the compiled byte code to find path possibilities not executed. | I haven't used it myself, but if you are willing to replace coverage analysis with [mutation testing](http://en.wikipedia.org/wiki/Mutation_testing "mutation testing"), I've heard of a mutation tester called "pester".
While I was doing googling, I also came across [a list of python testing tools](http://www.pycheesecake.org/wiki/PythonTestingToolsTaxonomy) which mentions some possible code coverage tools. | condition coverage in python | [
"",
"python",
"unit-testing",
"code-coverage",
""
] |
I need to Copy folder C:\FromFolder to C:\ToFolder
Below is code that will CUT my FromFolder and then will create my ToFolder.
So my FromFolder will be gone and all the items will be in the newly created folder called ToFolder
```
System.IO.Directory.Move(@"C:\FromFolder ", @"C:\ToFolder");
```
But i just want to Copy the files in FromFolder to ToFolder.
For some reason there is no System.IO.Directory.Copy???
How this is done using a batch file - Very easy
xcopy C:\FromFolder C:\ToFolder
Regards
Etienne | This link provides a nice example.
<http://msdn.microsoft.com/en-us/library/cc148994.aspx>
Here is a snippet
```
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
``` | there is a file copy.
Recreate folder and copy all the files from original directory to the new one
[example](http://www.java2s.com/Tutorial/CSharp/0300__File-Directory-Stream/CopyDirectory.htm)
```
static void Main(string[] args)
{
DirectoryInfo sourceDir = new DirectoryInfo("c:\\a");
DirectoryInfo destinationDir = new DirectoryInfo("c:\\b");
CopyDirectory(sourceDir, destinationDir);
}
static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
{
if (!destination.Exists)
{
destination.Create();
}
// Copy all files.
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files)
{
file.CopyTo(Path.Combine(destination.FullName,
file.Name));
}
// Process subdirectories.
DirectoryInfo[] dirs = source.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
// Get destination directory.
string destinationDir = Path.Combine(destination.FullName, dir.Name);
// Call CopyDirectory() recursively.
CopyDirectory(dir, new DirectoryInfo(destinationDir));
}
}
``` | Copy Folders in C# using System.IO | [
"",
"c#",
"asp.net",
"file-io",
".net",
""
] |
I have a Linq provider that sucessfully goes and gets data from my chosen datasource, but what I would like to do now that I have my filtered resultset, is allow Linq to Objects to process the rest of the Expression tree (for things like Joins, projection etc)
My thought was that I could just replace the expression constant that contains my IQueryProvider with the result-sets IEnumerable via an ExpressionVisitor and then return that new expression. Also return the IEnumerable's provider from my IQueryable...but this does not seem to work :-(
Any idea's?
Edit:
Some good answers here, but given the form...
```
var qry = from c in MyProv.Table<Customer>()
Join o in MyProv.Table<Order>() on c.OrderID equals o.ID
select new
{
CustID = c.ID,
OrderID = o.ID
}
```
In my provider I can easily get back the 2 resultsets from Customers and Orders, if the data was from a SQL source I would just construct and pass on the SQL Join syntax, but it this case the data is not from a SQL source so I need to do the join in code...but as I said I have the 2 result sets, and Linq to Objects can do a join...(and later the projection) it would be real nice to just substitute the Expression constants `MyProv.Table<Customer>` and `MyProv.Table<Order>` with `List<Customer>` and `List<Order>` and let a `List<>` provider process the expression...is that possible? how? | The kind of thing that I was after was replacing the Queryable<> constant in the expression tree with a concrete IEnumerable (or IQueryable via .AsQueryable()) result set...this is a complex topic that probably only makes any sense to Linq Provider writers who are knee deep in expression tree visitors etc.
I found a snippet on the msdn walkthrough that does something like what I am after, this gives me a way forward...
```
using System;
using System.Linq;
using System.Linq.Expressions;
namespace LinqToTerraServerProvider
{
internal class ExpressionTreeModifier : ExpressionVisitor
{
private IQueryable<Place> queryablePlaces;
internal ExpressionTreeModifier(IQueryable<Place> places)
{
this.queryablePlaces = places;
}
internal Expression CopyAndModify(Expression expression)
{
return this.Visit(expression);
}
protected override Expression VisitConstant(ConstantExpression c)
{
// Replace the constant QueryableTerraServerData arg with the queryable Place collection.
if (c.Type == typeof(QueryableTerraServerData<Place>))
return Expression.Constant(this.queryablePlaces);
else
return c;
}
}
}
``` | Both of the previous answers work, but it reads better if you use AsEnumerable() to cast the IQueryable to IEnumerable:
```
// Using Bob's code...
var result = datacontext.Table
.Where(x => x.Prop == val)
.OrderBy(x => x.Prop2)
.AsEnumerable() // <---- anything after this is done by LINQ to Objects
.Select(x => new { CoolProperty = x.Prop, OtherProperty = x.Prop2 });
```
EDIT:
```
// ... or MichaelGG's
var res = dc.Foos
.Where(x => x.Bla > 0) // uses IQueryable provider
.AsEnumerable()
.Where(y => y.Snag > 0); // IEnumerable, uses LINQ to Objects
``` | Performing part of a IQueryable query and deferring the rest to Linq for Objects | [
"",
"c#",
"linq",
"expression-trees",
"iqueryable",
""
] |
Is there a way to terminate a process started with the subprocess.Popen class with the "shell" argument set to "True"? In the working minimal example below (uses wxPython) you can open and terminate a Notepad process happily, however if you change the Popen "shell" argument to "True" then the Notepad process doesn't terminate.
```
import wx
import threading
import subprocess
class MainWindow(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title)
self.main_panel = wx.Panel(self, -1)
self.border_sizer = wx.BoxSizer()
self.process_button = wx.Button(self.main_panel, -1, "Start process", (50, 50))
self.process_button.Bind(wx.EVT_BUTTON, self.processButtonClick)
self.border_sizer.Add(self.process_button)
self.main_panel.SetSizerAndFit(self.border_sizer)
self.Fit()
self.Centre()
self.Show(True)
def processButtonClick(self, event):
if self.process_button.GetLabel() == "Start process":
self.process_button.SetLabel("End process")
self.notepad = threading.Thread(target = self.runProcess)
self.notepad.start()
else:
self.cancel = 1
self.process_button.SetLabel("Start process")
def runProcess(self):
self.cancel = 0
notepad_process = subprocess.Popen("notepad", shell = False)
while notepad_process.poll() == None: # While process has not yet terminated.
if self.cancel:
notepad_process.terminate()
break
def main():
app = wx.PySimpleApp()
mainView = MainWindow(None, wx.ID_ANY, "test")
app.MainLoop()
if __name__ == "__main__":
main()
```
Please accept for the sake of this question that "shell" does have to equal "True". | Based on the tip given in Thomas Watnedal's answer, where he points out that just the shell is actually being killed in the example, I have arranged the following function which solves the problem for my scenario, based on the example given in Mark Hammond's PyWin32 library:
procname is the name of the process as seen in Task Manager without the extension, e.g. FFMPEG.EXE would be killProcName("FFMPEG"). Note that the function is reasonably slow as it performs enumeration of all current running processes so the result is not instant.
```
import win32api
import win32pdhutil
import win32con
def killProcName(procname):
"""Kill a running process by name. Kills first process with the given name."""
try:
win32pdhutil.GetPerformanceAttributes("Process", "ID Process", procname)
except:
pass
pids = win32pdhutil.FindPerformanceAttributesByName(procname)
# If _my_ pid in there, remove it!
try:
pids.remove(win32api.GetCurrentProcessId())
except ValueError:
pass
handle = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pids[0])
win32api.TerminateProcess(handle, 0)
win32api.CloseHandle(handle)
``` | Why are you using `shell=True`?
Just don't do it. You don't need it, it invokes the shell and that is useless.
I don't accept it has to be `True`, because it doesn't. Using `shell=True` only brings you problems and no benefit. Just avoid it at all costs. Unless you're running some shell internal command, you don't need it, **ever**. | Python 2.6 on Windows: how to terminate subprocess.Popen with "shell=True" argument? | [
"",
"python",
"windows",
"windows-xp",
"subprocess",
"python-2.6",
""
] |
If a variable refers to either a function or a class method, how can I find out which one it is and get the class type in case it is a class method especially when the class is still being declared as in the given example.
eg.
```
def get_info(function_or_method):
print function_or_method
class Foo(object):
def __init__(self):
pass
get_info(__init__)
def bar():
pass
get_info(bar)
```
**Update to question after the first two responses from David and J. F. Sebastian**
To reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to `get_info(__init__)` happens I would like to be able to detect that its a method being declared as a part of a class.
This question came up since I am putting a decorator around it and it gets a handle to the **init** function and I can't actually figure out if a method is being declared within a class or as a stand alone function | > To reemphasize a point which J.F. Sebastian alluded to, I want to be able to distinguish it when the function is being declared within the class (when the type I am getting is a function and not a bound or unbound method). ie. where the first call to `get_info(__init__)` happens I would like to be able to detect that its a method being declared as a part of a class.
>
> This question came up since I am putting a decorator around it and it gets a handle to the init function and I can't actually figure out if a method is being declared within a class or as a stand alone function
You can't. J.F. Sebastian's answer is still 100% applicable. When the body of the class definition is being executed, the class itself doesn't exist yet. The statements (the `__init__` function definition, and the `get_info(__init__)` call) happen in a new local namespace; at the time the call to `get_info` occurs, `__init__` is a reference to the function in that namespace, which is indistinguishable from a function defined outside of a class. | You can distinguish between the two by checking the type:
```
>>> type(bar)
<type 'function'>
>>> type(Foo.__init__)
<type 'instancemethod'>
```
or
```
>>> import types
>>> isinstance(bar, types.FunctionType)
True
>>> isinstance(bar, types.UnboundMethodType)
True
```
which is the way you'd do it in an `if` statement.
Also, you can get the class from the `im_class` attribute of the method:
```
>>> Foo.__init__.im_class
__main__.Foo
``` | How to distinguish between a function and a class method? | [
"",
"python",
"reflection",
"metaprogramming",
""
] |
see above... | I faced the same question a couple years ago. The clear answer to which option, at the time, was Dundas Charts. And indeed, we did use Dundas Charts, with ease.
Since then, MS has acquired their chart codebase and included it in their 3.5 framework. You can easily use it with ASP.NET. Check out this blog post:
<http://weblogs.asp.net/scottgu/archive/2008/11/24/new-asp-net-charting-control-lt-asp-chart-runat-quot-server-quot-gt.aspx>
```
<asp:chart ...
```
Another third-party controls library I've used for charting is [Devexpress](http://www.devexpress.com/). It took very little time to get a product up and rolling with Devexpress (maybe even less), but in the end, Dundas had more functionality for customization. | [ZedGraph](http://zedgraph.org/wiki/index.php?title=Main_Page) | What options do I have available in C# asp.net to draw charts on websites? | [
"",
"c#",
"asp.net",
"charts",
""
] |
I just found out about **JRuby**, and I like the idea of running Ruby on Rails and being able to call Java libraries.
I would like to know about some experiences with running enterprise production applications in JRuby. Are stability and performance acceptable?
Thanks. | Here is a blog post from a company that created a cross-platform, multithreaded, desktop simulation application with JRuby. I think their success indicates JRuby is ready for enterprise production applications.
<http://spin.atomicobject.com/2009/01/30/ruby-for-desktop-applications-yes-we-can> | Actually it's pretty fast too. I'm not sure how they all compare now, but with the new dynamic invoke bytecode added to the JVM, it should become by far the fastest implementation available.
Groovy and Grails should also get a big speed boost from this pretty soon. | Is JRuby ready for production? | [
"",
"java",
"ruby-on-rails",
"jruby",
""
] |
I'm writing a GIS client tool in C# to retrieve "features" in a GML-based XML schema (sample below) from a server. Extracts are limited to 100,000 features.
I guestimate that the largest *extract.xml* might get up around 150 megabytes, so obviously DOM parsers are out I've been trying to decide between [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx "XmlSerializer") and [XSD.EXE](http://msdn.microsoft.com/en-us/library/x6c1kb0s.aspx "XSD.EXE - Visual Studio XML-schema-binder generator tool") generated bindings --OR-- [XmlReader](http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx "XmlReader class") and a hand-crafted object graph.
Or maybe there's a better way which I haven't considered yet? Like XLINQ, or ????
Please can anybody guide me? Especially with regards to the memory efficiency of any given approach. If not I'll have to "prototype" both solutions and profile them side-by-side.
I'm a bit of a raw prawn in .NET. Any guidance would be greatly appreciated.
Thanking you. Keith.
---
**Sample XML** - upto 100,000 of them, of upto 234,600 coords per feature.
```
<feature featId="27168306" fType="vegetation" fTypeId="1129" fClass="vegetation" gType="Polygon" ID="0" cLockNr="51598" metadataId="51599" mdFileId="NRM/TIS/VEGETATION/9543_22_v3" dataScale="25000">
<MultiGeometry>
<geometryMember>
<Polygon>
<outerBoundaryIs>
<LinearRing>
<coordinates>153.505004,-27.42196 153.505044,-27.422015 153.503992 .... 172 coordinates omitted to save space ... 153.505004,-27.42196</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</geometryMember>
</MultiGeometry>
</feature>
``` | Use `XmlReader` to parse large XML documents. `XmlReader` provides fast, forward-only, non-cached access to XML data. (Forward-only means you can read the XML file from beginning to end but cannot move backwards in the file.) `XmlReader` uses small amounts of memory, and is equivalent to using a simple SAX reader.
```
using (XmlReader myReader = XmlReader.Create(@"c:\data\coords.xml"))
{
while (myReader.Read())
{
// Process each node (myReader.Value) here
// ...
}
}
```
You can use XmlReader to process files that are up to 2 gigabytes (GB) in size.
Ref: [How to read XML from a file by using Visual C#](http://support.microsoft.com/kb/307548) | Asat 14 May 2009: I've switched to using a hybrid approach... see code below.
This version has most of the advantages of both:
\* the XmlReader/XmlTextReader (memory efficiency --> speed); and
\* the XmlSerializer (code-gen --> development expediancy and flexibility).
It uses the XmlTextReader to iterate through the document, and creates "doclets" which it deserializes using the XmlSerializer and "XML binding" classes generated with XSD.EXE.
I guess this recipe is universally applicable, and it's fast... I'm parsing a 201 MB XML Document containing 56,000 GML Features in about 7 seconds... the old VB6 implementation of this application took minutes (or even hours) to parse large extracts... so I'm lookin' good to go.
Once again, a **BIG** Thank You to the forumites for donating your valuable time. I really appreciate it.
Cheers all. Keith.
```
using System;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Collections.Generic;
using nrw_rime_extract.utils;
using nrw_rime_extract.xml.generated_bindings;
namespace nrw_rime_extract.xml
{
internal interface ExtractXmlReader
{
rimeType read(string xmlFilename);
}
/// <summary>
/// RimeExtractXml provides bindings to the RIME Extract XML as defined by
/// $/Release 2.7/Documentation/Technical/SCHEMA and DTDs/nrw-rime-extract.xsd
/// </summary>
internal class ExtractXmlReader_XmlSerializerImpl : ExtractXmlReader
{
private Log log = Log.getInstance();
public rimeType read(string xmlFilename)
{
log.write(
string.Format(
"DEBUG: ExtractXmlReader_XmlSerializerImpl.read({0})",
xmlFilename));
using (Stream stream = new FileStream(xmlFilename, FileMode.Open))
{
return read(stream);
}
}
internal rimeType read(Stream xmlInputStream)
{
// create an instance of the XmlSerializer class,
// specifying the type of object to be deserialized.
XmlSerializer serializer = new XmlSerializer(typeof(rimeType));
serializer.UnknownNode += new XmlNodeEventHandler(handleUnknownNode);
serializer.UnknownAttribute +=
new XmlAttributeEventHandler(handleUnknownAttribute);
// use the Deserialize method to restore the object's state
// with data from the XML document.
return (rimeType)serializer.Deserialize(xmlInputStream);
}
protected void handleUnknownNode(object sender, XmlNodeEventArgs e)
{
log.write(
string.Format(
"XML_ERROR: Unknown Node at line {0} position {1} : {2}\t{3}",
e.LineNumber, e.LinePosition, e.Name, e.Text));
}
protected void handleUnknownAttribute(object sender, XmlAttributeEventArgs e)
{
log.write(
string.Format(
"XML_ERROR: Unknown Attribute at line {0} position {1} : {2}='{3}'",
e.LineNumber, e.LinePosition, e.Attr.Name, e.Attr.Value));
}
}
/// <summary>
/// xtractXmlReader provides bindings to the extract.xml
/// returned by the RIME server; as defined by:
/// $/Release X/Documentation/Technical/SCHEMA and
/// DTDs/nrw-rime-extract.xsd
/// </summary>
internal class ExtractXmlReader_XmlTextReaderXmlSerializerHybridImpl :
ExtractXmlReader
{
private Log log = Log.getInstance();
public rimeType read(string xmlFilename)
{
log.write(
string.Format(
"DEBUG: ExtractXmlReader_XmlTextReaderXmlSerializerHybridImpl." +
"read({0})",
xmlFilename));
using (XmlReader reader = XmlReader.Create(xmlFilename))
{
return read(reader);
}
}
public rimeType read(XmlReader reader)
{
rimeType result = new rimeType();
// a deserializer for featureClass, feature, etc, "doclets"
Dictionary<Type, XmlSerializer> serializers =
new Dictionary<Type, XmlSerializer>();
serializers.Add(typeof(featureClassType),
newSerializer(typeof(featureClassType)));
serializers.Add(typeof(featureType),
newSerializer(typeof(featureType)));
List<featureClassType> featureClasses = new List<featureClassType>();
List<featureType> features = new List<featureType>();
while (!reader.EOF)
{
if (reader.MoveToContent() != XmlNodeType.Element)
{
reader.Read(); // skip non-element-nodes and unknown-elements.
continue;
}
// skip junk nodes.
if (reader.Name.Equals("featureClass"))
{
using (
StringReader elementReader =
new StringReader(reader.ReadOuterXml()))
{
XmlSerializer deserializer =
serializers[typeof (featureClassType)];
featureClasses.Add(
(featureClassType)
deserializer.Deserialize(elementReader));
}
continue;
// ReadOuterXml advances the reader, so don't read again.
}
if (reader.Name.Equals("feature"))
{
using (
StringReader elementReader =
new StringReader(reader.ReadOuterXml()))
{
XmlSerializer deserializer =
serializers[typeof (featureType)];
features.Add(
(featureType)
deserializer.Deserialize(elementReader));
}
continue;
// ReadOuterXml advances the reader, so don't read again.
}
log.write(
"WARNING: unknown element '" + reader.Name +
"' was skipped during parsing.");
reader.Read(); // skip non-element-nodes and unknown-elements.
}
result.featureClasses = featureClasses.ToArray();
result.features = features.ToArray();
return result;
}
private XmlSerializer newSerializer(Type elementType)
{
XmlSerializer serializer = new XmlSerializer(elementType);
serializer.UnknownNode += new XmlNodeEventHandler(handleUnknownNode);
serializer.UnknownAttribute +=
new XmlAttributeEventHandler(handleUnknownAttribute);
return serializer;
}
protected void handleUnknownNode(object sender, XmlNodeEventArgs e)
{
log.write(
string.Format(
"XML_ERROR: Unknown Node at line {0} position {1} : {2}\t{3}",
e.LineNumber, e.LinePosition, e.Name, e.Text));
}
protected void handleUnknownAttribute(object sender, XmlAttributeEventArgs e)
{
log.write(
string.Format(
"XML_ERROR: Unknown Attribute at line {0} position {1} : {2}='{3}'",
e.LineNumber, e.LinePosition, e.Attr.Name, e.Attr.Value));
}
}
}
``` | What is the best way to parse (big) XML in C# Code? | [
"",
"c#",
"xml",
"xml-serialization",
"xmlreader",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.