Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
**The original question is below, but I changed the title because I think it will be easier to find others with the same doubt. In the end, a XHTML document is a XML document.**
It's a beginner question, but I would like to know which do you think is the best library for parsing XHTML documents in PHP5?
I have generated the XHTML from HTML files (which where created using Word :S) with Tidy, and know I need to replace some elements from them (like the and element, replace some attributes in
tags).
I haven't used XML very much, there seems to be many options for parsing in PHP (Simple XML, DOM, etc.) and I don't know if all of them can do what I need, an which is the easiest one to use.
Sorry for my English, I'm form Argentina. Thanks!
**I bit more information:** I have a lot of HTML pages, done in Word 97. I used Tidy for cleaning and turning them in XHTML Strict, so now they are all XML compatible. I want to use an XML parser to find some elements and replace them (the logic by which I do this doesn't matter). For example, I want all of the pages to use the same CSS stylesheet and class attributes, for unified appearance. They are all static pages which contains legal documents, nothing strange there. Which of the extensions should I use? Is SimpleXML enough? Should I learn DOM in spite of being more difficult?
|
Just to clear up the confusion here. PHP has a number of XML libraries, because php4 didn't have very good options in that direction. From PHP5, you have the choice between [SimpleXml](http://docs.php.net/manual/en/book.simplexml.php), [DOM](http://docs.php.net/manual/en/book.dom.php) and the [sax-based expat parser](http://docs.php.net/manual/en/book.xml.php). The latter also existed in php4. php4 also had a DOM extension, which is **not** the same as php5's.
DOM and SimpleXml are alternatives to the same problem domain; They læoad the document into memory and let you access it as a tree-structure. DOM is a rather bulky api, but it's also very consistent and it's implemented in many languages, meaning that you can re-use your knowledge across languages (In Javascript for example). SimpleXml may be easier initially.
The SAX parser is a different beast. It treats an xml document as a stream of tags. This is useful if you are dealing with very large documents, since you don't need to hold it all in memory.
For your usage, I would probably use the DOM api.
|
You could use [SimpleXML](https://www.php.net/simplexml), which is included in a default PHP install. This extensions offers easy object-oriented access to XML-structures.
There's also [DOM XML](http://nl2.php.net/domxml). A "downside" to this extension is that it is a bit harder to use and that it is not included by default.
|
What's the difference between the different XML parsing libraries in PHP5?
|
[
"",
"php",
"xml",
"parsing",
"xhtml",
""
] |
Is there a way to get Visual Studio 2008 to do matching brace highlighting for Javascript?
If there is no way to do it in Studio, can it be done using ReSharper?
Thanks!!
|
Note that Visual Studio will still find a matching brace in JavaScript via Ctrl + ].
|
Here is an extension for VS2010 that will do just what you desire. And it's free!
<http://visualstudiogallery.msdn.microsoft.com/872d27ee-38c7-4a97-98dc-0d8a431cc2ed>
|
Brace highlighting in Visual Studio for Javascript?
|
[
"",
"javascript",
"visual-studio-2008",
"ide",
"resharper",
""
] |
I need to pad the output of an integer to a given length.
For example, with a length of 4 digits, the output of the integer 4 is "0004" instead of "4". How can I do this in C# 2.0?
|
Use the string.Format command.
```
output = String.Format("{0:0000}", intVariable);
```
More details: <http://msdn.microsoft.com/en-us/library/fht0f5be.aspx>
|
i think it was:
intVal.ToString( "####" );
but there is some [useful documentation here](http://msdn.microsoft.com/en-us/library/8wch342y.aspx)
|
Integer formatting, padding to a given length
|
[
"",
"c#",
"string",
"integer",
"format",
""
] |
I need to tweak some variables (only in a development setting) without having to restart IIS or anything (so I assume Web.Config is the wrong place to put them). Where is the easiest place to put about 500 config settings that have to be read for every request and written to, like I said, while IIS is running?
**EDIT**: Like I said, this is only for some Q&D development so I don't care about performance in any way. A database is a bit of overkill (and is probably more work than I want to deal with), I want something fast (like Settings), that I don't have to worry about parsing and can read from and write to. If I do XML, where do I write the file to so I don't have to spend time messing around with permissions?
|
In a database?
|
500 Config Settings to be read for every request? I'd put them in a database so they can be indexed and cached. A separate XML or data file would also most likely be cached in memory by the web server, but still wouldn't provide the performance an indexed database table could. But it depends on how you are accessing the settings.
|
Best way to have a live readable config file in Asp.Net
|
[
"",
"c#",
"asp.net",
"configuration-files",
""
] |
I am trying to upload files using the FileReference class. Files >2MB all work correctly but files <2MB cause this error:
> "java.io.IOException: Corrupt form data: premature ending"
On the server I am using the com.oreilly.servlet package to handle the request.
I have used this package many times to successfully handle file uploads from flex, but for some reason, now I am having this problem.
Here is the stack trace for some more info:
```
java.io.IOException: Corrupt form data: premature ending
at com.oreilly.servlet.multipart.MultipartParser.<init>(MultipartParser.java:205)
at com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:222)
at com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:173)
at com.mydomain.FileUploadServlet.doPost(FileUploadServlet.java:46)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.struts2.dispatcher.ActionContextCleanUp.doFilter(ActionContextCleanUp.java:99)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:414)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188)
```
|
It seems that there is a bug that exists when using com.orielly.servlet.MultipartRequest class and the org.apache.struts2.dispatcher.ActionContextCleanUp filter together. This is what was causing small file uploads to fail.
|
<http://www.servlets.com/cos/faq.html>
***Why when using com.oreilly.servlet.MultipartRequest or MultipartParser do large uploads fail?***
The classes themselves were specifically designed to have no maximum upload size limit (unlike most other file upload utilities), but for your server's protection the constructor allows you to set a maximum POST size to accept. Any upload larger than the limit is halted. The default maximum is 1 Meg. For a discussion of the difficulties a server has in notifying a client of the error, see the discussion in Java Servlet Programming, 2nd Edition, page 119.
So, did you specify the maximum POST size to accept?
P.S. Ok, now I see that it's small uploads that cause the problem. On the FAQ link above there is a section dedicated to troubleshooting uploads, including some helful methods to isolate the cause (client, browser, web-server, libraries). Try them.
Install a Firefox plugin (Tamper Data or Firebug) that shows the request sent to server. May help you to understand if anything is different between <2M and >2M uploads.
P.P.S. Are the files of the same structure? Could it be that smaller ones have different data (e.g. special symbols) that break Flash library? Try to upload small files of spaces only, for instance.
|
Corrupt form data: premature ending
|
[
"",
"java",
"actionscript-3",
"apache-flex",
""
] |
I'm using the javax.mail system, and having problems with "Invalid Address" exceptions. Here's the basics of the code:
```
// Get system properties
Properties props = System.getProperties();
// Setup mail server
props.put("mail.smtp.host", m_sending_host);
// Get session
Session session = Session.getDefaultInstance(props, new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(m_sending_user, m_sending_pass);
}
});
// Define message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(m_sending_from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(vcea.get(i).emailaddr));
message.setSubject( replaceEnvVars(subject) );
message.setText(replaceEnvVars(body));
// Send message
try {
Transport.send(message);
} catch (Exception e){
Log.Error("Error sending e-mail to addr (%s): %s",
vcea.get(i).emailaddr, e.getLocalizedMessage() );
}
```
The issue is that the above code does work, sometimes. But for some e-mail addresses that I know to be valid (because I can send to them via a standard e-mail client), the above code will throw an "Invalid Address" exception when trying to send.
Any clues or hints would be greatly appreciated.
--Update: problem with authentication.
Ok, here's what I've discovered was going on. When receiving e-mail, the code above correctly sets up authentication and the Authenticator.getPasswordAuthentication() callback is actually invoked.
Not so when sending e-mail. You have to do a bit more. Add this:
```
// Setup mail server
props.put("mail.smtp.host", m_sending_host);
props.put("mail.smtp.auth", "true");
```
which will force the javax.mail API to do the login authentication. And then use an actual Transport instance instead of the static .send() method:
```
Transport t = session.getTransport(m_sending_protocol);
t.connect(m_sending_user, m_sending_pass);
```
...
```
// Send message
try {
t.sendMessage(message, message.getAllRecipients());
} catch (Exception e){
```
Without forcing the authentication, the mail server saw me as an unauthorized relay, and just shut me down. The difference between the addresses that "worked" and the addresses that didn't was that the ones that "worked" were all local to the mail server. Therefore, it simply accepted them. But for any non-local "relay" addresses, it would reject the message because my authentication information hadn't been presented by the javax.mail API when I thought it would have.
Thanks for the clues to prompt me to look at the mail server side of things as well.
|
--Update: problem with authentication.
Ok, here's what I've discovered was going on. When receiving e-mail, the code above correctly sets up authentication and the Authenticator.getPasswordAuthentication() callback is actually invoked.
Not so when sending e-mail. You have to do a bit more. Add this:
```
// Setup mail server
props.put("mail.smtp.host", m_sending_host);
props.put("mail.smtp.auth", "true");
```
which will force the javax.mail API to do the login authentication. And then use an actual Transport instance instead of the static .send() method:
```
Transport t = session.getTransport(m_sending_protocol);
t.connect(m_sending_user, m_sending_pass);
```
...
```
// Send message
try {
t.sendMessage(message, message.getAllRecipients());
} catch (Exception e){
```
Without forcing the authentication, the mail server saw me as an unauthorized relay, and just shut me down. The difference between the addresses that "worked" and the addresses that didn't was that the ones that "worked" were all local to the mail server. Therefore, it simply accepted them. But for any non-local "relay" addresses, it would reject the message because my authentication information hadn't been presented by the javax.mail API when I thought it would have.
Thanks for the clues to prompt me to look at the mail server side of things as well.
|
I would change the call to InternetAddress to use the "strict" interpretation and see if you get further errors on the addresses you are having trouble with.
```
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(vcea.get(i).emailaddr, true ));
// ^^^^ turns on strict interpretation
```
[Javadoc for InternetAddress constructor](http://java.sun.com/products/javamail/javadocs/javax/mail/internet/InternetAddress.html#InternetAddress(java.lang.String,%20boolean))
If this fails, it will throw an `AddressException` which has a method called `getPos()` which returns the position of the failure ([Javadoc](http://java.sun.com/products/javamail/javadocs/javax/mail/internet/AddressException.html#getPos()))
|
Getting Invalid Address with javax.mail when the addresses are fine
|
[
"",
"java",
"email",
""
] |
Is there anything out there freeware or commercial that can facilitate analysis of memory usage by a PHP application? I know xdebug can produce trace files that shows memory usage by function call but without a graphical tool the data is hard to interpret.
Ideally I would like to be able to view not only total memory usage but also what objects are on the heap and who references them similar to [Jprofiler](http://www.codework.com/jprofiler/product.htm).
|
As you probably know, Xdebug dropped the memory profiling support since the 2.\* version. Please search for the "removed functions" string here: <http://www.xdebug.org/updates.php>
> **Removed functions**
>
> Removed support for Memory profiling as that didn't work properly.
So I've tried another tool and it worked well for me.
<https://github.com/arnaud-lb/php-memory-profiler>
This is what I've done on my Ubuntu server to enable it:
```
sudo apt-get install libjudy-dev libjudydebian1
sudo pecl install memprof
echo "extension=memprof.so" > /etc/php5/mods-available/memprof.ini
sudo php5enmod memprof
service apache2 restart
```
And then in my code:
```
<?php
memprof_enable();
// do your stuff
memprof_dump_callgrind(fopen("/tmp/callgrind.out", "w"));
```
Finally open the `callgrind.out` file with [KCachegrind](http://kcachegrind.sourceforge.net/html/Home.html)
# Using Google gperftools (recommended!)
First of all install the **Google gperftools** by downloading the latest package here: <https://code.google.com/p/gperftools/>
Then as always:
```
sudo apt-get update
sudo apt-get install libunwind-dev -y
./configure
make
make install
```
Now in your code:
```
memprof_enable();
// do your magic
memprof_dump_pprof(fopen("/tmp/profile.heap", "w"));
```
Then open your terminal and launch:
```
pprof --web /tmp/profile.heap
```
*pprof* will create a new window in your existing browser session with something like shown below:

# Xhprof + Xhgui (the best in my opinion to profile both cpu and memory)
With **Xhprof** and **Xhgui** you can profile the cpu usage as well or just the memory usage if that's your issue at the moment.
It's a very complete solutions, it gives you full control and the logs can be written both on mongo or in the filesystem.
For more details [see my answer here](https://stackoverflow.com/questions/16787462/php-xdebug-how-to-profile-forked-process/31388948#31388948).
# Blackfire
Blackfire is a PHP profiler by SensioLabs, the Symfony2 guys <https://blackfire.io/>
If you use [puphpet](https://puphpet.com/) to set up your virtual machine you'll be happy to know it's supported ;-)
|
I came across the same issue recently, couldn't find any specific tools unfortunately.
But something that helped was to output the xdebug trace in human readable format with mem deltas enabled (an INI setting, xdebug.show\_mem\_deltas or something I think?). Then run sort (if you are on \*nix) on the output:
```
sort -bgrk 3 -o sorted.txt mytracefile.xt
```
That sorts on the third col, the mem deltas. You can also sort on the second column, in which case you can find the line at which your app uses the most memory in total.
Of course, this can't detect when an object's memory usage only creeps up in small increments but ends up using a lot of memory overall. I have a fairly dumb method that attempts to do this using a combination of object iteration and serialization. It probably doesn't equate exactly to memory usage, but hopefully gives an idea of where to start looking. Bear in mind it will use up memory itself, and also has not been extensively tested, so buyer beware:
```
function analyzeMem($obj, $deep=false)
{
if (!is_scalar($obj))
{
$usage = array('Total'=>strlen(serialize($obj)));
while (list($prop, $propVal) = each($obj))
{
if ($deep && (is_object($propVal) || is_array($propVal)))
{
$usage['Children'][$prop] = analyzeMem($propVal);
}
else
{
$usage['Children'][$prop] = strlen(serialize($propVal));
}
}
return $usage;
}
else
{
return strlen(serialize($obj));
}
}
print_r(analyzeMem(get_defined_vars()));
```
Also, just got suggested this method by a colleague (cheers Dennis ;-) This hides the steps that are below 2 levels of indentation, you can quite easily see the points where the overall memory usage jumps up, and can narrow things down by increasing the indentation:
```
egrep '[0-9]+ ( ){1,2}-> ' mytracefile.xt
```
|
Tools to visually analyze memory usage of a PHP app
|
[
"",
"php",
"memory-management",
"profiling",
""
] |
How can I launch an application using C#?
Requirements:
Must work on [Windows XP](http://en.wikipedia.org/wiki/Windows_XP) and [Windows Vista](http://en.wikipedia.org/wiki/Windows_Vista).
I have seen a sample from DinnerNow.net sampler that only works in Windows Vista.
|
Use [`System.Diagnostics.Process.Start()`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx) method.
Check out [this article](http://www.codeproject.com/KB/cs/start_an_external_app.aspx) on how to use it.
```
Process.Start("notepad", "readme.txt");
string winpath = Environment.GetEnvironmentVariable("windir");
string path = System.IO.Path.GetDirectoryName(
System.Windows.Forms.Application.ExecutablePath);
Process.Start(winpath + @"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe",
path + "\\MyService.exe");
```
|
Here's a snippet of helpful code:
```
using System.Diagnostics;
// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = arguments;
// Enter the executable to run, including the complete path
start.FileName = ExeName;
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
int exitCode;
// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
proc.WaitForExit();
// Retrieve the app's exit code
exitCode = proc.ExitCode;
}
```
There is much more you can do with these objects, you should read the documentation: [ProcessStartInfo](http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.aspx), [Process](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx).
|
Launching an application (.EXE) from C#?
|
[
"",
"c#",
".net",
"windows-vista",
"windows-xp",
""
] |
Returning to WinForms in VS2008 after a long time.. Tinkering with a OOD problem in VS2008 Express Edition.
I need some controls to be "display only" widgets. The user should not be able to change the value of these controls... the widgets are updated by a periodic update tick event. I vaguely remember there being a ReadOnly property that you could set to have this behavior... can't find it now.
The **Enabled** property set to false: grays out the control content. I want the control to look normal.
The **Locked** property set to false: seems to be protecting the user from accidentally distorting the control in the Visual Form Designer.
What am I missing?
|
For some typical winforms controls:
<http://jquiz.wordpress.com/2007/05/29/c-winforms-readonly-controls/>
This is also a good tip to preserve the appearance:
```
Color clr = textBox1.BackColor;
textBox1.ReadOnly = true;
textBox1.BackColor = clr;
```
|
To make the forms control Readonly instantly on one click do use the following peice of Code :
```
public void LockControlValues(System.Windows.Forms.Control Container)
{
try
{
foreach (Control ctrl in Container.Controls)
{
if (ctrl.GetType() == typeof(TextBox))
((TextBox)ctrl).ReadOnly = true;
if (ctrl.GetType() == typeof(ComboBox))
((ComboBox)ctrl).Enabled= false;
if (ctrl.GetType() == typeof(CheckBox))
((CheckBox)ctrl).Enabled = false;
if (ctrl.GetType() == typeof(DateTimePicker))
((DateTimePicker)ctrl).Enabled = false;
if (ctrl.Controls.Count > 0)
LockControlValues(ctrl);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
```
Then call it from your Button Click Event like this :
```
LockControlValues(this)
```
Hope, this helps to solve your problem :
Happy Programming,
Rajan Arora
www.simplyrajan.co.nr
|
How do I make a Windows Forms control readonly?
|
[
"",
"c#",
".net",
"winforms",
""
] |
OK, so I've read through various posts about teaching beginner's to program, and there were some helpful things I will look at more closely. But what I want to know is whether there are any effective tools out there to teach a kid *Java* specifically?
I want to teach him Java specifically because (a) with my strong background in C I feel that's too complex, (b) Java is the other language I know extremely well and therefore I can assist meaningfully without needing to teach myself a new but (to me) useless language, and (c) I feel that managed languages are the future, and lastly (d) Java is one of the simplest of all the languages I know well (aside from basic).
I learned in basic, and I am open to teaching that first, but I am unaware of a decent free basic shell for Windows (though I haven't really searched, yet since it's not my first choice), and would anyway want to progress quickly to Java.
My son is 8, so that's a couple of years earlier than I started - but he has expressed an
interest in learning to program (possibly because I work from home a lot and he sees me programming all the time).
If no-one can suggest a tool designed for this purpose, I will probably start him off with text/console based apps to teach the basics, and then progress to GUI building.
Oh, one last thing, I am not a fan of IDE's (old school text editor type), so I would not be put off at all by a system that has him typing real code, and would likely prefer that to a toy drag/drop system.
EDIT: Just to clarify; I really am specifically after ways to teach him Java; there are already a good many posts with good answers for other language alternatives - but that's not what I am looking for here.
EDIT: What about Java frameworks for 2D video games - can anyone recommend any of them from personal experience? I like the idea of him starting with the mechanics in place (main game loop, scoring, etc) and adding the specifics for a game of his own imagining - that's what I did, though for me it was basic on a Commodore VIC-20 and a Sinclair ZX-81.
|
Just make the learning fun and all the rest will follow !
Amazingly Scala might be the easiest language if you try [Kojo](http://www.kogics.net/sf:kojo)
(Scala is better Java, you have access to all Java libraries of course)
|
You may find some inspiration in this project:
[Teaching Kids Programming: Even Younger Kids Can Learn Java](http://java.sys-con.com/node/44575)
> Java Programming for Kids, Parents and Grandparents.
You can find here at the [faratasystems web site](http://www.faratasystems.com/?page_id=69) (direct link [here](http://myflex.org/yf/JavaKid811.pdf))
Amongst the lessons learned during such a project, the author mentions:
* Most of the programming tasks require minimal knowledge of arithmetic and algebra skills. To start programming, a kid needs to understand what x = y+2 means. Another important concept to understand is an if statement.
* Kids develop the abstract reasoning abilities by the fourth-fifth grade, and they also easily perform such tasks as browsing the Web, downloading and installing software. Dave have learned how to type, compile and run Java programs in Eclipse IDE in no time.
* Kids learn much faster than adults, but they do not have "previous programming experience", which may actually be a good thing, because they do not have to switch from a procedural to object-oriented way of thinking. After learning about inheritance, Dave called my wife a superclass.
* Adults are responsible creatures, and they can keep doing boring operations much longer that kids. Programming lessons with kids have to be short. One or two 45-minute lessons per week is enough. High school kids should be able to study more, but I do not have such experience yet.
* Illustrations help. In my book I've included lots of color cartoon-like characters that are like a Java-fabric softener.

* Kids like to see immediate results and enjoy playing with shorter programs, for example a class Fish has a method dive(int howDeep). Let me try to call this method several times with different arguments...

* Graphical programming is the most fun, and even a fairly large program like Calculator, Tic-Tac-Toe or Ping Pong can be explained to children.
|
What's a good way to teach my son to program Java
|
[
"",
"java",
""
] |
Programming is learned by writing programs. But code reading is said to be another good way of learning. I would like to improve my unit-testing skills by reading, examining real-world code. Could you recommend any open source projects where the source is extensively tested with unit tests?
I'm interested in code written in C++.
|
AFAIK C++ Boost libraries - <http://boost.org/> - have broadly covered code base, and a policy that every new piece of code must have unit tests with it. Might be worth checking.
|
The [Chromium](http://code.google.com/chromium/) project.
|
Could you recommend any open source projects where the source is extensively tested with unit tests?
|
[
"",
"c++",
"unit-testing",
"open-source",
""
] |
I have written a script that goes through a bunch of files and snips out a portion of the files for further processing. The script creates a new directory and creates new files for each snip that is taken out. I have to now evaluate each of the files that were created to see if it is what I needed. The script also creates an html index file with links to each of the snips. So I can click the hyperlink to see the file, make a note in a spreadsheet to indicate if the file is correct or not and then use the back button in the browser to take me back to the index list.
I was sitting here wondering if I could somehow create a delete button in the browser next to the hyperlink. My thought is I would click the hyperlink, make a judgment about the file and if it is not one I want to keep then when I get back to the main page I just press the delete button and it is gone from the directory.
Does anyone have any idea if this is possible. I am writing this in python but clearly the issue is is there a way to create an htm file with a delete button-I would just use Python to write the commands for the deletion button.
|
Well I finally found an answer that achieved what I wanted-I did not want to learn a new language-Python is hard enough given my lack or experience
```
def OnDelete(self, event):
assert self.current, "invalid delete operation"
try:
os.remove(os.path.join(self.cwd, self.current))
```
|
You could make this even simpler by making it all happen in one main page. Instead of having a list of hyperlinks, just have the main page have one frame that loads one of the autocreated pages in it. Put a couple of buttons at the bottom - a "Keep this page" and a "Delete this page." When you click either button, the main page refreshes, this time with the next autocreated page in the frame.
You could make this as a cgi script in your favorite scripting language. You can't just do this in html because an html page only does stuff client-side, and you can only delete files server-side. You will probably need as cgi args the page to show in the frame, and the last page you viewed if the button click was a "delete".
|
Can I Use Python to Make a Delete Button in a 'web page'
|
[
"",
"python",
"web-applications",
"browser",
""
] |
I created a list of lists:
```
>>> xs = [[1] * 4] * 3
>>> print(xs)
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
```
Then, I changed one of the innermost values:
```
>>> xs[0][0] = 5
>>> print(xs)
[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]
```
Why did every first element of each sublist change to `5`?
---
See also:
* [How do I clone a list so that it doesn't change unexpectedly after assignment?](https://stackoverflow.com/questions/2612802) for workarounds for the problem
* [List of dictionary stores only last appended value in every iteration](https://stackoverflow.com/questions/46835197) for an analogous problem with a list of dicts
* [How do I initialize a dictionary of empty lists in Python?](https://stackoverflow.com/questions/11509721) for an analogous problem with a dict of lists
|
When you write `[x]*3` you get, essentially, the list `[x, x, x]`. That is, a list with 3 references to the same `x`. When you then modify this single `x` it is visible via all three references to it:
```
x = [1] * 4
xs = [x] * 3
print(f"id(x): {id(x)}")
# id(x): 140560897920048
print(
f"id(xs[0]): {id(xs[0])}\n"
f"id(xs[1]): {id(xs[1])}\n"
f"id(xs[2]): {id(xs[2])}"
)
# id(xs[0]): 140560897920048
# id(xs[1]): 140560897920048
# id(xs[2]): 140560897920048
x[0] = 42
print(f"x: {x}")
# x: [42, 1, 1, 1]
print(f"xs: {xs}")
# xs: [[42, 1, 1, 1], [42, 1, 1, 1], [42, 1, 1, 1]]
```
To fix it, you need to make sure that you create a new list at each position. One way to do it is
```
[[1]*4 for _ in range(3)]
```
which will reevaluate `[1]*4` each time instead of evaluating it once and making 3 references to 1 list.
---
You might wonder why `*` can't make independent objects the way the list comprehension does. That's because the multiplication operator `*` operates on objects, without seeing expressions. When you use `*` to multiply `[[1] * 4]` by 3, `*` only sees the 1-element list `[[1] * 4]` evaluates to, not the `[[1] * 4` expression text. `*` has no idea how to make copies of that element, no idea how to reevaluate `[[1] * 4]`, and no idea you even want copies, and in general, there might not even be a way to copy the element.
The only option `*` has is to make new references to the existing sublist instead of trying to make new sublists. Anything else would be inconsistent or require major redesigning of fundamental language design decisions.
In contrast, a list comprehension reevaluates the element expression on every iteration. `[[1] * 4 for n in range(3)]` reevaluates `[1] * 4` every time for the same reason `[x**2 for x in range(3)]` reevaluates `x**2` every time. Every evaluation of `[1] * 4` generates a new list, so the list comprehension does what you wanted.
Incidentally, `[1] * 4` also doesn't copy the elements of `[1]`, but that doesn't matter, since integers are immutable. You can't do something like `1.value = 2` and turn a 1 into a 2.
|
```
size = 3
matrix_surprise = [[0] * size] * size
matrix = [[0]*size for _ in range(size)]
```
[Live visualization](http://pythontutor.com/visualize.html#code=size%20%3D%203%0Amatrix_surprise%20%3D%20%5B%5B0%5D%20*%20size%5D%20*%20size%0Amatrix%20%3D%20%5B%5B0%5D*size%20for%20_%20in%20range%28size%29%5D&cumulative=false&curInstr=9&heapPrimitives=false&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false) using Python Tutor:
[](https://i.stack.imgur.com/AE8xf.png)
|
List of lists changes reflected across sublists unexpectedly
|
[
"",
"python",
"list",
"nested-lists",
"mutable",
""
] |
Is std::string size() a O(1) operation?
The implementation of STL I'm using is the one built into VC++
|
If you're asking if MSVC's implementation of string::size() has constant complexity, then the answer is yes. But [Don Wakefield](https://stackoverflow.com/questions/256033/is-stdstring-size-a-o1-operation#256081) mentioned Table 65 in 23.1 of the C++ Standard where it says that the complexity of `size()` should follow what's said in 'Note A'. Note A says:
> Those entries marked ‘‘(Note A)’’
> should have constant complexity.
However, that does not mean that those entries *shall* have constant complexity. Standards use very specific terminology, and "should" means that it is not mandatory.
'Note A' was added to the standard specifically to appease those who believed that `size()` should be allowed to have linear complexity so it would not be necessary to keep the size when the containers were modified.
So you can't rely on `size()` having constant complexity, but I'm honestly not sure if there are any implementations that do not have a constant `string::size()`.
|
Yes, std::string::size() is O(1).
|
Is std::string size() a O(1) operation?
|
[
"",
"c++",
"visual-c++",
"stl",
"stdstring",
""
] |
I have a base class with an optional virtual function
```
class Base {
virtual void OnlyImplementThisSometimes(int x) {}
};
```
When I compile this I get a warning about the unused param x. Is there some other way I should have implemented the virtual function? I have re-written it like this:
```
class Base {
virtual void OnlyImplementThisSometimes(int x)
{
x = 0;
}
};
```
I also have the problem that if I'm not careful, the subclass I make can implement the wrong function and then I don't notice because of overloading: e.g.
```
class Derived : public Base {
void OnlyImplementThisSometimes(int x, int y) { // some code }
};
Derived d;
Base *b = dynamic_cast<Base *>(&d);
b->OnlyImplementThisSometimes(x); // calls the method in the base class
```
The base class method was called because I implemented the derived function with an "int y" param but there is no warning about this. Are these just common pitfalls in C++ or have I misunderstood virtual functions?
|
Ignoring the design issues you can get around the compiler warning about an unused variable by omitting the variable name, for example:
```
virtual void OnlyImplementThisSometimes(int ) { }
```
Mistakenly implementing the wrong method signature when trying to override the virtual function is just something you need to be careful about in C++. Languages like C# get around this with the 'override' keyword.
|
We define a macro `_unused` as:
```
#define _unused(x) ((void)x)
```
Then define the function as:
```
virtual void OnlyImplementThisSometimes(int x) { _unused( x );}
```
This not only keeps the compiler from complaining, but makes it obvious to anyone maintaining the code that you haven't forgotten about x -- you are *intentionally* ignoring it.
|
Are non-pure virtual functions with parameters bad practice?
|
[
"",
"c++",
"polymorphism",
""
] |
What are you using for binding XML to Java? JAXB, Castor, and XMLBeans are some of the available choices. The comparisons that I've seen are all three or four years old. I'm open to other suggestions. Marshalling / unmarshalling performance and ease of use are of particular interest.
Clarification: I'd like to see not just what framework you use, but your reasoning for using one over the others.
|
[JiBX](http://www.jibx.org). Previously I used [Castor XML](http://www.castor.org/xml-framework.html), but JiBX proved to be significantly better, particularly in terms of performance (a straight port of some application code from Castor XML to JiBX made it 9x faster). I also found the mapping format for JiBX to be more elegant than Castor's.
JiBX achieves its performance by using post-compilation bytecode manipulation rather than the reflection approach adopted by Castor. This has the advantage that it places fewer demands on the way that you write your mapped classes. There is no need for getters, setters and no-arg constructors just to satisfy the tools. Most of the time you can write the class without considering mapping issues and then map it without modifications.
|
If you want to make an informed decision you need to be clear why you are translating between XML and java objects. The reason being that the different technologies in this space try to solve different problems. The different tools fall into two categories:
1. XML data binding - refers to the process of representing the information in an XML document as an object in computer memory. Typically, this means defining an XSD and generating a java source code equivalent. Interop between different languages is top priority (hence the use of XSD) - most typically for the implementation of SOAP-based web services.
2. XML serialisation - refers to writing out a graph of in memory objects to a stream, so that it can be reconstituted somewhere or sometime else. You write the java classes by hand; the xml representation is of secondary importance. Also, the need for performance is often greater and the need for interoperation with other languages such as .net is often lower.
For xml serialisation, Xstream is hard to beat. JAXB is the standard for XML binding.
In either case, if you are using J2EE you'll need to pay careful attention to classes retrieved from JPA since class proxies and persistence specific collection types can confuse binding / serialization tools.
|
Java XML Binding
|
[
"",
"java",
"xml",
"jaxb",
"castor",
"xmlbeans",
""
] |
I'm using a `std::map` (VC++ implementation) and it's a little slow for lookups via the map's find method.
The key type is `std::string`.
Can I increase the performance of this `std::map` lookup via a custom key compare override for the map? For example, maybe `std::string` < compare doesn't take into consideration a simple `string::size()` compare before comparing its data?
Any other ideas to speed up the compare?
In my situation the map will always contain < 15 elements, but it is being queried non stop and performance is critical. Maybe there is a better data structure that I can use that would be faster?
Update: The map contains file paths.
Update2: The map's elements are changing often.
|
First, turn off all the profiling and DEBUG switches. These can slow down STL immensely.
If that's not it, part of the problem may be that your strings are identical for the first 80-90% of the string. This isn't bad for map, necessarily, but it is for string comparisons. If this is the case, your search can take much longer.
For example, in this code find() will likely result in a couple of string compares, but each will return after comparing the first character until "david", and then the first three characters will be checked. So at most, 5 characters will be checked per call.
```
map<string,int> names;
names["larry"] = 1;
names["david"] = 2;
names["juanita"] = 3;
map<string,int>::iterator iter = names.find("daniel");
```
On the other hand, in the following code, find() will likely check 135+ characters:
```
map<string,int> names;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/wilma"] = 1;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/fred"] = 2;
names["/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/barney"] = 3;
map<string,int>::iterator iter = names.find("/usr/local/lib/fancy-pants/share/etc/doc/foobar/longpath/yadda/yadda/betty");
```
That's because the string comparisons have to search deeper to find a match since the beginning of each string is the same.
Using size() in your comparison for equality won't help you much here since your data set is so small. A std::map is kept sorted so its elements can be searched with a binary search. Each call to find should result in less than 5 string comparisons for a miss, and an average of 2 comparisons for a hit. But it does depend on your data. If most of your path strings are of different lengths, then a size check like Motti describes could help a lot.
Something to consider when thinking of alternative algorithms is how many many "hits" you get. Are most of your find() calls returning end() or a hit? If most of your find()s return end() (misses) then you are searching the entire map every time (2logn string compares).
Hash\_map is a good idea; it should cut your search time in about half for hits; more for misses.
A custom algorithm may be called for because of the nature of path strings, especially if your data set has common ancestry like in the above code.
Another thing to consider is how you get your search strings. If you are reusing them, it may help to encode them into something that is easier to compare. If you use them once and discard them, then this encoding step is probably too expensive.
I used something like a Huffman coding tree once (a long time ago) to optimize string searches. A binary string search tree like that may be more efficient in some cases, but its pretty expensive for small sets like yours.
Finally, look into alternative std::map implementations. I've heard bad things about some of VC's stl code performance. The DEBUG library in particular is bad about checking you on every call. [StlPort](http://stlport.sourceforge.net/) used to be a good alternative, but I haven't tried it in a few years. I've always loved [Boost](http://www.boost.org/) too.
|
As [Even](https://stackoverflow.com/questions/256038/how-can-i-increase-the-performance-in-a-map-lookup-with-key-type-stdstring#256052) said the operator used in a `set` is `<` not `==`.
If you don't care about the order of the strings in your `set` you can pass the `set` a custom comparator that performs better than the regular *less-than*.
For example if a lot of your strings have similar prefixes (but they vary in length) you can sort by string length (since `string.length` is constant speed).
If you do so beware a common mistake:
```
struct comp {
bool operator()(const std::string& lhs, const std::string& rhs)
{
if (lhs.length() < rhs.length())
return true;
return lhs < rhs;
}
};
```
This operator does not maintain a [strict weak ordering](http://en.wikipedia.org/wiki/Strict_weak_ordering), as it can treat two strings as each less than the other.
```
string a = "z";
string b = "aa";
```
Follow the logic and you'll see that `comp(a, b) == true` and `comp(b, a) == true`.
The correct implementation is:
```
struct comp {
bool operator()(const std::string& lhs, const std::string& rhs)
{
if (lhs.length() != rhs.length())
return lhs.length() < rhs.length();
return lhs < rhs;
}
};
```
|
How can I increase the performance in a map lookup with key type std::string?
|
[
"",
"c++",
"dictionary",
"optimization",
"visual-c++",
"stdmap",
""
] |
Is it generally better to run functions on the webserver, or in the database?
Example:
```
INSERT INTO example (hash) VALUE (MD5('hello'))
```
or
```
INSERT INTO example (hash) VALUE ('5d41402abc4b2a76b9719d911017c592')
```
Ok so that's a really trivial example, but for scalability when a site grows to multiple websites or database servers, where is it best to "do the work"?
|
I try to think of the database as the place to persist stuff only, and put all abstraction code elsewhere. Database expressions are complex enough already without adding functions to them.
Also, the query optimizer will trip over any expressions with functions if you should ever end up wanting to do something like "SELECT .... WHERE MD5(xxx) = ... "
And database functions aren't very portable in general.
|
I try to use functions in my scripting language whenever calculations like that are required. I keep my SQL function useage down to a minimum, for a number of reasons.
The primary reason is that my one SQL database is responsible for hosting multiple websites. If the SQL server were to get bogged down with requests from one site, it would adversely affect the rest. This is even more important to consider if you are working on a shared server for example, although in this case you have little control over what the other users are doing.
The secondary reason is that I like my SQL code to be as portable as possible. I don't even want to *try* to count the different flavors of SQL that exist, so I try to keep functions (especially non-standard extensions) out of my SQL code, except for things like SUM or MIN/MAX.
I guess what I'm saying is, SQL is designed to store and retrieve data, and it should be kept to that purpose. Use your serving language of choice to perform any calculations beforehand, and keep your SQL code portable.
|
Functions in MySQL or PHP
|
[
"",
"php",
"mysql",
"performance",
""
] |
I'm writing a lightweight XML editor, and in cases where the user's input is not well formed, I would like to indicate to the user where the problem is, or at least where the first problem is. Does anyone know of an existing algorithm for this? If looking at code helps, if I could fill in the FindIndexOfInvalidXml method (or something like it), this would answer my question.
```
using System;
namespace TempConsoleApp
{
class Program
{
static void Main(string[] args)
{
string text = "<?xml version=\"1.0\"?><tag1><tag2>Some text.</taagg2></tag1>";
int index = FindIndexOfInvalidXml(text);
Console.WriteLine(index);
}
private static int FindIndexOfInvalidXml(string theString)
{
int index = -1;
//Some logic
return index;
}
}
}
```
|
I'd probably just cheat. :) This will get you a line number and position:
```
string s = "<?xml version=\"1.0\"?><tag1><tag2>Some text.</taagg2></tag1>";
System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
try
{
doc.LoadXml(s);
}
catch(System.Xml.XmlException ex)
{
MessageBox.Show(ex.LineNumber.ToString());
MessageBox.Show(ex.LinePosition.ToString());
}
```
|
Unless this is an academic exercise, I think that writing your own XML parser is probably not the best way to go about this. I would probably check out the [XmlDocument class](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx) within the System.Xml namespace and try/catch [exceptions](http://msdn.microsoft.com/en-us/library/system.xml.xmlexception.aspx) for the Load() or LoadXml() methods. The exception's message property should contain info on where the error occurred (row/col numbers) and I suspect it'd be easier to use a regular expression to extract those error messages and the related positional info.
|
How can I find the position where a string is malformed XML (in C#)?
|
[
"",
"c#",
"xml",
"algorithm",
""
] |
How can i generate bytecode (Byte[]) from a String at runtime, without using a "javac" process or something of this sort? is there a simple way of calling the compiler like that?
later addition:
I chose to [accept the solution that actually best fits **my** situation](https://stackoverflow.com/questions/200833/when-should-i-accept-an-answer). my application is a hobby-project still in design sketch phase, and it is the right time to consider inserting new technology. also, since the guy that's supposed to help me with BL is a JavaScript developer, the idea of using a JavaScript interpreter instead of a stub compiler+classLoader seems more appealing to me in this situation. other (unaccepted) answers of this question are informative and, as far as i can tell, answer my question very well, so thanks, but I'm going to try [Rhino](http://www.mozilla.org/rhino/) :)
|
You might find something like rhino or groovy more useful in practice.
|
JDK6 has a [Java compiler API](http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm). However, it's not necessarily very easy to use.
A quick google pulled up [this example usage](http://www.java2s.com/Code/Java/JDK-6/CompilingfromMemory.htm).
|
java in-memory compilation
|
[
"",
"java",
"runtime",
"compilation",
""
] |
I'm trying to create Excel 2007 Documents programmatically. Now, there are two ways I've found:
* Manually creating the XML, as outlined in [this post](https://stackoverflow.com/questions/150339/generating-an-excel-file-in-aspnet#150368)
* Using a Third Party Library like [ExcelPackage](http://www.codeplex.com/ExcelPackage).
Currently, I use ExcelPackage, which has some really serious drawbacks and issues. As I do not need to create overly complex Excel sheets (the most "complicated" thing is that I explicitely need to set a cell type to numeric or text), I 'm looking towards Option 1 next, but I just wonder if there are any other good and supported ways to generate Excel 2007 Sheets? Bonus Points if they can be created without having to save them to the harddrive, i.e. generate and directly output them into a stream.
.net 3.0 is the target here, no 3.5 goodness :(
**Edit:** Thanks so far. The XML SDK is indeed 3.5 only, but Russian Roulet... erm... COM Interop is also something I want to avoid whenever possible, especially since Excel 2007 has a somewhat complicated but still rather easy to create document format. I'll have a look at the various links and hints posted.
|
You could try using the [Office Open XML SDK](http://www.microsoft.com/downloads/details.aspx?FamilyID=c6e744e5-36e9-45f5-8d8c-331df206e0d0&DisplayLang=en). This will allow you to create Excel files in memory using say a `MemoryStream` and much more easily than generating all the XML by hand.
As Brian Kim pointed out, version 2.0 of the SDK requires .NET 3.5 which you stated wasn't available. [Version 1](http://www.microsoft.com/downloads/details.aspx?FamilyId=AD0B72FB-4A1D-4C52-BDB5-7DD7E816D046&displaylang=en) of the SDK is also available which supports .NET 3.0. It isn't as complete, but will at least help you manage the XML parts of the document and the relationships between them.
|
I'm just generating HTML table, which can be opened by Excel:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Wnioski</title>
<style type="text/css">
<!--
br { mso-data-placement: same-cell; }
td { mso-number-format: \@; mso-displayed-decimal-separator: "."; }
-->
</style>
<table>
<tr style="height:15.0pt">
<td style="mso-number-format: general">474</td>
<td>474</td>
<tr>
<td>data2</td>
<td>data3</td>
<tr>
<td style="mso-number-format: "yyyy-mm-dd"">2008-10-01</td>
<td style="mso-number-format: standard">0.00</td>
<tr>
<td style="mso-number-format: general">line1<br>line2<br>line3</td>
<td></td>
</table>
```
This works well also as a data source for serial letters in Word, works with OpenOffice calc etc. And it is dead simple to generate.
|
Programmatically creating Excel 2007 Sheets
|
[
"",
"c#",
".net",
"excel",
""
] |
I have noticed that my particular instance of Trac is not running quickly and has big lags. This is at the very onset of a project, so not much is in Trac (except for plugins and code loaded into SVN).
**Setup Info:** This is via a SELinux system hosted by WebFaction. It is behind Apache, and connections are over SSL. Currently the .htpasswd file is what I use to control access.
Are there any recommend ways to improve the performance of Trac?
|
It's hard to say without knowing more about your setup, but one easy win is to make sure that Trac is running in something like `mod_python`, which keeps the Python runtime in memory. Otherwise, every HTTP request will cause Python to run, import all the modules, and then finally handle the request. Using `mod_python` (or FastCGI, whichever you prefer) will eliminate that loading and skip straight to the good stuff.
Also, as your Trac database grows and you get more people using the site, you'll probably outgrow the default SQLite database. At that point, you should think about migrating the database to PostgreSQL or MySQL, because they'll be able to handle concurrent requests much faster.
|
We've had the best luck with FastCGI. Another critical factor was to only use `https` for authentication but use `http` for all other traffic -- I was really surprised how much that made a difference.
|
How to improve Trac's performance
|
[
"",
"python",
"performance",
"trac",
""
] |
I have a HTML file that has code similar to the following.
```
<table>
<tr>
<td id="MyCell">Hello World</td>
</tr>
</table>
```
I am using javascript like the following to get the value
```
document.getElementById(cell2.Element.id).innerText
```
This returns the text "Hello World" with only 1 space between hello and world. I MUST keep the same number of spaces, is there any way for that to be done?
I've tried using innerHTML, outerHTML and similar items, but I'm having no luck.
|
HTML is white space insensititive which means your DOM is too. Would wrapping your "Hello World" in **pre** block work at all?
|
In HTML,any spaces >1 are ignored, both in displaying text and in retrieving it via the DOM. The only guaranteed way to maintain spaces it to use a non-breaking space ` `.
|
Javascript Removing Whitespace When It Shouldn't?
|
[
"",
"javascript",
"dom",
"whitespace",
"innerhtml",
""
] |
I noticed that writing to a file, closing it and moving it to destination place randomly fails on Vista. Specifically, MoveFileEx() would return `ERROR_ACCESS_DENIED` for no apparent reason. This happens on Vista SP1 at least (32 bit). Does not happen on XP SP3.
Found [this thread](http://groups.google.com/group/microsoft.public.windows.file_system/browse_thread/thread/e9774e86e98eb623/3348d92b8ba5858d?lnk=raot&pli=1) on the internets about exactly the same problem, with no real solutions. So far it looks like the error is caused by Vista's search indexer, see below.
The code example given there is enough to reproduce the problem. I'm pasting it here as well:
```
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
bool test() {
unsigned char buf[] = {
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99
};
HANDLE h;
DWORD nbytes;
LPCTSTR fn_tmp = "aaa";
LPCTSTR fn = "bbb";
h = CreateFile(fn_tmp, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_ALWAYS, 0, 0);
if (h == INVALID_HANDLE_VALUE) return 0;
if (!WriteFile(h, buf, sizeof buf, &nbytes, 0)) goto error;
if (!FlushFileBuffers(h)) goto error;
if (!CloseHandle(h)) goto error;
if (!MoveFileEx(fn_tmp, fn, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH)) {
printf("error=%d\n", GetLastError());
return 0;
}
return 1;
error:
CloseHandle(h);
return 0;
}
int main(int argc, char** argv) {
unsigned int i;
for (i = 0;; ++i) {
printf("*%u\n", i);
if (!test()) return 1;
}
return 0;
}
```
Build this as console app with Visual Studio. Correct behaviour would be infinite loop that prints test numbers. On Vista SP1, the program exits after random number of iterations (usually before 100 iterations are made).
This does not happen on Windows XP SP2. There's no antivirus running at all; and no other strange background processes (machine is pretty much vanilla OS install + Visual Studio).
**Edit**: Digging further via Process Monitor (thanks @sixlettervariables), I can't see anything particularly bad. Each test iteration results in 176 disk operations, majority of them coming from SearchProtocolHost.exe (search indexer). If search indexing service is stopped, no errors occur, so it looks like it's the culprit.
At the time of failure (when the app gets `ERROR_ACCESS_DENIED`), SearchProtocolHost.exe has two CreateFile(s) to the detination file (bbb) open with read/write/delete share modes, so it should be ok. One of the opens is followed by opportunistic lock (`FSCTL_REQUEST_FILTER_OPLOCK`), maybe that's the cause?
Anyway, I found out that I can avoid the problem by setting `FILE_ATTRIBUTE_TEMPORARY` and `FILE_ATTRIBUTE_NOT_CONTENT_INDEXED` flags on the file. It looks like `FILE_ATTRIBUTE_NOT_CONTENT_INDEXED` is enough by itself, but marking file as temporary also dramatically cuts down disk operations caused by search indexer.
But this is **not a real solution**. I mean, if an application can't expect to be able to create a file and rename it because some Vista's search indexer is messing with it, **it's totally crazy**! Should it keep retrying? Yell at the user (which is very undesirable)? Do something else?
|
I suggest you use [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) *(edit: the artist formerly known as FileMon)* to watch and see which application exactly is getting in the way. It can show you the entire trace of file system calls made on your machine.
*(edit: thanks to @moocha for the change in application)*
|
I'd say it's either your anti-virus or Windows Indexing messing with the file at the same moment. Can you run the same test without an anti-virus. Then run it again making sure the temp file is created somewhere not indexed by Windows Search?
|
Random MoveFileEx failures on Vista
|
[
"",
"c++",
"windows",
"winapi",
"windows-vista",
""
] |
In C and C++ you can tell the compiler that a number is a 'long' by putting an 'l' at the end of the number.
e.g long x = 0l;
How can I tell the C# compiler that a number is a byte?
|
According to the [C# language specification](http://msdn.microsoft.com/en-us/library/aa664674(VS.71).aspx) there is no way to specify a byte literal. You'll have to cast down to byte in order to get a byte. Your best bet is probably to specify in hex and cast down, like this:
```
byte b = (byte) 0x10;
```
|
```
byte b = (byte) 123;
```
even though
```
byte b = 123;
```
does the same thing. If you have a variable:
```
int a = 42;
byte b = (byte) a;
```
|
How to cast a number to a byte?
|
[
"",
"c#",
"casting",
""
] |
How can one programmatically sort a union query when pulling data from two tables? For example,
```
SELECT table1.field1 FROM table1 ORDER BY table1.field1
UNION
SELECT table2.field1 FROM table2 ORDER BY table2.field1
```
Throws an exception
Note: this is being attempted on MS Access Jet database engine
|
Sometimes you need to have the `ORDER BY` in each of the sections that need to be combined with `UNION`.
In this case
```
SELECT * FROM
(
SELECT table1.field1 FROM table1 ORDER BY table1.field1
) DUMMY_ALIAS1
UNION ALL
SELECT * FROM
(
SELECT table2.field1 FROM table2 ORDER BY table2.field1
) DUMMY_ALIAS2
```
|
```
SELECT field1 FROM table1
UNION
SELECT field1 FROM table2
ORDER BY field1
```
|
SQL Query - Using Order By in UNION
|
[
"",
"sql",
"ms-access",
"sorting",
"sql-order-by",
"union",
""
] |
The [.NET coding standards PDF from SubMain](http://submain.com/landing/codeit.right/?utm_campaign=codeit.right&utm_medium=textad&utm_source=stackoverflow) that have started showing up in the "Sponsored By" area seems to indicate that properties are only appropriate for logical data members (see pages 34-35 of the document). Methods are deemed appropriate in the following cases:
* The operation is a conversion, such as Object.ToString().* The operation is expensive enough that you want to communicate to the user that they should consider caching the result.* Obtaining a property value using the get accessor would have an observable side effect.* Calling the member twice in succession produces different results.* The order of execution is important.* The member is static but returns a value that can be changed.* The member returns an array.
Do most developers agree on the properties vs. methods argument above? If so, why? If not, why not?
|
They seem sound, and basically in line with MSDN member design guidelines:
<http://msdn.microsoft.com/en-us/library/ms229059.aspx>
One point that people sometimes seem to forget (\*) is that callers should be able to set properties in any order. Particularly important for classes that support designers, as you can't be sure of the order generated code will set properties.
(\*) I remember early versions of the Ajax Control Toolkit on Codeplex had numerous bugs due to developers forgetting this one.
As for "Calling the member twice in succession produces different results", every rule has an exception, as the property DateTime.Now illustrates.
|
Those are interesting guidelines, and I agree with them. It's interesting in that they are setting the rules based on "everything is a property except the following". That said, they are good guidelines for avoiding problems by defining something as a property that can cause issues later.
At the end of the day a property is just a structured method, so the rule of thumb I use is based on Object Orientation -- if the member represents data owned by the entity, it should be defined as a property; if it represents behavior of the entity it should be implemented as a method.
|
What guidelines are appropriate for determining when to implement a class member as a property versus a method?
|
[
"",
"c#",
".net",
""
] |
I'd like to make sure that a thread is moved to a specific CPU core and can never be moved from it by the scheduler.
There's a `SetThreadAffinityMask()` call but there's no `GetThreadAffinityMask()`.
The reason I need this is because high resolution timers will get messed up if the scheduler moves that thread to another CPU.
|
You should probably just use SetThreadAffinityMask and trust that it is working.
[MSDN](http://msdn.microsoft.com/en-us/library/ms684251.aspx)
|
If you could call a function that returns a number indicating what CPU the thread is running on, without using affinity, the answer would often be wrong as soon as the function returned. So checking the mask returned by `SetThreadAffinityMask()` is as close as you're going to get, outside of kernel code running at elevated IRQL, and [even that's changing](http://kernelmustard.com/2008/09/30/bad-idea-making-assumptions-about-cpu-number/).
It sounds like you're trying to work around `RDTSC` clock skew issues. If you are using the `RDTSC` instruction directly, consider calling `QueryPerformanceCounter()` instead:
* `QueryPerformanceCounter()` on Windows Vista uses the [HPET](http://en.wikipedia.org/wiki/High_Precision_Event_Timer) if it is supported by the chipset and is in the system's ACPI tables.
* AMD-based systems using the [AMD Processor Driver](http://www.amd.com/us-en/Processors/TechnicalResources/0,,30_182_871_9706,00.html) will mostly compensate for multi-core clock skew if you call `QueryPerformanceCounter()`, but this does nothing for applications that use `RDTSC` directly. The [AMD Dual-Core Optimizer](http://www.amd.com/us-en/Processors/TechnicalResources/0,,30_182_871_9706,00.html) is a hack for applications that use `RDTSC` directly, but if the amount of clock skew is changing due to C1 clock ramping (where the clock speed is reduced in the C1 power state), you will still have clock skew. And these utilities probably aren't very widespread, so using affinity with `QueryPerformanceCounter()` is still a good idea.
|
On Win32 how do you move a thread to another CPU core?
|
[
"",
"c++",
"c",
"multithreading",
"winapi",
"multicore",
""
] |
I went to school for programming years ago and when I got out I found a job in system administration and that is the direction my career took. I'd like to get back into development of some sort and have been 'playing' with C# and ASP.NET, but I've been hearing lots of buzz for other 'new' languages (by new I mean that they are new to me) like Ruby and F#. I guess I'm wondering if I'm wasting my time with learning largely MS languages instead of being more of a generalist. Having not been apart of the development community for a long time (if ever I was) has me floundering with trends and I'd like not to be left behind the times.
Any thoughts to if it's better to follow the "latest" languages or stick with what is more tried and true technologies?
|
You should learn at least 1 compiled language (like C# or Java) and 1 Script Language (Python, Ruby, etc). This is usually enough to help most developers succeed at what they do, regardless of the age of the language.
As for new vs old, I'd stick with C# for now as it's pretty popular. Learning a new language wouldn't be too bad though.
|
C.
Seriously, learn C.
If you don't run screaming for the hills pulling your hair out then you're cut out to be a developer.
Note that I'm not saying that people who don't know C aren't developers (Jeff, the founder of this site, doesn't know C and he's doing just fine) but C will introduce you to a lot of the [less glamorous and sugar coated aspects](http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html) of development.
As a second choice, pick C#.
|
What to learn first?
|
[
"",
"c#",
"asp.net",
"ruby",
"f#",
""
] |
I'm writing a CESetup.dll for a Windows Mobile app. It must be unmanaged, which I have little experience with. So I'm unsure of whether I should free the memory I allocate and how I do it.
Here's the function I've written:
```
Uninstall_Init(
HWND hwndParent,
LPCTSTR pszInstallDir
)
{
LPTSTR folderPath = new TCHAR[256];
_stprintf(folderPath, _T("%s\\cache"), pszInstallDir);
EmptyDirectory(folderPath);
RemoveDirectory(folderPath);
_stprintf(folderPath, _T("%s\\mobileadmin.dat"), pszInstallDir);
DeleteFile(folderPath);
// To continue uninstallation, return codeUNINSTALL_INIT_CONTINUE
// If you want to cancel installation,
// return codeUNINSTALL_INIT_CANCEL
return codeUNINSTALL_INIT_CONTINUE;
}
```
As I understand it, folderPath is allocated on the heap. EmptyDirectory() is my own function that removes all content in the directory. RemoveDirectory() and DeleteFile() are system calls.
My question is should I deallocate `folderPath` before the function exits? If I should, how do I do it?
|
I think you want to use this:
```
delete [] folderPath;
```
It looks like you're allocating an array of TCHARs, which makes sense since it's a string. When you allocate an array, you must delete using the array delete operator (which you get by including the brackets in the delete statement). I'm pretty sure you'll get a memory leak with Treb's solution.
|
There is a common misperception I have seen with people who are unused to C/C++ programming - when they see a function with a pointer parameter, they think the variable must be allocated with *new*. That is not the case, a local variable is suitable and preferred, since you don't have to worry about its lifetime.
You could simplify your life tremendously by doing
```
TCHAR folderPath[256];
```
My preferred solution would be to use std::string, but I've put that in a separate answer.
|
Freeing memory on the heap. Should I and how?
|
[
"",
"c++",
"winapi",
"memory-management",
"windows-ce",
""
] |
I have a question at [SO](https://stackoverflow.com/questions/150038/how-to-wire-a-middle-tier-of-objects-to-a-data-tier-consisting-of-a-dataset#151255) asking how to wire a middle tier to a DataSet.
I put up an answer showing what I had come up with, but I am not happy with the tight coupling. I have just started to get into testing and find it a good goal for my code.
How would this code be de-coupled to allow for unit testing?
Thank you,
Keith
|
IMO; DataSets are evil. They are, and should only be used as, offline databases. Nothing more, IMO. However, what you do in your Data Access Layer (DAL) should not really impact your Business layer (BL). I'd just use objects (use interfaces) between them (IList) and then use an interface to define your DAL (IRepository) and the nyou can mock that interface to return whatever you need in your BL for unit testing. Unit testing Datasets is another beast, never tried it and I hopefully never have to... Perhaps an in-memory database is your best bet there...
Oh, and for mocking I've used RhinoMock with some success. I'd also encourage you to look at IoCs (<http://www.castleproject.org/>).
|
You need IOC (inversion of control) and mock objects.
I encourage you to watch [dnrTV episode 126](http://www.dnrtv.com/default.aspx?showNum=126) with James Kovacs.
He demonstrates exactly what you are looking for.
|
How to decouple a middle tier and a dataset to allow for unit testing?
|
[
"",
"c#",
".net",
"integration-testing",
""
] |
For my C# RichTextBox, I want to programmatically do the same thing as clicking the up arrow at the top of a vertical scroll bar, which moves the RichTextBox display up by one line. What is the code for this? Thanks!
|
Here's what I do:
```
using System.Runtime.InteropServices;
[DllImport("user32.dll")]
static extern int SendMessage(IntPtr hWnd, uint wMsg,
UIntPtr wParam, IntPtr lParam);
```
then call:
```
SendMessage(myRichTextBox.Handle, (uint)0x00B6, (UIntPtr)0, (IntPtr)(-1));
```
Seems to work OK - you might need to tweak things a bit, though.
Hope that helps.
|
For future reference the EM\_LINESCROLL message is what you send to any multi-line edit control to set the scroll position. You can scroll vertically or horizontally.
See [MSDN](http://msdn.microsoft.com/en-us/library/bb761615(VS.85).aspx) for details.
You can also use the Rich Edit Selection method, where you set the character index (which you can get with EM\_LINEINDEX) then call RichEdit.ScrollToCaret ie:
```
RichEdit.SelectionStart = SendMessage(RichEdit.Handle, EM_LINEINDEX, ScrollTo, 0);
RichEdit.ScrollToCaret();
```
This will scroll that line to the top of the edit control.
|
How to move scroll bar up by one line? (In C# RichTextBox)
|
[
"",
"c#",
"richtextbox",
"scrollbar",
""
] |
I have a database with DateTime fields that are currently stored in local time. An upcoming project will require all these dates to be converted to universal time. Rather than writing a c# app to convert these times to universal time, I'd rather use available sqlserver/sql features to accurately convert these dates to universal time so I only need an update script. To be accurate, the conversion would need to account for Daylight savings time fluctuations, etc.
|
A User Defined Function would allow you to write an SQL query that looks like this:
```
SELECT toUTC([MyDateColumn], [MyTimeZoneColumn]) FROM [MyTable]
```
Then you get universal times back from the server without a lot of ugly syntax in the query itself. Now you could build the UDF for this with regular SQL similar to what Chris posted, but SQL Server 2005 and later will let you build the UDF using CLR (.Net: C# optional) instead. It has much better support for dates and can do a better job taking timezones and daylight savings time into account.
|
SQL Doesn't have anything built in for this.
Two ways would be the `C# application` (you mentioned you don't want) or writing a really complicated update statement with something like:
```
UtcDate = DATEADD(hour, CASE WHEN OriginalDate BETWEEN x AND y THEN 4
WHEN OriginalDate BETWEEN x2 AND y2 THEN 5 ... END, OriginalDate)
```
Note - I'd recommend the `C# app` plus something like [TZ4Net](http://www.babiej.demon.nl/Tz4Net/main.htm) to handle the conversion.
|
How to convert a SqlServer DateTime to universal time using SQL
|
[
"",
"sql",
"sql-server",
"database",
""
] |
I have several `std::vector`, all of the same length. I want to sort one of these vectors, and apply the same transformation to all of the other vectors. Is there a neat way of doing this? (preferably using the STL or Boost)? Some of the vectors hold `int`s and some of them `std::string`s.
Pseudo code:
```
std::vector<int> Index = { 3, 1, 2 };
std::vector<std::string> Values = { "Third", "First", "Second" };
Transformation = sort(Index);
Index is now { 1, 2, 3};
... magic happens as Transformation is applied to Values ...
Values are now { "First", "Second", "Third" };
```
|
friol's approach is good when coupled with yours. First, build a vector consisting of the numbers 1…*n*, along with the elements from the vector dictating the sorting order:
```
typedef vector<int>::const_iterator myiter;
vector<pair<size_t, myiter> > order(Index.size());
size_t n = 0;
for (myiter it = Index.begin(); it != Index.end(); ++it, ++n)
order[n] = make_pair(n, it);
```
Now you can sort this array using a custom sorter:
```
struct ordering {
bool operator ()(pair<size_t, myiter> const& a, pair<size_t, myiter> const& b) {
return *(a.second) < *(b.second);
}
};
sort(order.begin(), order.end(), ordering());
```
Now you've captured the order of rearrangement inside `order` (more precisely, in the first component of the items). You can now use this ordering to sort your other vectors. There's probably a very clever in-place variant running in the same time, but until someone else comes up with it, here's one variant that isn't in-place. It uses `order` as a look-up table for the new index of each element.
```
template <typename T>
vector<T> sort_from_ref(
vector<T> const& in,
vector<pair<size_t, myiter> > const& reference
) {
vector<T> ret(in.size());
size_t const size = in.size();
for (size_t i = 0; i < size; ++i)
ret[i] = in[reference[i].first];
return ret;
}
```
|
```
typedef std::vector<int> int_vec_t;
typedef std::vector<std::string> str_vec_t;
typedef std::vector<size_t> index_vec_t;
class SequenceGen {
public:
SequenceGen (int start = 0) : current(start) { }
int operator() () { return current++; }
private:
int current;
};
class Comp{
int_vec_t& _v;
public:
Comp(int_vec_t& v) : _v(v) {}
bool operator()(size_t i, size_t j){
return _v[i] < _v[j];
}
};
index_vec_t indices(3);
std::generate(indices.begin(), indices.end(), SequenceGen(0));
//indices are {0, 1, 2}
int_vec_t Index = { 3, 1, 2 };
str_vec_t Values = { "Third", "First", "Second" };
std::sort(indices.begin(), indices.end(), Comp(Index));
//now indices are {1,2,0}
```
Now you can use the "indices" vector to index into "Values" vector.
|
How do I sort a std::vector by the values of a different std::vector?
|
[
"",
"c++",
"stl",
"boost",
"vector",
"sorting",
""
] |
This code always works, even in different browsers:
```
function fooCheck() {
alert(internalFoo()); // We are using internalFoo() here...
return internalFoo(); // And here, even though it has not been defined...
function internalFoo() { return true; } //...until here!
}
fooCheck();
```
I could not find a single reference to why it should work, though.
I first saw this in John Resig's presentation note, but it was only mentioned. There's no explanation there or anywhere for that matter.
Could someone please enlighten me?
|
The `function` declaration is magic and causes its identifier to be bound before anything in its code-block\* is executed.
This differs from an assignment with a `function` expression, which is evaluated in normal top-down order.
If you changed the example to say:
```
var internalFoo = function() { return true; };
```
it would stop working.
The function declaration is syntactically quite separate from the function expression, even though they look almost identical and can be ambiguous in some cases.
This is documented in the [ECMAScript standard](https://www.ecma-international.org/publications/standards/Ecma-262.htm), section **10.1.3**. Unfortunately ECMA-262 is not a very readable document even by standards-standards!
\*: the containing function, block, module or script.
|
It is called HOISTING - Invoking (calling) a function before it has been defined.
Two different types of function that I want to write about are:
Expression Functions & Declaration Functions
1. Expression Functions:
Function expressions can be stored in a variable so they do not need function names. They will also be named as an anonymous function (a function without a name).
To invoke (call) these functions they always need a ***variable name***. This kind of function won't work if it is called before it has been defined which means Hoisting is not happening here. We must always define the expression function first and then invoke it.
```
let lastName = function (family) {
console.log("My last name is " + family);
};
let x = lastName("Lopez");
```
This is how you can write it in ECMAScript 6:
```
lastName = (family) => console.log("My last name is " + family);
x = lastName("Lopez");
```
2. Declaration Functions:
Functions declared with the following syntax are not executed immediately. They are "saved for later use" and will be executed later, when they are invoked (called upon). This type of function works if you call it BEFORE or AFTER where is has been defined. If you call a declaration function before it has been defined Hoisting works properly.
```
function Name(name) {
console.log("My cat's name is " + name);
}
Name("Chloe");
```
Hoisting example:
```
Name("Chloe");
function Name(name) {
console.log("My cat's name is " + name);
}
```
|
Why can I use a function before it's defined in JavaScript?
|
[
"",
"javascript",
"function",
""
] |
In class, we are all 'studying' databases, and everyone is using Access. Bored with this, I am trying to do what the rest of the class is doing, but with raw SQL commands with MySQL instead of using Access.
I have managed to create databases and tables, but now how do I make a relationship between two tables?
If I have my two tables like this:
```
CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY ( account_id )
)
```
and
```
CREATE TABLE customers(
customer_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
address VARCHAR(20) NOT NULL,
city VARCHAR(20) NOT NULL,
state VARCHAR(20) NOT NULL,
PRIMARY KEY ( customer_id )
)
```
How do I create a 'relationship' between the two tables? I want each account to be 'assigned' one customer\_id (to indicate who owns it).
|
If the tables are innodb you can create it like this:
```
CREATE TABLE accounts(
account_id INT NOT NULL AUTO_INCREMENT,
customer_id INT( 4 ) NOT NULL ,
account_type ENUM( 'savings', 'credit' ) NOT NULL,
balance FLOAT( 9 ) NOT NULL,
PRIMARY KEY ( account_id ),
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
) ENGINE=INNODB;
```
You have to specify that the tables are innodb because myisam engine doesn't support foreign key. Look [here](http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html) for more info.
|
as ehogue said, put this in your CREATE TABLE
```
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
```
alternatively, if you already have the table created, use an ALTER TABLE command:
```
ALTER TABLE `accounts`
ADD CONSTRAINT `FK_myKey` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON DELETE CASCADE ON UPDATE CASCADE;
```
One good way to start learning these commands is using the [MySQL GUI Tools](http://dev.mysql.com/downloads/gui-tools/5.0.html), which give you a more "visual" interface for working with your database. The real benefit to that (over Access's method), is that after designing your table via the GUI, it shows you the SQL it's going to run, and hence you can learn from that.
|
How to create relationships in MySQL
|
[
"",
"mysql",
"sql",
"foreign-keys",
"relational-database",
""
] |
I'd like to set up a large linear programming model to solve an interesting problem. I would be most comfortable in Java. What tools/libraries are available?
|
I used [lp\_solve](http://lpsolve.sourceforge.net/5.5/) with success. It looks like there is a native Java API, but I've only used the text file interface. It supports the semi-standard MPS and LP file formats, which I found more convenient for trying out different solvers (such as [glpsol](http://www.gnu.org/software/glpk/)).
|
There were several suggestions from an [earlier question that I posted](https://stackoverflow.com/questions/143020/mathematical-optimization-library-for-java-free-or-open-source-recommendations):
* [CPLEX](http://www.ilog.com/products/cplex)
* [Dash](http://www.dashoptimization.com/home/cgi-bin/example.pl#bcl_java)
* [OptimJ](http://www.ateji.com/optimj.html)
* [COIN-OR](http://www.coin-or.org/)
* [lp\_solve](http://sourceforge.net/projects/lpsolve)
and possibly more...
|
Linear Programming Tool/Libraries for Java
|
[
"",
"java",
"linear-programming",
""
] |
I am getting the following error when I try to call a stored procedure that contains a SELECT Statement:
> The operation is not valid for the state of the transaction
Here is the structure of my calls:
```
public void MyAddUpdateMethod()
{
using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//do my first add update statement
//do my call to the select statement sp
bool DoesRecordExist = this.SelectStatementCall(id)
}
}
}
public bool SelectStatementCall(System.Guid id)
{
using(SQLServer Sql = new SQLServer(this.m_connstring)) //breaks on this line
{
//create parameters
//
}
}
```
Is the problem with me creating another connection to the same database within the transaction?
|
After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:
```
public void MyAddUpdateMethod()
{
using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//do my first add update statement
}
//removed the method call from the first sql server using statement
bool DoesRecordExist = this.SelectStatementCall(id)
}
}
public bool SelectStatementCall(System.Guid id)
{
using(SQLServer Sql = new SQLServer(this.m_connstring))
{
//create parameters
}
}
```
|
When I encountered this exception, there was an InnerException "Transaction Timeout". Since this was during a debug session, when I halted my code for some time inside the TransactionScope, I chose to ignore this issue.
When this specific exception with a timeout appears in deployed code, I think that the following section in you .config file will help you out:
```
<system.transactions>
<machineSettings maxTimeout="00:05:00" />
</system.transactions>
```
|
"The operation is not valid for the state of the transaction" error and transaction scope
|
[
"",
"c#",
".net",
"sql-server",
"transactions",
"transactionscope",
""
] |
SQL Server (2005/2008)
Each of the below statements have the same result. Does anyone know if one outperforms the other?
```
insert into SOMETABLE
values ('FieldOneValue','FieldTwoValue',3,4.55,'10/10/2008 16:42:00.000')
insert into SOMETABLE
select 'FieldOneValue','FieldTwoValue',3,4.55,'10/10/2008 16:42:00.000'
insert into SOMETALBE
Select
Field1 = 'FieldOneValue',
Field2 = 'FieldTwoValue',
Field3 = 3,
Field4 = 4.55,
Field5 = '10/10/2008 16:42:00.000'
```
Assuming of course that the data types match the table appropriately...
|
I just tested this.
5 million iterations of both approaches on two sets of hardware, one a server with 16GB RAM, one a notebook with 1GB.
Result: They appear to be the same.
The query plans for these are the same, and the performance differential is statistically insignificant.
|
i think, based on this question, you are to the point of [premature optimization](http://en.wikipedia.org/wiki/Code_optimization#When_to_optimize). i'd stick to the standard insert () values () if you are just inserting 1 record and let the Sql Server team make it the most performant.
|
Insert Into: Is one syntax more optimal or is it preference?
|
[
"",
"sql",
"performance",
"optimization",
"insert",
""
] |
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy?
Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.
In particular:
1. Where do you put the source?
2. Where do you put application startup scripts?
3. Where do you put the IDE project cruft?
4. Where do you put the unit/acceptance tests?
5. Where do you put non-Python data such as config files?
6. Where do you put non-Python sources such as C++ for pyd/so binary extension modules?
|
Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple.
* `/scripts` or `/bin` for that kind of command-line interface stuff
* `/tests` for your tests
* `/lib` for your C-language libraries
* `/doc` for most documentation
* `/apidoc` for the Epydoc-generated API docs.
And the top-level directory can contain README's, Config's and whatnot.
The hard choice is whether or not to use a `/src` tree. Python doesn't have a distinction between `/src`, `/lib`, and `/bin` like Java or C has.
Since a top-level `/src` directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application.
* `/foo`
* `/bar`
* `/baz`
I recommend putting all of this under the "name-of-my-product" directory. So, if you're writing an application named `quux`, the directory that contains all this stuff is named `/quux`.
Another project's `PYTHONPATH`, then, can include `/path/to/quux/foo` to reuse the `QUUX.foo` module.
In my case, since I use Komodo Edit, my IDE cuft is a single .KPF file. I actually put that in the top-level `/quux` directory, and omit adding it to SVN.
|
According to Jean-Paul Calderone's [Filesystem structure of a Python project](http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html):
```
Project/
|-- bin/
| |-- project
|
|-- project/
| |-- test/
| | |-- __init__.py
| | |-- test_main.py
| |
| |-- __init__.py
| |-- main.py
|
|-- setup.py
|-- README
```
|
What is the best project structure for a Python application?
|
[
"",
"python",
"directory-structure",
"organization",
"project-structure",
""
] |
I am developing a piece of software in Python that will be distributed to my employer's customers. My employer wants to limit the usage of the software with a time-restricted license file.
If we distribute the `.py` files or even `.pyc` files it will be easy to (decompile and) remove the code that checks the license file.
Another aspect is that my employer does not want the code to be read by our customers, fearing that the code may be stolen or at least the "novel ideas".
Is there a good way to handle this problem?
|
Python, being a byte-code-compiled interpreted language, is very difficult to lock down. Even if you use a exe-packager like [py2exe](http://py2exe.org), the layout of the executable is well-known, and the Python byte-codes are well understood.
Usually in cases like this, you have to make a tradeoff. How important is it really to protect the code? Are there real secrets in there (such as a key for symmetric encryption of bank transfers), or are you just being paranoid? Choose the language that lets you develop the best product quickest, and be realistic about how valuable your novel ideas are.
If you decide you really need to enforce the license check securely, write it as a small C extension so that the license check code can be extra-hard (but not impossible!) to reverse engineer, and leave the bulk of your code in Python.
|
"Is there a good way to handle this problem?" No. Nothing can be protected against reverse engineering. Even the firmware on DVD machines has been reverse engineered and the [AACS Encryption key](http://en.wikipedia.org/wiki/AACS_encryption_key_controversy) exposed. And that's in spite of the DMCA making that a criminal offense.
Since no technical method can stop your customers from reading your code, you have to apply ordinary commercial methods.
1. Licenses. Contracts. Terms and Conditions. This still works even when people can read the code. Note that some of your Python-based components may require that you pay fees before you sell software using those components. Also, some open-source licenses prohibit you from concealing the source or origins of that component.
2. Offer significant value. If your stuff is so good -- at a price that is hard to refuse -- there's no incentive to waste time and money reverse engineering anything. Reverse engineering is expensive. Make your product slightly less expensive.
3. Offer upgrades and enhancements that make any reverse engineering a bad idea. When the next release breaks their reverse engineering, there's no point. This can be carried to absurd extremes, but you should offer new features that make the next release more valuable than reverse engineering.
4. Offer customization at rates so attractive that they'd rather pay you to build and support the enhancements.
5. Use a license key which expires. This is cruel, and will give you a bad reputation, but it certainly makes your software stop working.
6. Offer it as a web service. SaaS involves no downloads to customers.
|
How do I protect Python code from being read by users?
|
[
"",
"python",
"licensing",
"obfuscation",
"copy-protection",
""
] |
I'm developing an application which has a lot of text and also different modules which can be included or not in every build.
For each saved project we generate automatically a report with all the details (i.e. description of algorithms used in that project and so on). Currently we embed all text as strings in the source code and we also support different languages through po and mo files.
The good points of the system is that it is very easy to dynamically generate documentation and report files.
The bad point is that having a lot of text in source code is ugly and the formatting (i.e. with html) is not comfortable, editing of the text is difficult, no easy spell check and terrible to translate.
So, the final question is: whould you rather embed documentation in code or write external documentation files (for example html) for different languages and parse them on runtime? Obviously the core text of the software, such us message boxes will stay in code anyway.
If it matters, I'm working in C++ with wxWidgets.
|
I think all text which may change between different versions of the code should be kept in separate property files. You can build a mechanism which maps message ids to the proper string from a property file, say map id 15 to "search" or to "busca" in the English and Spanish property files respectively. So a property file may be an XML or a CSV with id-message pairs.
When running your program, you supply it with the property file(s) as parameters.
When it starts, it first loads the property strings into a map, and then you will use
property[15] instead of the string "search". Of course, you can use a textual label instead of a numerical id.
I would also consider generating the documentation from the property files automatically, maybe using CSS. This makes it a lot easier to edit and translate the messages.
|
If I have lots of text to display, I typically store it in XML outside the application and read it as needed. This would work well for documentation, as well, I think. You could simply have a separate stylesheet to produce documentation from it. Localizing your application would then become a matter of maintaining the alternate translations separately -- could be done either internally as separate nodes in the XML file or organizationally by maintaining different XML files for each language.
While this approach will cause your program to take more time to start, I think the customer eventually wins because:
1. Your program text is cleaner (and easier to maintain)
2. You aren't forced to modify code to change text
3. You can support many more translations easily, making your product available to more people.
|
What's the best way to manage a lot of text in code (and also support translations)?
|
[
"",
"c++",
"documentation",
"internationalization",
""
] |
I have a list of tuples like this:
```
[
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
```
I want to iterate through this keying by the first item, so, for example, I could print something like this:
```
a 1 2 3
b 1 2
c 1
```
How would I go about doing this without keeping an item to track whether the first item is the same as I loop around the tuples? This feels rather messy (plus I have to sort the list to start with)...
|
```
l = [
('a', 1),
('a', 2),
('a', 3),
('b', 1),
('b', 2),
('c', 1),
]
d = {}
for x, y in l:
d.setdefault(x, []).append(y)
print d
```
produces:
```
{'a': [1, 2, 3], 'c': [1], 'b': [1, 2]}
```
|
Slightly simpler...
```
from collections import defaultdict
fq = defaultdict(list)
for n, v in myList:
fq[n].append(v)
print(fq) # defaultdict(<type 'list'>, {'a': [1, 2, 3], 'c': [1], 'b': [1, 2]})
```
|
Converting a list of tuples into a dict
|
[
"",
"python",
"list",
"dictionary",
"tuples",
"iteration",
""
] |
I was recently working with a `DateTime` object, and wrote something like this:
```
DateTime dt = DateTime.Now;
dt.AddDays(1);
return dt; // still today's date! WTF?
```
The intellisense documentation for `AddDays()` says it adds a day to the date, which it doesn't - it actually *returns* a date with a day added to it, so you have to write it like:
```
DateTime dt = DateTime.Now;
dt = dt.AddDays(1);
return dt; // tomorrow's date
```
This one has bitten me a number of times before, so I thought it would be useful to catalog the worst C# gotchas.
|
```
private int myVar;
public int MyVar
{
get { return MyVar; }
}
```
Blammo. Your app crashes with no stack trace. Happens all the time.
(Notice capital `MyVar` instead of lowercase `myVar` in the getter.)
|
**Type.GetType**
The one which I've seen bite lots of people is [`Type.GetType(string)`](http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx). They wonder why it works for types in their own assembly, and some types like `System.String`, but not `System.Windows.Forms.Form`. The answer is that it only looks in the current assembly and in `mscorlib`.
---
**Anonymous methods**
C# 2.0 introduced anonymous methods, leading to nasty situations like this:
```
using System;
using System.Threading;
class Test
{
static void Main()
{
for (int i=0; i < 10; i++)
{
ThreadStart ts = delegate { Console.WriteLine(i); };
new Thread(ts).Start();
}
}
}
```
What will that print out? Well, it entirely depends on the scheduling. It will print 10 numbers, but it probably won't print 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 which is what you might expect. The problem is that it's the `i` variable which has been captured, not its value at the point of the creation of the delegate. This can be solved easily with an extra local variable of the right scope:
```
using System;
using System.Threading;
class Test
{
static void Main()
{
for (int i=0; i < 10; i++)
{
int copy = i;
ThreadStart ts = delegate { Console.WriteLine(copy); };
new Thread(ts).Start();
}
}
}
```
---
**Deferred execution of iterator blocks**
This "poor man's unit test" doesn't pass - why not?
```
using System;
using System.Collections.Generic;
using System.Diagnostics;
class Test
{
static IEnumerable<char> CapitalLetters(string input)
{
if (input == null)
{
throw new ArgumentNullException(input);
}
foreach (char c in input)
{
yield return char.ToUpper(c);
}
}
static void Main()
{
// Test that null input is handled correctly
try
{
CapitalLetters(null);
Console.WriteLine("An exception should have been thrown!");
}
catch (ArgumentNullException)
{
// Expected
}
}
}
```
The answer is that the code within the source of the `CapitalLetters` code doesn't get executed until the iterator's `MoveNext()` method is first called.
I've got some other oddities on my [brainteasers page](https://jonskeet.uk/csharp/teasers.html).
|
What is the worst gotcha in C# or .NET?
|
[
"",
"c#",
".net",
""
] |
I have a `TreeView` windows forms control with an `ImageList`, and I want some of the nodes to display images, but the others to not have images.
I *don't* want a blank space where the image should be. I *don't* want an image that looks like the lines that the TreeView would draw if it didn't have an ImageList. How do I get it to draw images for some items and not others, without resorting to clumsy hacks like that?
|
I tried this once and I don't think it is possible.
If you try to set both `ImageKey` and `ImageIndex` to "not set" values the control just defaults `ImageIndex` to 0. The following code:
```
treeView.ImageKey = "Value";
Debug.WriteLine(treeView.ImageIndex);
treeView.ImageKey = null;
Debug.WriteLine(treeView.ImageIndex);
treeView.ImageIndex = -1;
Debug.WriteLine(treeView.ImageIndex);
```
Produces output:
```
-1
0
0
```
This kind of tells you that the control developers wanted to make sure that there was always a default image. That just leaves you with the hack options I'm afraid.
|
You need to set `ImageIndex` and `SelectedImageIndex` to a number that is higher than the number of values in your `ImageList`. For example, if you create this node and add it to your `TreeView`:
```
TreeNode node1 = new TreeNode(string.Empty, 12, 12); // imageList1.Count = 5
```
you will have an invisible `TreeNode` inserted into your `TreeView`. I changed the background color of my `TreeView` and it was still invisible.
(I googled this for some time, and I eventually found the answer here: <http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.windowsforms/2006-09/msg00322.html>)
|
How do I set an image for some but not all nodes in a TreeView?
|
[
"",
"c#",
".net",
"winforms",
"treeview",
""
] |
Is it possible to define an implicit conversion of enums in c#?
something that could achieve this?
```
public enum MyEnum
{
one = 1, two = 2
}
MyEnum number = MyEnum.one;
long i = number;
```
If not, why not?
|
There is a solution. Consider the following:
```
public sealed class AccountStatus
{
public static readonly AccountStatus Open = new AccountStatus(1);
public static readonly AccountStatus Closed = new AccountStatus(2);
public static readonly SortedList<byte, AccountStatus> Values = new SortedList<byte, AccountStatus>();
private readonly byte Value;
private AccountStatus(byte value)
{
this.Value = value;
Values.Add(value, this);
}
public static implicit operator AccountStatus(byte value)
{
return Values[value];
}
public static implicit operator byte(AccountStatus value)
{
return value.Value;
}
}
```
The above offers implicit conversion:
```
AccountStatus openedAccount = 1; // Works
byte openedValue = AccountStatus.Open; // Works
```
This is a fair bit more work than declaring a normal enum (though you can refactor some of the above into a common generic base class). You can go even further by having the base class implement IComparable & IEquatable, as well as adding methods to return the value of DescriptionAttributes, declared names, etc, etc.
I wrote a base class (RichEnum<>) to handle most fo the grunt work, which eases the above declaration of enums down to:
```
public sealed class AccountStatus : RichEnum<byte, AccountStatus>
{
public static readonly AccountStatus Open = new AccountStatus(1);
public static readonly AccountStatus Closed = new AccountStatus(2);
private AccountStatus(byte value) : base (value)
{
}
public static implicit operator AccountStatus(byte value)
{
return Convert(value);
}
}
```
The base class (RichEnum) is listed below.
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Resources;
namespace Ethica
{
using Reflection;
using Text;
[DebuggerDisplay("{Value} ({Name})")]
public abstract class RichEnum<TValue, TDerived>
: IEquatable<TDerived>,
IComparable<TDerived>,
IComparable, IComparer<TDerived>
where TValue : struct , IComparable<TValue>, IEquatable<TValue>
where TDerived : RichEnum<TValue, TDerived>
{
#region Backing Fields
/// <summary>
/// The value of the enum item
/// </summary>
public readonly TValue Value;
/// <summary>
/// The public field name, determined from reflection
/// </summary>
private string _name;
/// <summary>
/// The DescriptionAttribute, if any, linked to the declaring field
/// </summary>
private DescriptionAttribute _descriptionAttribute;
/// <summary>
/// Reverse lookup to convert values back to local instances
/// </summary>
private static SortedList<TValue, TDerived> _values;
private static bool _isInitialized;
#endregion
#region Constructors
protected RichEnum(TValue value)
{
if (_values == null)
_values = new SortedList<TValue, TDerived>();
this.Value = value;
_values.Add(value, (TDerived)this);
}
#endregion
#region Properties
public string Name
{
get
{
CheckInitialized();
return _name;
}
}
public string Description
{
get
{
CheckInitialized();
if (_descriptionAttribute != null)
return _descriptionAttribute.Description;
return _name;
}
}
#endregion
#region Initialization
private static void CheckInitialized()
{
if (!_isInitialized)
{
ResourceManager _resources = new ResourceManager(typeof(TDerived).Name, typeof(TDerived).Assembly);
var fields = typeof(TDerived)
.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)
.Where(t => t.FieldType == typeof(TDerived));
foreach (var field in fields)
{
TDerived instance = (TDerived)field.GetValue(null);
instance._name = field.Name;
instance._descriptionAttribute = field.GetAttribute<DescriptionAttribute>();
var displayName = field.Name.ToPhrase();
}
_isInitialized = true;
}
}
#endregion
#region Conversion and Equality
public static TDerived Convert(TValue value)
{
return _values[value];
}
public static bool TryConvert(TValue value, out TDerived result)
{
return _values.TryGetValue(value, out result);
}
public static implicit operator TValue(RichEnum<TValue, TDerived> value)
{
return value.Value;
}
public static implicit operator RichEnum<TValue, TDerived>(TValue value)
{
return _values[value];
}
public static implicit operator TDerived(RichEnum<TValue, TDerived> value)
{
return value;
}
public override string ToString()
{
return _name;
}
#endregion
#region IEquatable<TDerived> Members
public override bool Equals(object obj)
{
if (obj != null)
{
if (obj is TValue)
return Value.Equals((TValue)obj);
if (obj is TDerived)
return Value.Equals(((TDerived)obj).Value);
}
return false;
}
bool IEquatable<TDerived>.Equals(TDerived other)
{
return Value.Equals(other.Value);
}
public override int GetHashCode()
{
return Value.GetHashCode();
}
#endregion
#region IComparable Members
int IComparable<TDerived>.CompareTo(TDerived other)
{
return Value.CompareTo(other.Value);
}
int IComparable.CompareTo(object obj)
{
if (obj != null)
{
if (obj is TValue)
return Value.CompareTo((TValue)obj);
if (obj is TDerived)
return Value.CompareTo(((TDerived)obj).Value);
}
return -1;
}
int IComparer<TDerived>.Compare(TDerived x, TDerived y)
{
return (x == null) ? -1 :
(y == null) ? 1 :
x.Value.CompareTo(y.Value);
}
#endregion
public static IEnumerable<TDerived> Values
{
get
{
return _values.Values;
}
}
public static TDerived Parse(string name)
{
foreach (TDerived value in _values.Values)
if (0 == string.Compare(value.Name, name, true) || 0 == string.Compare(value.DisplayName, name, true))
return value;
return null;
}
}
}
```
|
You can't do implict conversions (except for zero), and you can't write your own instance methods - however, you can probably write your own extension methods:
```
public enum MyEnum { A, B, C }
public static class MyEnumExt
{
public static int Value(this MyEnum foo) { return (int)foo; }
static void Main()
{
MyEnum val = MyEnum.A;
int i = val.Value();
}
}
```
This doesn't give you a lot, though (compared to just doing an explicit cast).
One of the main times I've seen people want this is for doing `[Flags]` manipulation via generics - i.e. a `bool IsFlagSet<T>(T value, T flag);` method. Unfortunately, C# 3.0 doesn't support operators on generics, but you can get around this using [things like this](http://www.pobox.com/~skeet/csharp/miscutil/usage/genericoperators.html), which make operators fully available with generics.
|
Can we define implicit conversions of enums in c#?
|
[
"",
"c#",
"enums",
"implicit-conversion",
"implicit",
""
] |
I'm running my C++ program in gdb. I'm not real experienced with gdb, but I'm getting messages like:
```
warning: HEAP[test.exe]:
warning: Heap block at 064EA560 modified at 064EA569 past requested size of 1
```
How can I track down where this is happening at? Viewing the memory doesn't give me any clues.
Thanks!
|
So you're busting your heap. Here's a nice [GDB tutorial](http://www.cs.princeton.edu/courses/archive/spring99/cs126/help/gdbtut.html) to keep in mind.
My normal practice is to set a break in known good part of the code. Once it gets there step through until you error out. Normally you can determine the problem that way.
Because you're getting a heap error I'd assume it has to do with something you're putting on the heap so pay special attention to variables (I think you can use print in GDB to determine it's memory address and that may be able to sync you with where your erroring out). You should also remember that entering functions and returning from functions play with the heap so they may be where your problem lies (especially if you messed your heap before returning from a function).
|
You can probably use a feature called a "watch point". This is like a break point but the debugger stops when the memory is modified.
I gave a rough idea on how to use this in an [answer](https://stackoverflow.com/questions/7525/of-memory-management-heap-corruption-and-c#71983) to a different question.
|
Debugging a memory error with GDB and C++
|
[
"",
"c++",
"memory",
"gdb",
""
] |
What is the difference between `new`/`delete` and `malloc`/`free`?
Related (duplicate?): [In what cases do I use malloc vs new?](https://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new)
|
## `new` / `delete`
* Allocate / release memory
1. Memory allocated from 'Free Store'.
2. Returns a fully typed pointer.
3. `new` (standard version) never returns a `NULL` (will throw on failure).
4. Are called with Type-ID (compiler calculates the size).
5. Has a version explicitly to handle arrays.
6. Reallocating (to get more space) not handled intuitively (because of copy constructor).
7. Whether they call `malloc` / `free` is implementation defined.
8. Can add a new memory allocator to deal with low memory (`std::set_new_handler`).
9. `operator new` / `operator delete` can be overridden legally.
10. **Constructor / destructor used to initialize / destroy the object.**
## `malloc` / `free`
* Allocate / release memory
1. Memory allocated from 'Heap'.
2. Returns a `void*`.
3. Returns `NULL` on failure.
4. Must specify the size required in bytes.
5. Allocating array requires manual calculation of space.
6. Reallocating larger chunk of memory simple (no copy constructor to worry about).
7. They will **NOT** call `new` / `delete`.
8. No way to splice user code into the allocation sequence to help with low memory.
9. `malloc` / `free` can **NOT** be overridden legally.
## Table comparison of the features:
| Feature | `new` / `delete` | `malloc` / `free` |
| --- | --- | --- |
| Memory allocated from | 'Free Store' | 'Heap' |
| Returns | Fully typed pointer | `void*` |
| On failure | Throws (never returns `NULL`) | Returns `NULL` |
| Required size | Calculated by compiler | Must be specified in bytes |
| Handling arrays | Has an explicit version | Requires manual calculations |
| Reallocating | Not handled intuitively | Simple (no copy constructor) |
| Call of reverse | Implementation defined | No |
| Low memory cases | Can add a new memory allocator | Not handled by user code |
| Overridable | Yes | No |
| Use of constructor / destructor | Yes | No |
Technically, memory allocated by `new` comes from the 'Free Store' while memory allocated by `malloc` comes from the 'Heap'. Whether these two areas are the same is an implementation detail, which is another reason that `malloc` and `new` cannot be mixed.
|
The most relevant difference is that the `new` operator allocates memory then calls the constructor, and `delete` calls the destructor then deallocates the memory.
|
What is the difference between new/delete and malloc/free?
|
[
"",
"c++",
"memory-management",
""
] |
I'm writing a password encryption routine. I've written the below app to illustrate my problem. About 20% of the time, this code works as expected. The rest of the time, the decryption throws a cryptographic exception - "The data is invalid".
I believe the problem is in the encryption portion, because the decryption portion works the same every time. That is, if the encryption routine yields a value that the decryption routine can decrypt, it can always decrypt it. But if the encryption routine yields a value that chokes the decryption routine, it always chokes. So the decrypt routine is consistent; the encrypt routine is not.
I suspect my use of Unicode encoding is incorrect, but I've tried others with the same result.
What am I doing wrong?
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace DataProtectionTest
{
public partial class Form1 : Form
{
private static readonly byte[] entropy = { 1, 2, 3, 4, 1, 2, 3, 4 };
private string password;
public Form1()
{
InitializeComponent();
}
private void btnEncryptIt_Click(object sender, EventArgs e)
{
Byte[] pw = Encoding.Unicode.GetBytes(textBox1.Text);
Byte[] encryptedPw = ProtectedData.Protect(pw, entropy, DataProtectionScope.LocalMachine);
password = Encoding.Unicode.GetString(encryptedPw);
}
private void btnDecryptIt_Click(object sender, EventArgs e)
{
Byte[] pwBytes = Encoding.Unicode.GetBytes(password);
try
{
Byte[] decryptedPw = ProtectedData.Unprotect(pwBytes, entropy, DataProtectionScope.LocalMachine);
string pw = Encoding.Unicode.GetString(decryptedPw);
textBox2.Text = pw;
}
catch (CryptographicException ce)
{
textBox2.Text = ce.Message;
}
}
}
}
```
|
On the advice of a colleague, I opted for Convert.ToBase64String. Works well. Corrected program below.
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace DataProtectionTest
{
public partial class Form1 : Form
{
private static readonly byte[] entropy = { 1, 2, 3, 4, 1, 2, 3, 4 };
private string password;
public Form1()
{
InitializeComponent();
}
private void btnEncryptIt_Click(object sender, EventArgs e)
{
Byte[] pw = Encoding.Unicode.GetBytes(textBox1.Text);
Byte[] encryptedPw = ProtectedData.Protect(pw, entropy, DataProtectionScope.LocalMachine);
//password = Encoding.Unicode.GetString(encryptedPw);
password = Convert.ToBase64String(encryptedPw);
}
private void btnDecryptIt_Click(object sender, EventArgs e)
{
//Byte[] pwBytes = Encoding.Unicode.GetBytes(password);
Byte[] pwBytes = Convert.FromBase64String(password);
try
{
Byte[] decryptedPw = ProtectedData.Unprotect(pwBytes, entropy, DataProtectionScope.LocalMachine);
string pw = Encoding.Unicode.GetString(decryptedPw);
textBox2.Text = pw;
}
catch (CryptographicException ce)
{
textBox2.Text = ce.Message;
}
}
}
}
```
|
You should never use any of the `System.Text.Encoding` classes for cipher text. You *will* experience intermittent errors. You should use Base64 encoding and the `System.Convert` class methods.
1. To obtain an encrypted `string` from an encrypted `byte[]`, you should use:
```
Convert.ToBase64String(byte[] bytes)
```
2. To obtain a a raw `byte[]` from a `string` to be encrypted, you should use:
```
Convert.FromBase64String(string data)
```
For additional info, please refer to [MS Security guru Shawn Fanning's post.](http://blogs.msdn.com/b/shawnfa/archive/2005/11/10/491431.aspx)
|
ProtectedData.Protect intermittent failure
|
[
"",
"c#",
".net",
"security",
"encoding",
"cryptography",
""
] |
I've been doing "plain old java objects" programming for 10 years now, with Swing and JDBC, and I consider myself pretty good at it. But I start a new job in two weeks where they use JBoss, and I'd like to get a heads up and start learning all this stuff before I start. What are good resources? On-line tutorials, books, e-books, anything you can suggest, especially ones that don't try to teach you the basics of plain Java first.
|
For quick getting up to speed, you really need to master EJBs and JSP/Servlets. Those are the fundamentals of Java EE technology. The Head First series on EJBs and JSP/Servlets is a good start for what has usually been a mind-numbingly complex framework. Beware that recent Head First editions have switched to teaching the simpler annotation-based Java EE 1.5 frameworks. While the newer version of Java EE is simpler and better, you probably need to know the previous versions (Java EE 1.4 = EJB 2.1 and Servlets 2.4).
At this point, you've only dipped your foot in the water. I would spend a lot of time over the next year, reading up on Java EE technologies and more generally enterprise application development for client-servers.
a) You absolutely must understand data modeling, and databases. The best I've seen are by Chris Date, Steve Feuerstein (if you're using Oracle) and Joe Celko. The better Java EE developers can keep up with their DBAs in technical discussions about the database.
b) You do need to understand how JDBC works, and why ORM tools like iBatis, Hibernate and Toplink came about. Assuming you know how to write a JDBC DAO, then be sure to understand how Hibernate works.
c) You should understand how the layered architecture of a Java EE application. *Core Java EE Design Patterns* has prescribed typical practice, and it's highly likely that your upcoming project will stick to those patterns. That said, you should also understand alternative points of view on architecture. I've found Martin Fowler's *Patterns of Enterprise Application Architecture* and Rod Johnson's *Expert One-On-One Java EE Design and Development* to be valuable. The ideas in the latter became the Spring framework, and has settled into mainstream for how many J2EE developers prefer to develop their apps.
d) Then learn some of the frameworks that have sprouted up around the Java EEE ecosystem. While it's a philosophical question why there are so many frameworks, and which one is better, focusing on the frameworks your employer is specifically using is more than enough.
|
A couple of answers come to mind:
* if "plain old java" is what you're used to, you'll probably need a grounding of plain old j2EE more than JBOSS specific stuff. I'd start with [the sun tutorials](http://java.sun.com/javaee/5/docs/tutorial/doc/), but being familiar with the general structure of servlets, the servlet api, is base.
* as application servers go, JBoss is (my biased opinion only) insanely large and complicated. Think "launching the space shuttle" and you won't be far off. A million services. It is specifically noted for having an unusual class loader structure (although this may have changed since I used it last, about 1 -2 years ago), among other things. It also has an extensive list of nice services, like a JMX base (management configuration beans) although documentation is likely to be spotty, as support is a paid service.
Best suggestion- familiarize yourself with the J2EE libraries. Next would be to get a basic site running in JBOSS. More specific stuff that you might want to do is likely to be very specific to their installation (e.g. there's a JMS implementation available in there but they may not be using it) as I've seen people use it for nothing but a servlet container.
|
Learning Java EE, jboss, etc
|
[
"",
"java",
"jakarta-ee",
"jboss",
""
] |
We have similar code to the following in one of our projects. Can anyone explain (in simple English) why the fixed statement is needed here?
```
class TestClass
{
int iMyVariable;
static void Main()
{
TestClass oTestClass = new TestClass();
unsafe
{
fixed (int* p = &oTestClasst.iMyVariable)
{
*p = 9;
}
}
}
}
```
|
It fixes the pointer in memory. Garbage collected languages have the freedom to move objects around memory for efficiency. This is all transparent to the programmer because they don't really use pointers in "normal" CLR code. However, when you do require pointers, then you need to fix it in memory if you want to work with them.
|
The [fixed statement](http://msdn.microsoft.com/en-us/library/f58wzh21(VS.80).aspx) will "pin" the variable in memory so that the garbage collector doesn't move it around when collecting. If it did move the variable, the pointer would become useless and when you used it you'd be trying to access or modify something that you didn't intend to.
|
Fixed Statement in C#
|
[
"",
"c#",
".net",
"memory-management",
"garbage-collection",
"unsafe",
""
] |
I have to concatenate a bunch of Strings in Javascript and am searching for the fastest way to do so. Let's assume that the Javascript has to create a large XML-"file" that, naturally, consists of many small Strings. So I came up with:
```
var sbuffer = [];
for (var idx=0; idx<10000; idx=idx+1) {
sbuffer.push(‘<xmltag>Data comes here... bla... </xmltag>’);
}
// Now we "send" it to the browser...
alert(sbuffer.join(”));
```
Do not pay any attention to the loop or the other "sophisticated" code which builds the example.
My question is: For an unknown number of Strings, do you have a faster algorithm / method / idea to concatenate many small Strings to a huge one?
|
Changing the line:
`sbuffer.push(‘Data comes here... bla... ’);`
to
`sbuffer[sbuffer.length] = ‘Data comes here... bla... ’;`
will give you 5-50% speed gain (depending on browser, in IE - gain will be highest)
Regards.
|
The question [JavaScript string concatenation](https://stackoverflow.com/questions/112158/javascript-string-concatenation) has an accepted answer that links to a [very good comparison of JavaScript string concatenation performance](http://www.sitepen.com/blog/2008/05/09/string-performance-an-analysis/).
**Edit:**
I would have thought that you could eek out a little more performance by using Duff's device as the article suggests.
|
Javascript String concatenation faster than this example?
|
[
"",
"javascript",
"performance",
"join",
""
] |
What is their use if when you call the method, it might not exist?
Does that mean that you would be able to dynamically create a method on a dynamic object?
What are the practical use of this?
|
You won't really be able to dynamically create the method - but you can get an implementation of `IDynamicMetaObject` (often by extending `DynamicObject`) to respond *as if the method existed*.
Uses:
* Programming against COM objects with a weak API (e.g. office)
* Calling into dynamic languages such as Ruby/Python
* Potentially making "explorable" objects - imagine an XPath-like query but via a method/property calls e.g. `document.RootElement.Person[5].Name["Attribute"]`
* No doubt many more we have yet to think of :)
|
First of all, you can't use it now. It's part of C#4, which will be released sometime in the future.
Basically, it's for an object, whose properties won't be known until runtime. Perhaps it comes from a COM object. Perhaps it's a "define on the fly object" as you describe (although I don't think there's a facility to create those yet or planned).
It's rather like a System.Object, except that you are allowed to call methods that the compiler doesn't know about, and that the runtime figures out how to call.
|
What is the practical use of "dynamic" variable in C# 4.0?
|
[
"",
"c#",
".net",
"c#-4.0",
""
] |
I have a main window (#1) on my webpage from which I open a new browser window (#2) from which I open a new window (#3).
Now if my user closes window#2 before window#3, I have the problem that window#3 no longer can call function in its window.opener since it has gone away.
What I would like to do is to set window#3.opener to window#1 when window#2 closes.
I've tried to do this i window#2 (by the way I use jquery):
```
var children = [];
$(window).unload( function( ) {
$.each( children, function( p, win ) {
if ( win ) {
win.opener = window.opener;
}
} );
} );
```
When window#3 is loaded I add the window to the array children in window#2.
But still when window#2 is closed before window#3, windows#3's window.opener doesn't point to window#1.
How do I make sure that my grand child window (window#3), can still call the main window (window#1) after window#2 is closed?
|
In the third wndow you put in:
```
<script type="text/javascript">
var grandMother = null;
window.onload = function(){
grandMother = window.opener.opener;
}
</script>
```
Thus you have the handle to the grandmother-window, and you can then use it for anything directly:
```
if(grandMother)
grandMother.document.getElementById("myDiv").firstChild.nodeValue ="Greetings from your grandchild !-";
```
|
`window.opener` probably is read-only. I'd setup your own property to refer to the grandparent when grandchild is loaded.
```
function onLoad() {
window.grandparent = window.opener.opener;
}
```
|
Handling of child and grandchild windows in Javascript
|
[
"",
"javascript",
"jquery",
"window",
""
] |
I would like create my own collection that has all the attributes of python list and also knows how to save/load itself into/from a database. Also I want to make the load implicit and lazy, as in it doesn't happen at the point of creation of the list, but waits until its first used.
Is there a single`__xxx__`method I can override to load the list on first usage of any list property (such as`len`,`getitem`,`iter`...etc) without having to override them all?
|
No, there isn't.
|
Not a *single*, but 5 is enough:
```
from collections import MutableSequence
class Monitored(MutableSequence):
def __init__(self):
super(Monitored, self).__init__()
self._list = []
def __len__(self):
r = len(self._list)
print "len: {0:d}".format(r)
return r
def __getitem__(self, index):
r = self._list[index]
print "getitem: {0!s}".format(index)
return r
def __setitem__(self, index, value):
print "setitem {0!s}: {1:s}".format(index, repr(value))
self._list[index] = value
def __delitem__(self, index):
print "delitem: {0!s}".format(index)
del self._list[index]
def insert(self, index, value):
print "insert at {0:d}: {1:s}".format(index, repr(value))
self._list.insert(index, value)
```
The correct way of checking if something implements the whole list interface is to check if it is a subclass of `MutableSequence`. The ABCs found in the `collections` module, of which `MutableSequence` is one, are there for two reasons:
1. to allow you to make your own classes emulating internal container types so that they are usable everywhere a normal built-in is.
2. to use as argument for `isinstance` and `issubclass` to verify that an object implements the necessary functionality:
```
>>> isinstance([], MutableSequence)
True
>>> issubclass(list, MutableSequence)
True
```
Our `Monitored` class works like this:
```
>>> m = Monitored()
>>> m.append(3)
len: 0
insert at 0: 3
>>> m.extend((1, 4))
len: 1
insert at 1: 1
len: 2
insert at 2: 4
>>> m.l
[3, 1, 4]
>>> m.remove(4)
getitem: 0
getitem: 1
getitem: 2
delitem: 2
>>> m.pop(0) # after this, m.l == [1]
getitem: 0
delitem: 0
3
>>> m.insert(0, 4)
insert at 0: 4
>>> m.reverse() # After reversing, m.l == [1, 4]
len: 2
getitem: 1
getitem: 0
setitem 0: 1
setitem 1: 4
>>> m.index(4)
getitem: 0
getitem: 1
1
```
|
Python lazy list
|
[
"",
"python",
""
] |
Java process control is notoriously bad - primarily due to inadequate support by the Java VM/JDK classes (e.g. java.lang.Process).
I am wondering, are there any good open source libraries out there that are reliable.
The requirements would be:
1. OSS
2. Start/Stop processes
3. Manage STDIN and STDOUT
4. cross platform (at least Linux,
Windows, Solaris, HP, and IBM in
that order)
5. (optional) restartable
6. (desirable) mature
|
[Java Service Wrapper](http://wrapper.tanukisoftware.org/doc/english/download.jsp) might be what you're looking for. It's cross-platform, can be used to start things as a Windows service, capture IO, and generally completely manage any java app. It's very light weight and well designed. Atlassian uses it to wrap their products (Jira, Bamboo, etc), so it's battle tested.
|
How about [Apache Commons Exec](http://commons.apache.org/exec/download_exec.cgi)?
|
Good Java Process Control Library
|
[
"",
"java",
"open-source",
"process",
""
] |
```
struct elem
{
int i;
char k;
};
elem user; // compile error!
struct elem user; // this is correct
```
In the above piece of code we are getting an error for the first declaration. But this error doesn't occur with a C++ compiler. In C++ we don't need to use the keyword struct again and again.
So why doesn't anyone update their C compiler, so that we can use structure without the keyword as in C++ ?
Why doesn't the C compiler developer remove some of the glitches of C, like the one above, and update with some advanced features without damaging the original concept of C?
Why it is the same old compiler not updated from 1970's ?
Look at visual studio etc.. It is frequently updated with new releases and for every new release we have to learn some new function usage (even though it is a problem we can cope up with it). We will also get updated with the new compiler if there is any.
Don't take this as a silly question. Why it is not possible? It could be developed without any incompatibility issues (without affecting the code that was developed on the present / old compiler)
Ok, lets develop the new C language, C+, which is in between C and C++ which removes all glitches of C and adds some advanced features from C++ while keeping it useful for specific applications like system level applications, embedded systems etc.
|
Because it takes years for a new Standard to evolve.
They are working on a new C++ Standard ([C++0x](http://en.wikipedia.org/wiki/C%2B%2B0x)), and also on a new C standard (C1x), but if you remember that it usually takes between 5 and 10 years for each iteration, i don't expect to see it before 2010 or so.
Also, just like in any democracy, there are compromises in a Standard. You got the hardliners who say "If you want all that fancy syntactic sugar, go for a toy language like Java or C# that takes you by the hand and even buys you a lollipop", whereas others say "The language needs to be easier and less error-prone to survive in these days or rapidly reducing development cycles".
Both sides are partially right, so standardization is a very long battle that takes years and will lead to many compromises. That applies to everything where multiple big parties are involved, it's not just limited to C/C++.
|
```
typedef struct
{
int i;
char k;
} elem;
elem user;
```
will work nicely. as other said, it's about standard -- when you implement this in VS2008, you can't use it in GCC and when you implement this even in GCC, you certainly not compile in something else. Method above will work everywhere.
On the other side -- when we have C99 standard with bool type, declarations in a for() cycle and in the middle of blocks -- why not this feature as well?
|
Why doesn't anyone upgrade their C compiler with advanced features?
|
[
"",
"c++",
"c",
"visual-studio",
"compiler-construction",
""
] |
Markdown is a great tool for formatting plain text into pretty html, but it doesn't turn plain-text links into URLs automatically. Like this one:
<http://www.google.com/>
How do I get markdown to add tags to URLs when I format a block of text?
|
I couldn't get superjoe30's regular expression to compile, so I adapted his solution to convert plain URLs (within Markdown text) to be Markdown compatible.
The modified filter:
```
urlfinder = re.compile('^(http:\/\/\S+)')
urlfinder2 = re.compile('\s(http:\/\/\S+)')
@register.filter('urlify_markdown')
def urlify_markdown(value):
value = urlfinder.sub(r'<\1>', value)
return urlfinder2.sub(r' <\1>', value)
```
Within the template:
```
<div>
{{ content|urlify_markdown|markdown}}
</div>
```
|
You could write an extension to markdown. Save this code as mdx\_autolink.py
```
import markdown
from markdown.inlinepatterns import Pattern
EXTRA_AUTOLINK_RE = r'(?<!"|>)((https?://|www)[-\w./#?%=&]+)'
class AutoLinkPattern(Pattern):
def handleMatch(self, m):
el = markdown.etree.Element('a')
if m.group(2).startswith('http'):
href = m.group(2)
else:
href = 'http://%s' % m.group(2)
el.set('href', href)
el.text = m.group(2)
return el
class AutoLinkExtension(markdown.Extension):
"""
There's already an inline pattern called autolink which handles
<http://www.google.com> type links. So lets call this extra_autolink
"""
def extendMarkdown(self, md, md_globals):
md.inlinePatterns.add('extra_autolink',
AutoLinkPattern(EXTRA_AUTOLINK_RE, self), '<automail')
def makeExtension(configs=[]):
return AutoLinkExtension(configs=configs)
```
Then use it in your template like this:
```
{% load markdown %}
(( content|markdown:'autolink'))
```
Update:
I've found an issue with this solution: When markdown's standard link syntax is used and the displayed portion matches the regular expression, eg:
```
[www.google.com](http://www.yahoo.co.uk)
```
strangely becomes:
[www.google.com](http://www.google.com)
But who'd want to do that anyway?!
|
How do I get python-markdown to additionally "urlify" links when formatting plain text?
|
[
"",
"python",
"django",
"markdown",
""
] |
I was looking at the Java code for `LinkedList` and noticed that it made use of a static nested class, `Entry`.
```
public class LinkedList<E> ... {
...
private static class Entry<E> { ... }
}
```
What is the reason for using a static nested class, rather than an normal inner class?
The only reason I could think of, was that Entry doesn't have access to instance variables, so from an OOP point of view it has better encapsulation.
But I thought there might be other reasons, maybe performance. What might it be?
Note. I hope I have got my terms correct, I would have called it a static inner class, but I think this is wrong: <http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html>
|
The Sun page you link to has some key differences between the two:
> A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.
> ...
>
> Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. **In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.**
There is no need for `LinkedList.Entry` to be top-level class as it is *only* used by `LinkedList` (there are some other interfaces that also have static nested classes named `Entry`, such as `Map.Entry` - same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach.
As [Jon Skeet points out](https://stackoverflow.com/a/253507/4249), I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.
|
To my mind, the question ought to be the other way round whenever you see an inner class - does it *really* need to be an inner class, with the extra complexity and the implicit (rather than explicit and clearer, IMO) reference to an instance of the containing class?
Mind you, I'm biased as a C# fan - C# doesn't have the equivalent of inner classes, although it does have nested types. I can't say I've missed inner classes yet :)
|
Static nested class in Java, why?
|
[
"",
"java",
"class",
"static",
"member",
""
] |
i want to be a good developer citizen, [pay my taxes](http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx), and disable things if we're running over Remote Desktop, or running on battery.
If we're running over remote desktop (or equivalently in a Terminal server session), we must disable animations and double-buffering. You can check this with:
```
/// <summary>
/// Indicates if we're running in a remote desktop session.
/// If we are, then you MUST disable animations and double buffering i.e. Pay your taxes!
///
/// </summary>
/// <returns></returns>
public static Boolean IsRemoteSession
{
//This is just a friendly wrapper around the built-in way
get
{
return System.Windows.Forms.SystemInformation.TerminalServerSession;
}
}
```
Now i need to find out if the user is running on battery power. If they are, i don't want to blow through their battery. i want to do things such as
* disable animations
* disable background spell-checking
* disable background printing
* turn off gradients
* use `graphics.SmoothingMode = SmoothingMode.HighSpeed;`
* use `graphics.InterpolationMode = InterpolationMode.Low;`
* use `graphics.CompositingQuality = CompositingQuality.HighSpeed;`
* minimize hard drive access - to avoid spin up
* minimize network access - to save WiFi power
Is there a managed way to see if the machine is **currently** running on battery?
## Bonus Reading
* [How do you convince developers to pay their "taxes"?](http://blogs.msdn.com/oldnewthing/archive/2005/08/22/454487.aspx) *([archive.is](https://archive.fo/iNVg5))*
* [Taxes: Remote Desktop Connection and painting](http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx) *([archive.is](https://archive.fo/lJx1u))*
* [GetSystemMetrics(SM\_REMOTESESSION)](http://msdn.microsoft.com/en-us/library/ms724385(VS.85).aspx) *([archive.is](https://archive.fo/Ywbw7))*
|
I believe you can check [SystemInformation.PowerStatus](http://msdn.microsoft.com/en-us/library/system.windows.forms.systeminformation.powerstatus(VS.80).aspx) to see if it's on battery or not.
```
Boolean isRunningOnBattery =
(System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus ==
PowerLineStatus.Offline);
```
Edit: In addition to the above, there's also a System.Windows.Forms.[PowerStatus](http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus(VS.80).aspx) class. One of its methods is [PowerLineStatus](http://msdn.microsoft.com/en-us/library/system.windows.forms.powerstatus.powerlinestatus(VS.80).aspx), which will equal PowerLineStatus.Online if it's on AC Power.
|
R. Bemrose found the managed call. Here's some sample code:
```
/// <summary>
/// Indicates if we're running on battery power.
/// If we are, then disable CPU wasting things like animations, background operations, network, I/O, etc
/// </summary>
public static Boolean IsRunningOnBattery
{
get
{
PowerLineStatus pls = System.Windows.Forms.SystemInformation.PowerStatus.PowerLineStatus;
//Offline means running on battery
return (pls == PowerLineStatus.Offline);
}
}
```
|
C# .NET: How to check if we're running on battery?
|
[
"",
"c#",
"performance",
"optimization",
""
] |
I want to display an image within a scroll area. The view port of the scroll area shall have a defined initial size. That means, if the image's size is bigger than the initial size of the view port, scroll bars will be visible, otherwise not.
```
// create label for displaying an image
QImage image( ":/test.png" );
QLabel *label = new QLabel( this );
label->setPixmap( image.toPixmap() );
// put label into scroll area
QScollArea *area = new QScrollArea( this );
area->setWidget( label );
// set the initial size of the view port
// NOTE: This is what I'd like to do, but this method does not exist
area->setViewPortSize( QSize( 300, 300 ) );
```
It shall be possible to resize the whole application so that the view port will get another size than the initial one.
Unfortunately, I was not able to find out, how to set the size of the view port. Qt's layout mechanism seems to set a default size for the view port, but up to now I was not able to change it.
Setting a new size with `area->setMinimumSize( QSize( 300, 300 ) );` will actually set the demanded size, but then the scroll area looses the ability to get resized to a size smaller than 300x300.
|
I think that you are looking at the problem the wrong way. The QScrollArea is just a widget that you put in a frame or QMainWindow. The size of the widget is controlled by the layout of the widget that contains it.
Take a look at this example from Trolltech: [Image Viewer Example](http://doc.qt.io/qt-5/qtwidgets-widgets-imageviewer-example.html)
|
You can try:
```
class MyScrollArea : public QScrollArea
{
virtual QSize sizeHint() const { return QSize( 300, 300 ); }
};
// create label for displaying an image
QImage image( ":/test.png" );
Label *label = new QLabel;
label->setPixmap( image.toPixmap() );
// put label into scroll area
QScollArea *area = new MyScrollArea( this );
area->setWidget( label );
```
However layout and Qt is amazingly Voodoo. It is IMO its least functional part.
if that doesn't work, try calling QWidget::resize() on various widgets.
|
How to set an initial size of a QScrollArea?
|
[
"",
"c++",
"qt",
"qscrollarea",
""
] |
I have the following code which works just fine when the method is "POST", but changing to "GET" doesn't work:
```
HttpWebRequest request = null;
request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
request.Method = "POST"; // Doesn't work with "GET"
request.BeginGetRequestStream(this.RequestCallback, null);
```
I get a `ProtocolViolationException` exception with the "GET" method.
**Edit:** After having a look using Reflector, it seems there is an explicit check for the "GET" method, if it's set to that it throws the exception.
**Edit2:** I've updated my code to the following, but it still throws an exception when I call EndGetResponse()
```
if (request.Method == "GET")
{
request.BeginGetResponse(this.ResponseCallback, state);
}
else
{
request.BeginGetRequestStream(this.RequestCallback, state);
}
```
In my function, ResponseCallback, I have this:
```
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
```
Which throws the exception as well.
**Answer**
The above code now works, I had forgotten to take out the Content-Type line which was causing the exception to be thrown at the end. +1 to tweakt & answer to Jon.
The working code is now below:
```
HttpWebRequest request = null;
request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.Method = "GET";// Supports POST too
if (request.Method == "GET")
{
request.BeginGetResponse(this.ResponseCallback, state);
}
else
{
request.BeginGetRequestStream(this.RequestCallback, state);
}
```
|
This is [specified in the documentation](http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx). Basically GET requests aren't meant to contain bodies, so there's no sensible reason to call `BeginGetRequestStream`.
|
Does it make sense for a GET request to send a Content-Type? Did you try removing the third line?
|
How do I use HttpWebRequest with GET method
|
[
"",
"c#",
".net",
"silverlight",
"web-services",
"http",
""
] |
```
template <class T>
bool BST<T>::search(const T& x, int& len) const
{
return search(BT<T>::root, x);
}
template <class T>
bool BST<T>::search(struct Node<T>*& root, const T& x)
{
if (root == NULL)
return false;
else
{
if (root->data == x)
return true;
else if(root->data < x)
search(root->left, x);
else
search(root->right, x);
}
}
```
So this is my search function for my BST class with a T node. x is the data being searched for within the tree, len is just the amount of nodes it has to travel to come up with the matching node if it exists. I have not implented that yet, I'm just incrementally developing my assignment. I'm calling it by doing this:
```
if(t.search(v[1], len) == true)
cout << endl << "true";
```
v is just a vector I had to create to compare it to, and so this is just supplying it with an int. The error I'm getting:
```
BST.h: In member function âbool BST<T>::search(const T&, int&) const [with T = int]â:
prog5.cc:24: instantiated from here
BST.h:78: error: no matching function for call to âBST<int>::search(Node<int>* const&, const int&) constâ
BST.h:76: note: candidates are: bool BST<T>::search(const T&, int&) const [with T = int]
BST.h:83: note: bool BST<T>::search(Node<T>*&, const T&) [with T = int]
```
So I'm not sure what I'm doing wrong or where I'm doing wrong.
|
Okay, `bool BST<T>::search(struct Node<T>*& root, const T& x)` should probably have const after it like so: `bool BST<T>::search(struct Node<T>*& root, const T& x) const`. Basically, you've called a non-const function from a const function and this is a no-no.
BTW, this looks suspect to me "`struct Node<T>*&`"... I'd probably drop the & and work with `Node<T>*`... but maybe you need that because of the *struct*?
Also, this is C++, there is no reason to leave Node as a struct... needing to have **struct** in the parameter definition just looks bad, IMHO. Why not make Node a class?
|
There are multiple problems in your search code:
* The sort order is backwards, if the node data is less than what you search, you should search in the right branch, not the left branch.
* You should return the result of the recursive call
* It is also unclear why you pass `root` by reference. it should instead be passed as a `const` qualified pointer and the method body should be `const` qualified too.
Here is a alternative:
```
template <class T>
bool BST<T>::search(const struct Node<T> *root, const T& x) const {
if (root == NULL)
return false;
else
if (root->data == x)
return true;
else
if (root->data < x)
return search(root->right, x);
else
return search(root->left, x);
}
```
And here is a simpler non recursive implementation:
```
template <class T>
bool BST<T>::search(const struct Node<T> *root, const T& x) const {
while (root != NULL) {
if (root->data == x)
return true;
if (root->data < x)
root = root->right;
else
root = root->left;
}
return false;
}
```
|
C++ Binary Search Tree Recursive search function
|
[
"",
"c++",
"binary-search-tree",
""
] |
I've recently started using code coverage tools (particularily Emma and EclEmma), and I really like the view that it gives me as to the completeness of my unit tests - and the ability to see what areas of the code my unit tests aren't hitting at all. I currently work in an organization that doesn't do a lot of unit testing, and I plan on really pushing everyone to take on unit testing and code coverage and TDD and hopefully convert the organization.
One issue that I'm unsure of with this subject is exactly how far I should take my code coverage. For example, if I have a class such as this:
```
//this class is meant as a pseudo-enum - I'm stuck on Java 1.4 for time being
public final class BillingUnit {
public final static BillingUnit MONTH = new BillingUnit("month");
public final static BillingUnit YEAR = new BillingUnit("year");
private String value;
private BillingUnit(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
public boolean equals(Object obj) {
return value.equals(((BillingUnit) obj).getValue());
}
public int hashCode() {
return value.hashCode();
}
}
```
I wrote some simple unit tests to make sure that `equals()` works correctly, that `getValue()` returns what I expected, etc. But thanks to the visual nature of EclEmma, the `hashcode()` method shows up as bright red for "not tested".
Is it worthwhile to even bother to test `hashCode()`, in this example, considering how simple the implementation is? I feel like I would be adding a unit test for this method simply to bump the code coverage % up, and get rid of the glaring red highlight that EclEmma adds to these lines.
Maybe I'm being neurotic and OCD-like, but I find that using something like EclEmma that makes it so easy to see what is untested - the plugin highlights the source code in red, and covered code in green - really makes me want to push to get as many classes 100% green as a I can - even when it doesn't add much of a benefit.
|
I use code coverage to give me hints on places where I may have an incomplete set of tests. For example, I may write a test for some given functionality, then go develop the code that satisfies that functionality, but in doing so actually write code that does more than it is supposed to -- say it might catch an exception in an alternate case that the test doesn't exercise. When I use the coverage analyzer, I can see that I've introduced code that doesn't have an associated test. It helps me to know when I haven't written enough tests.
On the other hand, coverage analysis can lead to false security. Having all of your code covered does not mean that you have enough tests. You need to think about tests from the perspective of what should the code do and write tests to make sure that it does it. Preferably by writing the test first. Just because your code is completely covered does not mean that the code does what it is supposed to do.
In your example, I would have written the test for hashCode to define what the functionality of the method does, before I wrote the code. Therefore, I would have it covered. That doesn't mean that I always have 100% coverage. I'm not overly zealous about writing tests for simple accessors, for example. I also may not test methods from the parent class where I inherit from a framework, since I don't feel the need to test other people's code.
|
I think it is worthwhile to use a library where you can choose to ignore certain kinds of statements. For example, if you have a lot of:
```
if(logger.isDebugEnabled()) {
logger.debug("something");
}
```
It is useful if you can turn off coverage calculations for those sorts of lines. It can also be (arguably) valid to turn off coverage calculations for trivial getters and setters (those that simply set or return a member variable with no other checks or side-effects). I do however think that if you have overridden equals and hashcode, those should be tested. You added non-trivial functionality, and it should be tested.
Just to be clear, the reason I think the above situations should be excluded from coverage is that:
* Not testing that functionality is ok. You shouldn't have to run through your entire suite of tests 5 times, with the logging library set to each logging level, just to make sure that all your statements are hit.
* If you did the above, it would skew your coverage the other way. If 90% of your branches are `if(log.isDebugEnabled())`, and you test them all but no other branches, it will look like you have 90% branch coverage (good), when in reality, you have 0% non-trivial branch coverage (bad!!).
|
How far do you take code coverage?
|
[
"",
"java",
"tdd",
"code-coverage",
"emma",
""
] |
Ok, I am reading in dat files into a byte array. For some reason, the people who generate these files put about a half meg's worth of useless null bytes at the end of the file. Anybody know a quick way to trim these off the end?
First thought was to start at the end of the array and iterate backwards until I found something other than a null, then copy everything up to that point, but I wonder if there isn't a better way.
To answer some questions:
Are you sure the 0 bytes are definitely in the file, rather than there being a bug in the file reading code? Yes, I am certain of that.
Can you definitely trim all trailing 0s? Yes.
Can there be any 0s in the rest of the file? Yes, there can be 0's other places, so, no, I can't start at the beginning and stop at the first 0.
|
Given the extra questions now answered, it sounds like you're fundamentally doing the right thing. In particular, you have to touch every byte of the file from the last 0 onwards, to check that it only has 0s.
Now, whether you have to copy everything or not depends on what you're then doing with the data.
* You could perhaps remember the index and keep it with the data or filename.
* You could copy the data into a new byte array
* If you want to "fix" the file, you could call [FileStream.SetLength](http://msdn.microsoft.com/en-us/library/system.io.filestream.setlength.aspx) to truncate the file
The "you *have* to read every byte between the truncation point and the end of the file" is the critical part though.
|
I agree with Jon. The critical bit is that you must "touch" every byte from the last one until the first non-zero byte. Something like this:
```
byte[] foo;
// populate foo
int i = foo.Length - 1;
while(foo[i] == 0)
--i;
// now foo[i] is the last non-zero byte
byte[] bar = new byte[i+1];
Array.Copy(foo, bar, i+1);
```
I'm pretty sure that's about as efficient as you're going to be able to make it.
|
Removing trailing nulls from byte array in C#
|
[
"",
"c#",
"arrays",
""
] |
I'm hitting this error and I'm not really sure why. I have a minified version of excanvas.js and something is breaking in IE, specifically on:
`var b=a.createStyleSheet();`
I'm not sure why. Does anyone have any insight? I can provide more information, I'm just not sure what information will help.
|
This is a slightly old thread, but I thought it would be useful to post. There seems to be a limitation on how much style information a page can contain, which causes this error in IE6. I am able to produce an invalid argument error using this simple test page:
```
<html>
<head>
<title></title>
<script>
for(var i=0;i<32;i++) {
document.createStyleSheet();
}
</script>
</head>
<body>
</body>
</html>
```
I think this is the source of the problem.
HTH,
Russell
|
The newest version of excanvas.js did not fix this issue for me in IE8 so I updated line 111 of excanvas.js to the code below and I no longer get the exception. The code for this solution is from <http://dean.edwards.name/weblog/2010/02/bug85/>.
```
var ss = null;
var cssText = 'canvas{display:inline-block;overflow:hidden;' +
// default size is 300x150 in Gecko and Opera
'text-align:left;width:300px;height:150px}';
try{
ss = doc.createStyleSheet();
ss.owningElement.id = 'ex_canvas_';
ss.cssText = cssText;
} catch(e) {
ss = document.styleSheets[document.styleSheets.length - 1];
ss.cssText += "\r\n" + cssText;
}
```
|
What does the error "htmlfile: invalid argument" mean? I'm getting this in excanvas.js
|
[
"",
"javascript",
""
] |
I have a requirement to get the contents of every method in a cs file into a string. What I am looking for is when you have an input of a cs file, a dictionary is returned with the method name as the key and the method body as the value.
I have tried Regex and reflection with no success, can anyone help?
Thanks
|
I don't know if it's any use to you but Visual Studio Addins include a EnvDTE object, that gives you full access to the VB and C# language parsers.
See [Discovering Code with the code Model](http://msdn.microsoft.com/en-us/library/ms228763(VS.80).aspx)
I touched on it tangentially years ago, I don't know how difficult it is to use, or how effective it is, but it does look like it will give you what you need.
> **The code model allows
> automation clients to avoid
> implementing a parser for Visual
> Studio languages** in order to discover
> the high-level definitions in a
> project, such as classes, interfaces,
> structures, methods, properties, and
> so on.
If you read the article in full it tells how to pull the full text from a file for a function
Hope this helps :)
|
**Assuming that the file is valid** (i.e. compiles), you can start by reading the whole file into a string.
I gather from your question that you are only interested in method names, not in class names. Then you need a regex that gives you all instances of *public|protected|private*, optional keywords virtual/override etc, *MethodName*, *(*, optional parameters, *)*.
It would help if there were coding conventions, so you could **assume** that all method definitions were always in one line, not spread over several lines.
Once you have that, it is only a matter of counting { and } to get the function body.
And one final advice: **Beware of assumptions**. They have the nasty habbit of biting you in the butt.
**EDIT:** Ouch, forgot about comments! if you have brackets in comments in the method body, your counting can go wrong. So you need to strip all comments from the source as your very first step.
|
Get a method's contents from a cs file
|
[
"",
"c#",
"regex",
"methods",
""
] |
How would I achieve the pseudo-code below in JavaScript? I want to include the date check in the second code excerpt, where txtDate is for the BilledDate.
```
If ABS(billeddate – getdate) > 31 then yesno “The date you have entered is more than a month from today, Are you sure the date is correct,”.
if (txtDate && txtDate.value == "")
{
txtDate.focus();
alert("Please enter a date in the 'Date' field.")
return false;
}
```
|
Generally speaking you work with Date-objects in javascript, and these should be constructed with the following syntax:
```
var myDate = new Date(yearno, monthno-1, dayno);
//you could put hour, minute, second and milliseconds in this too
```
Beware, the month-part is an index, so january is 0, february is 1 and december is 11 !-)
Then you can pull out anything you want, the .getTime() thing returns number of milliseconds since start of Unix-age, 1/1 1970 00:00, så this value you could subtract and then look if that value is greater than what you want:
```
//today (right now !-) can be constructed by an empty constructor
var today = new Date();
var olddate = new Date(2008,9,2);
var diff = today.getTime() - olddate.getTime();
var diffInDays = diff/(1000*60*60*24);//24 hours of 60 minutes of 60 second of 1000 milliseconds
alert(diffInDays);
```
This will return a decimal number, so probably you'll want to look at the integer-value:
```
alert(Math.floor(diffInDays));
```
|
To get the date difference in days in plain JavaScript, you can do it like this:
```
var billeddate = Date.parse("2008/10/27");
var getdate = Date.parse("2008/09/25");
var differenceInDays = (billeddate - getdate)/(1000*60*60*24)
```
However if you want to get more control in your date manipulation I suggest you to use a date library, I like [DateJS](http://www.datejs.com/), it's really good to parse and manipulate dates in many formats, and it's really syntactic sugar:
```
// What date is next thrusday?
Date.today().next().thursday();
//or
Date.parse('next thursday');
// Add 3 days to Today
Date.today().add(3).days();
// Is today Friday?
Date.today().is().friday();
// Number fun
(3).days().ago();
```
|
Date Parsing and Validation in JavaScript
|
[
"",
"javascript",
""
] |
I'd like something like a generic, re-usable `getPosition()` method that will tell me the number of bytes read from the starting point of the stream. Ideally, I would prefer this to work with all InputStreams, so that I don't have to wrap each and every one of them as I get them from disparate sources.
Does such a beast exist? If not, can anyone recommend an existing implementation of a counting `InputStream`?
|
Take a look at [CountingInputStream](http://commons.apache.org/io/apidocs/org/apache/commons/io/input/CountingInputStream.html) in the Commons IO package. They have a pretty good collection of other useful InputStream variants as well.
|
You'll need to follow the Decorator pattern established in `java.io` to implement this.
Let's give it a try here:
```
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public final class PositionInputStream
extends FilterInputStream
{
private long pos = 0;
private long mark = 0;
public PositionInputStream(InputStream in)
{
super(in);
}
/**
* <p>Get the stream position.</p>
*
* <p>Eventually, the position will roll over to a negative number.
* Reading 1 Tb per second, this would occur after approximately three
* months. Applications should account for this possibility in their
* design.</p>
*
* @return the current stream position.
*/
public synchronized long getPosition()
{
return pos;
}
@Override
public synchronized int read()
throws IOException
{
int b = super.read();
if (b >= 0)
pos += 1;
return b;
}
@Override
public synchronized int read(byte[] b, int off, int len)
throws IOException
{
int n = super.read(b, off, len);
if (n > 0)
pos += n;
return n;
}
@Override
public synchronized long skip(long skip)
throws IOException
{
long n = super.skip(skip);
if (n > 0)
pos += n;
return n;
}
@Override
public synchronized void mark(int readlimit)
{
super.mark(readlimit);
mark = pos;
}
@Override
public synchronized void reset()
throws IOException
{
/* A call to reset can still succeed if mark is not supported, but the
* resulting stream position is undefined, so it's not allowed here. */
if (!markSupported())
throw new IOException("Mark not supported.");
super.reset();
pos = mark;
}
}
```
The InputStreams are intended to be thread safe, so that accounts for the liberal use of synchronization. I played around with `volatile` and `AtomicLong` position variables, but synchronization is probably best because it allows one thread to operate on the stream and query its position without relinquishing the lock.
```
PositionInputStream is = …
synchronized (is) {
is.read(buf);
pos = is.getPosition();
}
```
|
Given a Java InputStream, how can I determine the current offset in the stream?
|
[
"",
"java",
"io",
"inputstream",
""
] |
I have just installed Eclipse 3.4 and found out that there is not a plugin to create Swing applications yet. I also have found that there is a Matisse implementation in MyEclipse IDE, but I'd like to now whether there is such a Matisse plugin for free.
|
Instatiations Swing Designer is the best in my opinion. We settled on it after trying may different Eclipse plugins.
|
there isnt one for free. myeclipse is the only way to run matisse inside eclipse.
|
Matisse in Eclipse
|
[
"",
"java",
"eclipse",
"swing",
"eclipse-3.4",
"matisse",
""
] |
I'd like to receive error logs via email. For example, if a `Warning-level` error message should occur, I'd like to get an email about it.
How can I get that working in CodeIgniter?
|
You could extend the Exception core class to do it.
Might have to adjust the reference to CI's email class, not sure if you can instantiate it from a library like this. I don't use CI's email class myself, I've been using the Swift Mailer library. But this should get you on the right path.
Make a file MY\_Exceptions.php and place it in /application/libraries/ (Or in /application/core/ for CI 2)
```
class MY_Exceptions extends CI_Exceptions {
function __construct()
{
parent::__construct();
}
function log_exception($severity, $message, $filepath, $line)
{
if (ENVIRONMENT === 'production') {
$ci =& get_instance();
$ci->load->library('email');
$ci->email->from('your@example.com', 'Your Name');
$ci->email->to('someone@example.com');
$ci->email->cc('another@another-example.com');
$ci->email->bcc('them@their-example.com');
$ci->email->subject('error');
$ci->email->message('Severity: '.$severity.' --> '.$message. ' '.$filepath.' '.$line);
$ci->email->send();
}
parent::log_exception($severity, $message, $filepath, $line);
}
}
```
|
One thing that is left out of the solution is that you have to grab CodeIgniters super object to load and use the email library (or any of CodeIgniters other libraries and native functions).
```
$CI =& get_instance();
```
After you have done that you use `$CI` instead of `$this` to load the email library and set all of the parameters. For more information [click here](http://codeigniter.com/user_guide/general/creating_libraries.html) and look under the **Utilizing CodeIgniter Resources within Your Library** section.
|
In CodeIgniter, How Can I Have PHP Error Messages Emailed to Me?
|
[
"",
"php",
"email",
"codeigniter",
"error-logging",
""
] |
When running PHP in CLI mode, *most* of the time (not always), the script will hang at the end of execution for about 5 seconds and then output this:
> `Error in my_thread_global_end(): 1 threads didn't exit`
It doesn't seem to actually have any effect on the script itself.
Some web searches turned up blogs which suggest replacing the php\_mysql.dll with a different version, however this has not solved the issue for me, and I suspect the info from those blogs is now out of date.
My setup:
* PHP Version 5.2.4
* Apache/2.2.4 (Win32)
* Windows Vista Home Premium SP1
|
This is a known bug with some of the PHP 5.2.X version in the windows fast-cgi implementation
<http://bugs.php.net/bug.php?id=41350&edit=1>
I have encountered this bug before and downgrading my PHP install to 5.2.0 solved the problem.
|
There is no need to downgrade the entire PHP version, just replace the **libmysql.dll** from the **PHP 5.2.1 release** & things should be rolling :) Refer [**this link**](http://www.eukhost.com/forums/f15/fix-error-my_thread_global_end-1-thread-didnt-exit-5612/) for more info.
|
PHP: Error in my_thread_global_end(): 1 threads didn't exit
|
[
"",
"php",
"mysql",
""
] |
I have a one-dimensional array of strings in JavaScript that I'd like to turn into a comma-separated list. Is there a simple way in garden-variety JavaScript (or jQuery) to turn that into a comma-separated list? (I know how to iterate through the array and build the string myself by concatenation if that's the only way.)
|
The [Array.prototype.join()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join) method:
```
var arr = ["Zero", "One", "Two"];
document.write(arr.join(", "));
```
|
Actually, the `toString()` implementation does a join with commas by default:
```
var arr = [ 42, 55 ];
var str1 = arr.toString(); // Gives you "42,55"
var str2 = String(arr); // Ditto
```
I don't know if this is mandated by the JS spec but this is what ~~most~~ pretty much all browsers seem to be doing.
|
Easy way to turn JavaScript array into comma-separated list?
|
[
"",
"javascript",
""
] |
Is there a PHP class/library that would allow me to query an XHTML document with CSS selectors? I need to scrape some pages for data that is very easily accessible if I could somehow use CSS selectors (jQuery has spoiled me!). Any ideas?
|
After Googling further (initial results weren't very helpful), it seems there is actually a Zend Framework library for this, along with some others:
* [DOM-Query](https://github.com/PHPPowertools/DOM-Query)
* [phpQuery](http://code.google.com/p/phpquery/)
* [pQuery](https://github.com/tburry/pquery)
* [QueryPath](http://querypath.org/)
* [Simple HTML DOM Parser](http://simplehtmldom.sourceforge.net/)
* [Ultimate Web Scraper Toolkit](https://github.com/cubiclesoft/ultimate-web-scraper/)
* [Zend-Dom](https://github.com/zendframework/zend-dom)
|
XPath is a fairly standard way to access XML (and XHTML) nodes, and provides much more precision than CSS.
|
PHP CSS Selector Library?
|
[
"",
"php",
"screen-scraping",
"css-selectors",
""
] |
i am planning to use 2 dedicated root servers rented at a hosting provider. those machines will run tomcat 6 in a cluster.
if i will add additional machines later on - it is unlikely that they will be accessible with multicast, because they will be located in different subnets.
is it possible to run tomcat without multicast? all tutorials for tomcat 6 clustering include multicast heartbeat. are there any alternatives to SimpleTcpCluster?
or are other alternatives more appropriate in this situation?
|
With no control over the distance between both servers (they might be in two different datacenters) and no dedicated inter-server-communication line, I'd rather run them via round-robin DNS or a loadbalancer that redirects clients to either www1.yourdomain.xxx or www2.yourdomain.xxx and handle server-communication carefully.
If the servers are heavily communicating with each other you might either look to change your architecture, optimize the hell out of your application to "fit" on one server (at least for a while) or go for dedicated hosting with control over the location, distance and cabling of your servers. Otherwise your inter-server-communication, heartbeat etc. would use the same channel as the clients that are communicating with it (e.g. the same network segment) which might slow everyone down.
If you are really expecting that much load I suppose there's at least some money involved, no? Use it wisely and use your setup skills for problems harder than setting up distributed clustering with no control or dedicated lines.
|
Seeing the comment to the question after having given my other answer I'm puzzled about what your question is... Is it about session replication? Cluster communication? It might be better to state your problem instead of your planned solution that has problems itself.
I'll state some possible problems together with quick answers:
## Your application is CPU/RAM intensive
* Profile it, optimize it, try again
* Buy a bigger/better server
## Your application is bandwidth intensive
* using the cheapo clustering you mentioned in your question will most likely make it worse, as the same (cloaked) channel is used for inter-server-communication as for client-server communication
* You might be able to separate different kinds of bandwidth e.g. by having dynamic content served from a different server than static content: No need for inter-server-communication here
## Your application is storage intensive
* get a bigger server
* go for dedicated hosting and fit in as many spinning disks as you need
* see if other models (like amazons S3 storage) might work for you)
## Your application is likely to be slashdotted
* determine which of the above factors (or others) are determining the limits of your application, fix that.
## You just need session replication?
* Tomcats SessionManager interface is small and can easily be implemented/extended yourself. Use it for any session replication you like. See the [StandardManager](http://tomcat.apache.org/tomcat-6.0-doc/api/org/apache/catalina/session/StandardManager.html) documentation and implementation for more information
## More ideas
* look at more flexible setups like EC2 (amazon), googles offerings or other cloud computing setups. Make use of their own cloud-storage and inter-server-communication-facilities. Be careful to not depend too much on this infrastructure.
I certainly have forgotten something, but this might provide some starting point. Be more concrete about the nature of your underlying problem to get better answers :)
|
tomcat session replication without multicast
|
[
"",
"java",
"tomcat",
"multicast",
"failovercluster",
""
] |
In this thread, we look at examples of good uses of `goto` in C or C++. It's inspired by [an answer](https://stackoverflow.com/questions/244445/best-refactoring-for-the-dreaded-while-true-loop#244644) which people voted up because they thought I was joking.
Summary (label changed from original to make intent even clearer):
```
infinite_loop:
// code goes here
goto infinite_loop;
```
Why it's better than the alternatives:
* It's specific. `goto` is the
language construct which causes an
unconditional branch. Alternatives
depend on using structures
supporting conditional branches,
with a degenerate always-true
condition.
* The label documents the intent
without extra comments.
* The reader doesn't have to scan the
intervening code for early `break`s
(although it's still possible for an
unprincipled hacker to simulate
`continue` with an early `goto`).
**Rules:**
* Pretend that the gotophobes didn't
win. It's understood that the above
can't be used in real code because
it goes against established idiom.
* Assume that we have all heard of
'Goto considered harmful' and know
that goto can be used to write
spaghetti code.
* If you disagree with an example,
criticize it on technical merit
alone ('Because people don't like
goto' is not a technical reason).
Let's see if we can talk about this like grown ups.
**Edit**
This question seems finished now. It generated some high quality answers. Thanks to everyone,
especially those who took my little loop example seriously. Most skeptics were concerned
by the lack of block scope. As @quinmars pointed out in a comment, you can always put braces around the
loop body. I note in passing that `for(;;)` and `while(true)` don't give you the braces
for free either (and omitting them can cause vexing bugs). Anyway, I won't waste any more
of your brain power on this trifle - I can live with the harmless and idiomatic `for(;;)` and `while(true)` (just as well if I want to keep my job).
Considering the other responses, I see that many people view `goto` as something you always
have to rewrite in another way. Of course you can avoid a `goto` by introducing a loop,
an extra flag, a stack of nested `if`s, or whatever, but why not consider whether `goto` is
perhaps the best tool for the job? Put another way, how much ugliness are people prepared to endure to avoid using a built-in language feature for its intended purpose? My take is that
even adding a flag is too high a price to pay. I like my variables to represent things in
the problem or solution domains. 'Solely to avoid a `goto`' doesn't cut it.
I'll accept the first answer which gave the C pattern for branching to a cleanup block. IMO, this makes the strongest case for a `goto` of all the posted answers, certainly
if you measure it by the contortions a hater has to go through to avoid it.
|
Heres one trick I've heard of people using. I've never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically.
```
void foo()
{
if (!doA())
goto exit;
if (!doB())
goto cleanupA;
if (!doC())
goto cleanupB;
/* everything has succeeded */
return;
cleanupB:
undoB();
cleanupA:
undoA();
exit:
return;
}
```
|
The classic need for GOTO in C is as follows
```
for ...
for ...
if(breakout_condition)
goto final;
final:
```
There is no straightforward way to break out of nested loops without a goto.
|
Examples of good gotos in C or C++
|
[
"",
"c++",
"c",
"goto",
""
] |
Can an abstract class have a constructor?
If so, how can it be used and for what purposes?
|
Yes, an abstract class can have a constructor. Consider this:
```
abstract class Product {
int multiplyBy;
public Product( int multiplyBy ) {
this.multiplyBy = multiplyBy;
}
public int mutiply(int val) {
return multiplyBy * val;
}
}
class TimesTwo extends Product {
public TimesTwo() {
super(2);
}
}
class TimesWhat extends Product {
public TimesWhat(int what) {
super(what);
}
}
```
The superclass `Product` is abstract and has a constructor. The concrete class `TimesTwo` has a constructor that just hardcodes the value 2. The concrete class `TimesWhat` has a constructor that allows the caller to specify the value.
Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.
> NOTE: As there is no default (or no-arg) constructor in the parent
> abstract class, the constructor used in subclass must explicitly call
> the parent constructor.
|
You would define a constructor in an abstract class if you are in one of these situations:
* you want to perform some
initialization (to fields of the
abstract class) before the
instantiation of a subclass actually
takes place
* you have defined final fields in the
abstract class but you did not
initialize them in the declaration
itself; in this case, you MUST have
a constructor to initialize these
fields
Note that:
* you may define more than one
constructor (with different
arguments)
* you can (should?) define all your
constructors protected (making them
public is pointless anyway)
* your subclass constructor(s) can
call one constructor of the abstract
class; it may even **have to** call it
(if there is no no-arg constructor
in the abstract class)
In any case, don't forget that if you don't define a constructor, then the compiler will automatically generate one for you (this one is public, has no argument, and does nothing).
|
Can an abstract class have a constructor?
|
[
"",
"java",
"constructor",
"abstract-class",
""
] |
If I have a table like:
```
CREATE TABLE FRED
(
recordId number(18) primary key,
firstName varchar2(50)
);
```
Is there an easy way to clone it's structure (not it's data) into another table of a given name. Basically I want to create table with exactly the same structure, but a different name, so that I can perform some functionality on it. I want to do this in code obviously. Java preferably, but most other languages should be similar.
|
If you're looking a way to find the exact DDL to recreate the table, including the storage clause, you can use
```
select dbms_metadata.get_ddl('TABLE', 'TABLE_NAME', 'SCHEMA_NAME') from dual
```
as described [here](http://www.troygeek.com/articles/ExtractingOracleDDLCommandLine/).
|
CREATE TABLE tablename AS SELECT \* FROM orginaltable WHERE 1=2;
Edit: The WHERE clause prohibits any rows from qualifying.
|
Is there an easy way to clone the structure of a table in Oracle?
|
[
"",
"java",
"database",
"oracle",
""
] |
What does Mozilla Firefox's XPCSafeJSObject wrapper actually do?
[MDC](https://developer.mozilla.org/en/XPConnect_wrappers#XPCSafeJSObjectWrapper)'s documentation is as follows:
> This wrapper was created to address some problems with XPCNativeWrapper. In particular, some extensions want to be able to safely access non-natively-implemented content defined objects (and to access the underlying JavaScript object under an XPCNativeWrapper without its strong behavior guarantees). XPCSJOW act as a buffer between the chrome code.
This doesn't tell me a lot. In particular, I can't tell how accessing objects via XPCSafeObject is any different to accessing them directly.
**Edit**: I understand that the purpose of the wrappers in general is to protect privileged code from unprivileged code. What I don't understand (and doesn't seem to be documented) is *how* exactly XPCSafeJSObject does this.
Does it just drop privileges before accessing a property?
|
The purpose of the wrappers in general is to protect Privileged code when interacting with unprivileged code. The author of the unprivileged code might redefine a JavaScript object to do something malicious, like redefine the getter of a property to execute something bad as a side effect. When the privileged code tries to access the property it would execute the bad code as privileged code. The wrapper prevents this. [This page](https://developer.mozilla.org/en/Safely_accessing_content_DOM_from_chrome) describes the idea.
XPCSafeJSObject provide a wrapper for non-natively implemented JavaScript objects (i.e. not window, document, etc. but user defined objects.)
Edit: For how it's implemented, check out the [source code](http://zenit.senecac.on.ca/wiki/dxr/source.cgi/mozilla/js/src/xpconnect/src/XPCSafeJSObjectWrapper.cpp) (it's not loading completely for me at the moment.) Also search for XPCSafeJSObject on [DXR](http://zenit.senecac.on.ca/wiki/dxr/) for other relevant source files.
|
Actually XPCSafeJSObjectWrapper is used for all content objects, including windows and documents (which is in fact where it's most usually needed.) I believe it was invented mainly to stop XSS attacks automatically turning into privilege escalation attacks (by doing XSS against the browser itself). At least now if an XSS attack is found (and people will unfortunately keep looking) it doesn't compromise the whole browser. It's a natural development from the XPCNativeWrapper which was originally a manual (and therefore prone to accidental misuse by extensions) way for the browser to defend itself from XSS attacks.
|
What does XPCSafeJSObjectWrapper do?
|
[
"",
"javascript",
"firefox",
"firefox-addon",
"gecko",
""
] |
I've been given some code with commenting unlike anything I've come across before:
```
//{{{ Imports
import imports;
//}}}
```
It is the same for each method block,
```
//{{{ above the code block
//}}} below the code block
```
Also see: <http://en.wikipedia.org/wiki/Folding_editor>
|
A quick search for *"triple curly" comment* suggests it's "[Emacs folding mode](http://www.emacswiki.org/cgi-bin/wiki/FoldingMode)".
Or some other code folding marker in any case.
|
[jEdit](http://www.jedit.org) uses {{{ and }}} to mark "explicit" folds.
|
Java: Triple Curly Bracing
|
[
"",
"java",
"coding-style",
"folding",
""
] |
I am debugging some code and have encountered the following SQL query (simplified version):
```
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9
```
I'm getting very strange results from the query and I think its because the first OR is negating the AND operators that are found before it.
This results in getting results back for ads of all types and not just for the type 13.
Each time the query is called there may be a differnt amount of county entities that need to be looked up.
Any help on the correct way to go about this would be appreciated.
|
Put parentheses around the "OR"s:
```
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND
(
ads.county_id = 2
OR ads.county_id = 5
OR ads.county_id = 7
OR ads.county_id = 9
)
```
Or even better, use IN:
```
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2, 5, 7, 9)
```
|
You can try using parentheses around the OR expressions to make sure your query is interpreted correctly, or more concisely, use IN:
```
SELECT ads.*, location.county
FROM ads
LEFT JOIN location ON location.county = ads.county_id
WHERE ads.published = 1
AND ads.type = 13
AND ads.county_id IN (2,5,7,9)
```
|
How to do select from where x is equal to multiple values?
|
[
"",
"sql",
"mysql",
""
] |
i have a server - client application that runs on java 1.3; i want to change to java 1.6 step by step, meaning first few clients, than rest of the clients and finally server...
i was wondering could you direct me to some common problems that can come along and what should i look after?
|
Sun tries to keep a high level of backward-compatibility, so you possibly simply can install the new JVM and restart your application with it.
A document describing the backward-incompatibilities from Java 1.6 with earlier version is [here](http://java.sun.com/javase/6/webnotes/compatibility.html). This document links the compatibility-documents for [Java 1.5](http://java.sun.com/j2se/1.5.0/compatibility.html) and [Java 1.4](http://java.sun.com/javase/compatibility_j2se1.4.html) as well. You probably want to read this documents to learn about possible pitfalls.
Java 1.5 and [Java 1.6](https://jdk.dev.java.net/verifier.html) introduced new class-file-formats. The JVM's will run the old class-files as well, but recompiling your code - especially with JDK 1.6 - will help the new JVM to take advantage of some changes to make your application faster. So you might consider recompiling.
Additionally some new keywords were introduced, namely assert (in 1.4) and enum (in 1.5) (as Yuval already mentioned). If you use these words as identifiers, a recompile will fail, but the old class-files will work. You can provide the switch `-source` to javac to let it compile: '`javac -source 1.3`' will compile the code without *assert* and *enum* as a keyword.
|
Off the top of my head, look for the names `enum` and `assert` in fields and local variables... These words have become keywords in java 1.4 and 5. The java 6 compiler will mark them as compilation errors if it sees them.
Yuval =8-)
|
Changing java version
|
[
"",
"java",
"jvm",
"version",
"compatibility",
"versions",
""
] |
I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?
(I'm not asking about `$('p.foo')` syntax that you see in jQuery and others, but normal variables like `$name` and `$order`)
|
Very common use in **jQuery** is to distinguish **jQuery** objects stored in variables from other variables.
For example, I would define:
```
var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself
```
I find this to be very helpful in writing **jQuery** code and makes it easy to see **jQuery** objects which have a different set of properties.
|
In the 1st, 2nd, and [3rd Edition of ECMAScript](http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262,%203rd%20edition,%20December%201999.pdf), using $-prefixed variable names was explicitly discouraged by the spec except in the context of autogenerated code:
> The dollar sign (`$`) and the underscore (`_`) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.
However, in the next version (the [5th Edition](http://www.ecma-international.org/publications/files/ECMA-ST-ARCH/ECMA-262%205th%20edition%20December%202009.pdf), which is current), this restriction was dropped, and the above passage replaced with
> The dollar sign (`$`) and the underscore (`_`) are permitted anywhere in an *IdentifierName*.
As such, the $ sign may now be used freely in variable names. Certain frameworks and libraries have their own conventions on the meaning of the symbol, noted in other answers here.
|
Why would a JavaScript variable start with a dollar sign?
|
[
"",
"javascript",
"naming-conventions",
""
] |
I have roughly the following code. Could this be made nicer or more efficient? Perhaps using `std::remove_if`? Can you remove items from the map while traversing it? Can we avoid using the temporary map?
```
typedef std::map<Action, What> Actions;
static Actions _actions;
bool expired(const Actions::value_type &action)
{
return <something>;
}
void bar(const Actions::value_type &action)
{
// do some stuff
}
void foo()
{
// loop the actions finding expired items
Actions actions;
BOOST_FOREACH(Actions::value_type &action, _actions)
{
if (expired(action))
bar(action);
else
actions[action.first]=action.second;
}
}
actions.swap(_actions);
}
```
|
You could use erase(), but I don't know how BOOST\_FOREACH will handle the invalidated iterator. The [documentation for map::erase](http://en.cppreference.com/w/cpp/container/map/erase) states that only the erased iterator will be invalidated, the others should be OK. Here's how I would restructure the inner loop:
```
Actions::iterator it = _actions.begin();
while (it != _actions.end())
{
if (expired(*it))
{
bar(*it);
Actions::iterator toerase = it;
++it;
_actions.erase(toerase);
}
else
++it;
}
```
|
A variation of Mark Ransom algorithm but without the need for a temporary.
```
for(Actions::iterator it = _actions.begin();it != _actions.end();)
{
if (expired(*it))
{
bar(*it);
_actions.erase(it++); // Note the post increment here.
// This increments 'it' and returns a copy of
// the original 'it' to be used by erase()
}
else
{
++it; // Use Pre-Increment here as it is more effecient
// Because no copy of it is required.
}
}
```
|
How to filter items from a std::map?
|
[
"",
"c++",
"boost",
"stl",
""
] |
In our application we enable users to print pages. We do this by supplying a button which when click calls the window.print() function.
Some of the pages would look better if they were printed in landscape mode rather than portrait. Is there a way to control the page layout from JavaScript?
Update: Following the advice given here I looked for "css landscape" in google, and found the [following article](http://www.tek-tips.com/faqs.cfm?fid=5803) that showed ways of css-ly defining landscape:
|
You should use a print stylesheet.
```
<link rel="stylesheet" href="print.css" type="text/css" media="print" />
```
More info...
[How to print only parts of a page?](https://stackoverflow.com/questions/224078/how-to-print-only-parts-of-a-page)
Edit: to coerce landscape orientation, apparently the standard is `size: landscape`, but I have no idea how well that's supported across browsers.
|
Do it with CSS by including a print stylesheet thusly:
```
<style type="text/css" media="print">@import url("/inc/web.print.css");</style>
```
|
Can I change page layout when using window.print()?
|
[
"",
"javascript",
""
] |
Ant has a nice way to select groups of files, most handily using \*\* to indicate a directory tree. E.g.
```
**/CVS/* # All files immediately under a CVS directory.
mydir/mysubdir/** # All files recursively under mysubdir
```
More examples can be seen here:
<http://ant.apache.org/manual/dirtasks.html>
How would you implement this in python, so that you could do something like:
```
files = get_files("**/CVS/*")
for file in files:
print file
=>
CVS/Repository
mydir/mysubdir/CVS/Entries
mydir/mysubdir/foo/bar/CVS/Entries
```
|
As soon as you come across a `**`, you're going to have to recurse through the whole directory structure, so I think at that point, the easiest method is to iterate through the directory with os.walk, construct a path, and then check if it matches the pattern. You can probably convert to a regex by something like:
```
def glob_to_regex(pat, dirsep=os.sep):
dirsep = re.escape(dirsep)
print re.escape(pat)
regex = (re.escape(pat).replace("\\*\\*"+dirsep,".*")
.replace("\\*\\*",".*")
.replace("\\*","[^%s]*" % dirsep)
.replace("\\?","[^%s]" % dirsep))
return re.compile(regex+"$")
```
(Though note that this isn't that fully featured - it doesn't support `[a-z]` style glob patterns for instance, though this could probably be added). (The first `\*\*/` match is to cover cases like `\*\*/CVS` matching `./CVS`, as well as having just `\*\*` to match at the tail.)
However, obviously you don't want to recurse through everything below the current dir when not processing a `**` pattern, so I think you'll need a two-phase approach. I haven't tried implementing the below, and there are probably a few corner cases, but I think it should work:
1. Split the pattern on your directory seperator. ie `pat.split('/') -> ['**','CVS','*']`
2. Recurse through the directories, and look at the relevant part of the pattern for this level. ie. `n levels deep -> look at pat[n]`.
3. If `pat[n] == '**'` switch to the above strategy:
* Reconstruct the pattern with `dirsep.join(pat[n:])`
* Convert to a regex with `glob\_to\_regex()`
* Recursively `os.walk` through the current directory, building up the path relative to the level you started at. If the path matches the regex, yield it.
4. If pat doesn't match `"**"`, and it is the last element in the pattern, then yield all files/dirs matching `glob.glob(os.path.join(curpath,pat[n]))`
5. If pat doesn't match `"**"`, and it is NOT the last element in the pattern, then for each directory, check if it matches (with glob) `pat[n]`. If so, recurse down through it, incrementing depth (so it will look at `pat[n+1]`)
|
Sorry, this is quite a long time after your OP. I have just released a Python package which does exactly this - it's called Formic and it's available at the [PyPI Cheeseshop](http://pypi.python.org/pypi/formic). With Formic, your problem is solved with:
```
import formic
fileset = formic.FileSet(include="**/CVS/*", default_excludes=False)
for file_name in fileset.qualified_files():
print file_name
```
There is one slight complexity: default\_excludes. Formic, just like Ant, excludes CVS directories by default (as for the most part collecting files from them for a build is dangerous), the default answer to the question would result in no files. Setting default\_excludes=False disables this behaviour.
|
How would you implement ant-style patternsets in python to select groups of files?
|
[
"",
"python",
"file",
"ant",
""
] |
Are the two events the same or are there differences that we should take note when coding the keyboard presses?
|
My answer here is just based on experimenting with different applications, not programming per se.
Handle the keydown. Let that be the trigger for your logic. That's what the user would expect based on interacting with other applications.
For example, try a key down in Notepad, and you'll see that the DOWN triggers the reaction in Notepad. It doesn't wait for the UP.
|
It doesn't matter if it's .Net or not, it matters what the user expects. Keydown is a good time to respond to the four arrow keys. Character input is a good time to respond to input of visible characters. Keyup is usually a good time to respond to any action that is going to have an effect on a document, but keydown would be better if it's a game where the user wants immediate effect.
|
In .Net, what's the better choice to code key presses in keyboard, key-up or keydown?
|
[
"",
"c#",
".net",
"vb.net",
"winapi",
""
] |
I'm trying to use stl algorithm for\_each without proliferating templates throughout my code. std::for\_each wants to instantiate MyFunctor class by value, but it can't since its abstract. I've created a functor adapter class which passes a pointer around and then derefernces it when appropriate.
My Question:
Does the STL or Boost already have such an adapter class? I don't want to have to reinvent the wheel!
```
struct MyFunctor {
virtual ~MyFunctor() {}
virtual void operator()(int a) = 0;
}
namespace {
template<typename FunctorType, typename OperandType> struct
FunctorAdapter
{
FunctorAdapter(FunctorType* functor) : mFunctor(functor) {}
void operator()(OperandType& subject)
{
(*mFunctor)(subject);
}
FunctorType* mFunctor;
}; }
void applyToAll(MyFunctor &f) {
FunctorHelper<MyFunctor, int> tmp(&f);
std::for_each(myvector.begin(), myvector.end(), tmp); }
```
Cheers,
Dave
|
tr1::ref may help you here --- it's meant to be a reference wrapper so that you can pass normal objects by reference to bind or function objects (even abstract ones) by reference to standard algorithms.
```
// requires TR1 support from your compiler / standard library implementation
#include <functional>
void applyToAll(MyFunctor &f) {
std::for_each(
myvector.begin(),
myvector.end(),
std::tr1::ref(f)
);
}
```
However, NOTE that compilers without decltype support *MAY* reject passing a reference to an abstract type... so this code may not compile until you get C++0x support.
|
You could use the function adapters (and their shims) from `functional`.
```
#include <functional>
using namespace std;
for_each( vec.begin(), vec.end(), :mem_fun_ptr( &MyClass::f ) );
```
If your container contains pointers-to-objects, use `mem_fun_ptr`, else use `mem_fun`. Next to these, there are wrappers for member functions that take 1 argument: `mem_fun1_ptr` and `mem_fun1`.
@Evan: indeed, you could call the member function with the same argument for each object. The first argument of the `mem_fun1` wrappers is the `this` pointer, the second is the member function argument:
```
for_each( vec.begin(), vec.end(), bind2nd( mem_fun_ptr( &MyClass::f ), 1 ) );
```
With more arguments, it becomes more readable to create a loop yourself, or create a custom functor that has const member variables representing the arguments.
|
Polymorphic functors in std::for_each
|
[
"",
"c++",
"stl",
"polymorphism",
""
] |
Each of my clients can have many todo items and every todo item has a due date.
What would be the query for discovering the next undone todo item by due date for each file? In the event that a client has more than one todo, the one with the lowest id is the correct one.
Assuming the following minimal schema:
```
clients (id, name)
todos (id, client_id, description, timestamp_due, timestamp_completed)
```
Thank you.
|
I haven't tested this yet, so you may have to tweak it:
```
SELECT
TD1.client_id,
TD1.id,
TD1.description,
TD1.timestamp_due
FROM
Todos TD1
LEFT OUTER JOIN Todos TD2 ON
TD2.client_id = TD1.client_id AND
TD2.timestamp_completed IS NULL AND
(
TD2.timestamp_due < TD1.timestamp_due OR
(TD2.timestamp_due = TD1.timestamp_due AND TD2.id < TD1.id)
)
WHERE
TD2.id IS NULL
```
Instead of trying to sort and aggregate, you're basically answering the question, "Is there any other todo that would come before this one?" (based on your definition of "before"). If not, then this is the one that you want.
This should be valid on most SQL platforms.
|
This question is the classic ***pick-a-winner for each group***. It gets posted about twice a day.
```
SELECT *
FROM todos t
WHERE t.timestamp_completed is null
and
(
SELECT top 1 t2.id
FROM todos t2
WHERE t.client_id = t2.client_id
and t2.timestamp_completed is null
--there is no earlier record
and
(t.timestamp_due > t2.timestamp_due
or (t.timestamp_due = t2.timestamp_due and t.id > t2.id)
)
) is null
```
|
"Simple" SQL Query
|
[
"",
"sql",
"sql-server",
""
] |
I have the following SQL-statement:
```
SELECT DISTINCT name FROM log WHERE NOT name = '' AND name LIKE '%.EDIT%';
```
It works fine on Postgres (returns all different names from log, which aren't empty and contain the string '.EDIT'). But on Oracle this statement doesn't work. Any idea why?
|
```
SELECT DISTINCT name FROM log WHERE NOT name = '' AND name LIKE '%.EDIT%';
```
1) Oracle treats '' as NULL, which means the comparison "NOT name = ''" is never true or false; use "IS NOT NULL" instead. But...
2) The second condition "name LIKE '%.EDIT%' will not match an empty string anyway, making the first condition redundant.
So re-write as:
```
SELECT DISTINCT name FROM log WHERE name LIKE '%.EDIT%';
```
|
The empty string in Oracle is equivalent to NULL, causing the comparison to fail.
Change that part of the query to NAME IS NOT NULL
|
Why won't this SQL statement work?
|
[
"",
"sql",
"oracle",
""
] |
```
$doba = explode("/", $dob);
$date = date("Y-m-d", mktime(0,0,0, $doba[0], $doba[1], $doba[2]));
```
The above code turns any date i pass through into 1999-11-30 and i know it was working yesterday. Date is correct when I echo $doba. Anyone have any ideas?
Cheers
|
What is the format of `$doba`? Remember `mktime`'s syntax goes hour, minute, second, **month, day year** which can be confusing.
Here's some examples:
```
$doba = explode('/', '1991/08/03');
echo(date('Y-m-d', mktime(0,0,0, $doba[1], $doba[2], $doba[0]);
$doba = explode('/', '03/08/1991');
echo(date('Y-m-d', mktime(0,0,0, $doba[1], $doba[0], $doba[2]);
```
|
or even easier: `$date = date('Y-m-d', strtotime($dob))`
|
PHP mangles my dates
|
[
"",
"php",
"date",
""
] |
What is the upper limit for an autoincrement primary key in SQL Server?
What happens when an SQL Server autoincrement primary key reaches its upper limit?
|
Joel's answer is correct, it is the upper limit of whatever datatype you use.
Here's an example of two of them:
* int: 2^31-1 (2,147,483,647)
* bigint: 2^63-1 (9,223,372,036,854,775,807)
I have actually hit the limit at a job I worked at. The actual error is:
```
Msg 8115, Level 16, State 1, Line 1
Arithmetic overflow error converting IDENTITY to data type int.
Arithmetic overflow occurred.
```
There are a couple fixes to this I can think of off the top of my head. Number 1 is probably very hard and not very likely, number 2 is easy, but will probably cause problems in your code base.
1. If the identity column doesn't matter to you (it's not a Foreign Key, etc.) then you can just reseed the database and reset the identity column.
2. Change your identity column to a bigger number. So for example if you've overflowed an int, change your identity column to a big int. Good luck overflowing that :)
There are probably other fixes, but there is no magic bullet easy one. I just hope this doesn't happen in a table that is the center of a bunch of relationships, because if it does, you're in for a lot of pain. It's not a hard fix, just a tedious and long one.
|
It depends on the datatype. If you use bigint, you're unlikely to ever overflow. Even a normal int gives you a couple billion rows. I've never overflowed, so I can't tell you what happens if you do.
|
Upper limit for autoincrement primary key in SQL Server
|
[
"",
"sql",
"sql-server",
"auto-increment",
""
] |
How can I play audio (it would be like a 1 second sound) from a Python script?
It would be best if it was platform independent, but firstly it needs to work on a Mac.
I know I could just execute the `afplay file.mp3` command from within Python, but is it possible to do it in raw Python? I would also be better if it didn't rely on external libraries.
|
You can find information about Python audio here: <http://wiki.python.org/moin/Audio/>
It doesn't look like it can play .mp3 files without external libraries. You could either convert your .mp3 file to a .wav or other format, or use a library like [PyMedia](http://pymedia.org/).
|
Try [playsound](https://github.com/TaylorSMarks/playsound) which is a Pure Python, cross platform, single function module with no dependencies for playing sounds.
Install via pip:
```
$ pip install playsound
```
Once you've installed, you can use it like this:
```
from playsound import playsound
playsound('/path/to/a/sound/file/you/want/to/play.mp3')
```
|
Play audio with Python
|
[
"",
"python",
"audio",
""
] |
An abstract class can only be used as a base class which is extended by some other class, right? The constructor(s) of an abstract class can have the usual access modifiers (public, protected, and private (for internal use)). Which of `protected` and `public` is the correct access modifier to use, since the abstract type seems to indicate that technically a public constructor will act very much protected? Should I just use protected on all my constructors?
|
An abstract class's constructor can only be called from the implementation's constructor, so there is no difference between it being public or protected. E.g.:
```
public class Scratch
{
public static abstract class A
{
public A( int i ) {}
}
public static class B extends A
{
private B() { super(0); };
}
}
```
|
If this behavior is true, and I'm not sure it is, you should always use the most restricted scope available for your application to function. So in that case, I would recommend using protected.
|
Abstract class constructor access modifier
|
[
"",
"java",
""
] |
I have a menu with an animation going on, but I want to disable the click while the animation is happening.
```
<div></div>
<div></div>
<div></div>
$("div").click(function() {
$(this).animate({height: "200px"}, 2000);
return false;
});
```
However, I want to disable all the buttons while the event is happening, AND disable the div that was clicked.
I was thinking of adding a class to the div that's clicked and putting the click only on the divs without that class:
```
$("div").not("clicked").click(function() {
$(this).animate({height: "200px"}, 2000).addClass("clicked");
return false;
});
```
But this doesn't appear to work (I think it does logically)?
Any help appreciated.
Cheers,
Steve
|
```
$("div").click(function() {
if (!$(this).parent().children().is(':animated')) {
$(this).animate({height: "200px"}, 2000);
}
return false;
});
```
|
You could do something like this...
```
$(function() {
$("div").click(function() {
//check to see if any of the divs are animating
if ($("div").is(":animated")) {
alert("busy");
return;
}
//whatever your animation is
var div = $(this);
div.slideUp(3000, function(){ div.slideDown(1000); });
});
});
```
This will animate the click so long as any div is not currently animating. I'm most likely put all those divs in a container and not just simply refer to div, since it could affect a lot more on the page than just your menu,
|
Using jQuery, how do I disable the click effect on the current tab?
|
[
"",
"javascript",
"jquery",
""
] |
I want to increment a cookie value every time a page is referenced even if the page is loaded from cache. What is the "best" or most concise way to implement this?
|
Stolen from <http://www.quirksmode.org/js/cookies.html#script>
```
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toUTCString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
```
using it:
```
var oldCount = parseInt(readCookie('hitCount'), 10) || 0;
createCookie('hitCount', oldCount + 1, 7);
```
as pointed out in the comments, you should cast to an int since cookies are stored and returned as strings. Using `foo++` or `++foo` will actually cast for you, but it's safer to know exactly what you're working with:
```
var x = "5"; // x = "5" (string)
x += 1; // x = "51" (string!)
x += 5; // x = "515" (string!)
++x; // x = 516 (number)
```
|
Most of the old cookie handling functions I've seen use simple string manipulations for storing an retrieving values, like [this](http://www.w3schools.com/JS/js_cookies.asp) example, you can use other libraries, like [cookie-js](http://code.google.com/p/cookie-js/), a small *(< 100 lines)* utility for cookie access.
I personally use jQuery on my projects, and I use the [jQuery Cookie Plugin](http://plugins.jquery.com/cookie/), it's really simple to use:
```
var cookieName = "increment";
if ($.cookie(cookieName) == null){
$.cookie(cookieName, 1, { expires: 10 });
}else{
var newValue = Number($.cookie(cookieName)) + 1;
$.cookie(cookieName, newValue, { expires: 10 });
}
```
|
What is the "best" way to get and set a single cookie value using JavaScript
|
[
"",
"javascript",
"cookies",
""
] |
What I want to do is scroll down the window when I expand elements in my page.
The effect I am trying to achieve is like the Stack Overflow comments. If it expands beyond the page, it scrolls down to fit all the comments in the window.
What is the best way of doing this?
Edit: I am using JQuery.
|
This jQuery plugin worked well for me:
<http://demos.flesler.com/jquery/scrollTo/>
|
You can do it nicely with [Scriptaculous](http://script.aculo.us/) (built on top of [Prototype](http://prototypejs.org)):
```
new Effect.ScrollTo('someDiv',{...some parameters...})
```
It gives you finer control than Prototype alone (delay before start, duration and callback events (such as afterFinish) that allow you to trigger other effects or whatever you choose. You can make it scroll smoothly and nicely, so the page doesn't suddenly jump.
|
What is the best way of scrolling the browser window for expanding elements?
|
[
"",
"javascript",
"window",
"scroll",
""
] |
I've got a little problem that's slightly frustrating. Is it possible to set a default value when deserializing xml in C# (.NET 3.5)? Basically I'm trying to deserialize some xml that is not under my control and one element looks like this:
```
<assignee-id type="integer">38628</assignee-id>
```
it can also look like this:
```
<assignee-id type="integer" nil="true"></assignee-id>
```
Now, in my class I have the following property that should receive the data:
```
[XmlElementAttribute("assignee-id")]
public int AssigneeId { get; set; }
```
This works fine for the first xml element example, but the second fails. I've tried changing the property type to be int? but this doesn't help. I'll need to serialize it back to that same xml format at some point too, but I'm trying to use the built in serialization support without having to resort to rolling my own.
Does anyone have experience with this kind of problem?
|
It looks like your source XML is using xsi:type and xsi:nil, but not prefixing them with a namespace.
What you could do is process these with XSLT to turn this:
```
<assignees>
<assignee>
<assignee-id type="integer">123456</assignee-id>
</assignee>
<assignee>
<assignee-id type="integer" nil="true"></assignee-id>
</assignee>
</assignees>
```
into this:
```
<assignees xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<assignee>
<assignee-id xsi:type="integer">123456</assignee-id>
</assignee>
<assignee>
<assignee-id xsi:type="integer" xsi:nil="true" />
</assignee>
</assignees>
```
This would then be handled correctly by the XmlSerializer without needing any custom code. The XSLT for this is rather trivial, and a fun exercise. Start with one of the many "copy" XSLT samples and simply add a template for the "type" and "nil" attributes to ouput a namespaced attribute.
If you prefer you could load your XML document into memory and change the attributes but this is not a good idea as the XSLT engine is tuned for performance and can process quite large files without loading them entirely into memory.
|
You might want to take a look at the [OnDeserializedAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializedattribute.aspx),[OnSerializingAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializingattribute.aspx), [OnSerializedAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.onserializedattribute.aspx), and [OnDeserializingAttribute](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute.aspx) to add custom logic to the serialization process
|
Is it possible to set a default value when deserializing xml in C# (.NET 3.5)?
|
[
"",
"c#",
"xml",
"serialization",
""
] |
Currently using System.Web.UI.WebControls.FileUpload wrapped in our own control.
We have licenses for Telerik. I wanted to know if anyone had experience with that or could suggest a better one?
Some criteria to be measured by
* validation
* peformance
* multiple files
* localisation ([browse](https://stackoverflow.com/questions/94316/how-to-change-the-text-of-the-browse-button-in-the-fileupload-control-systemweb) is difficult)
* security
|
Personally, if you have the Telerik controls I would give them a shot. I've found that they are very helpful, and the user experience is good. Their upload control is quite nice.
|
I just posted about this [in another question](https://stackoverflow.com/questions/254419/aspnet-image-uploading-with-resizing#254812), but if you use this ActiveX control you will be able to process images quickly and efficiently. The component will actually resize the images on the client machine before sending them. This reduces unnecessary bandwidth and transfers multiple images at one time.
|
Can you recommend alternative FileUpload control for asp.net-mvc?
|
[
"",
"c#",
"asp.net-mvc",
"file-upload",
"web-controls",
""
] |
I need to integrate a email client in my current python web app.
Anything available?
L.E.: I'm building my app on top of CherryPy
|
Looking up [webmail](http://pypi.python.org/pypi?%3Aaction=search&term=webmail&submit=search) on [pypi](http://pypi.python.org/pypi) gives [Posterity](http://pypi.python.org/pypi/Posterity/).
There is very probably some way to build a webmail with very little work using [Zope3](http://www.zope.org/Products/Zope3) components, or some other CMS.
I guess if you are writing a webapp, you are probably using one of the popular frameworks. We would need to know which one to give a more specific answer.
|
For others who might find this thread, check out [Mailpile](http://www.mailpile.is/). I haven't used it yet, it is a python-based mail client, and I am sure it could be modified to work as a webmail app as well.
|
Are there any web based email clients written in python?
|
[
"",
"python",
"email",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.